Skip to content

Studio: export token usage from Profile stats as CSV - #14213

Merged
danielhanchen merged 4 commits into
mainfrom
studio-usage-csv-export
Oct 19, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
studio-usage-csv-export

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Adds an Export CSV button to Settings > Profile > Your stats that downloads the token usage behind the stats, one row per chat response or API request.

Fixes #7214 (the export part; the usage limiter in that issue is not part of this PR).

What the file looks like

time,date,source,model,prompt_tokens,completion_tokens,total_tokens,cached_tokens
2026-03-04 12:00:10,2026-03-04,chat,unsloth/gpt-oss-20b,100,25,125,5
2026-03-04 13:00:00,2026-03-04,api,unsloth/api-model,40,10,50,0
  • time / date are in the browser's timezone, the same bucketing the activity chart uses, so a spreadsheet pivot by day, month, year or model matches the Profile numbers.
  • source is chat (Studio chat) or api (authenticated local API requests).
  • Rows are oldest first. Responses with no recorded tokens are skipped.

How

  • GET /api/profile/stats/export (new, read-only) returns text/csv with an attachment filename.
  • The rows come from the same two folds that already compute the Profile stats (_fold_messages, _fold_api_usage), through an optional per-row callback. No new tables, no second parser, and the counting rules (forks, compare mode panes, llama.cpp serverTimings fallback) stay identical, so the CSV total equals the "Lifetime tokens" figure.
  • Scoping is the same as /api/profile/stats: chat history is install-wide (those rows have no owner), API receipts only for the calling subject, and the per-account database under multi-user installs.
  • Model ids are client-supplied, so a value starting with =, +, -, @ is prefixed with ' to stop it running as a spreadsheet formula.
  • Frontend saves through downloadFile, which uses the native save dialog in Unsloth Desktop and a normal download in the browser. The button only shows when there is usage to export.
  • New exportCsv / exportError strings are added to all 14 locales (i18n:check:strict passes).

Nothing else on the Profile page changes; the stats request and payload are unchanged.

Tests

  • tests/test_profile_stats.py: exported rows (ordering, local time, chat vs api, formula escaping), the other subject's API receipts excluded, CSV token sum equals compute_profile_stats totalTokens, repeat export byte-identical, header-only file for empty history.
  • tests/test_api_profile_usage_routes.py: the route forwards the authenticated subject and timezone and responds as a CSV attachment.
python -m pytest tests/test_profile_stats.py tests/test_api_profile_usage_routes.py tests/test_account_chat_settings.py -q
152 passed

Frontend: npm run typecheck and npm run i18n:check:strict clean.

Before / after

Settings > Profile > Your stats on the merge base vs this branch, with the same seeded chat history (two replies, 4,500 tokens). After: the Export CSV button sits beside the heading, and the browser saves unsloth-token-usage-<date>.csv with 2 rows summing to 4,500 tokens, equal to the Profile total. The export endpoint answers 404 before and 200 after.

Profile stats before and after

@danielhanchen danielhanchen self-assigned this Oct 19, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-19T09:44:57.793374Z e9f936e New commits
🔒 Security Review ⚠️ Failed 2026-10-19T07:34:04.833642Z 2a02d80 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2a02d80248

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

{hasUsage ? <ExportUsageButton /> : null}
</header>

<StatsHighlights stats={stats} />

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Hide export when no token rows exist

When a profile contains only user messages or assistant messages from before token metadata was recorded, stats.totals.messages makes hasUsage true even though every candidate row has zero token counts and export_usage_csv() filters all of them out. The newly displayed button therefore downloads a header-only file; gate it on the token fields that the exporter uses (prompt, completion, or total tokens) rather than the general message-based hasUsage flag.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping this as is: a header-only file is the correct export for a history with no recorded token counts, nothing is lost or wrong, and the button already hides when there is no usage at all.

Comment on lines +797 to +801
rows: list[tuple[int, str, str, int, int, int, int]] = []

def collect(*row) -> None:
if row[3] or row[4] or row[5]:
rows.append(row)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Stream unbounded lifetime exports

For accounts with long-lived chat or API histories, this retains every exported record in rows and then builds a second full in-memory CSV in StringIO; Starlette subsequently encodes another complete response buffer, while the frontend reads it as a string and Desktop encodes it again for IPC. Since the lifetime history has no row cap, sufficiently large but valid profiles can exhaust backend or Desktop memory during export; emit the CSV through a streaming response or a bounded temporary-file path and use the existing streaming download infrastructure.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Measured on a synthetic 30k-response history: 1.77 MB of CSV in about 1 s, so even the 260k-message history noted in the stats route is roughly 15 MB. The Profile stats fold already walks the same history in memory, so this does not add a new memory ceiling worth a streaming path.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 6d4737a0cc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Comprehensive Token Usage Analytics & Global Usage Guardrails

1 participant