Skip to content

Show tokens, cache use and estimated cost after each reply - #583

Merged
neuromechanist merged 7 commits into
developfrom
feature/issue-582-usage-display
Oct 7, 2026
Merged

neuromechanist merged 7 commits into
developfrom
feature/issue-582-usage-display

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Closes #582.

Each reply now tells the reader what it used and cost, in the API, the widget and the CLI, for every request (platform-paid and bring-your-own-key).
OSA already counted these tokens and priced them for the metrics database and Langfuse; nothing reached the reader.

What the reader sees

  • Widget: one line under each finished reply, between its sources and the feedback buttons, for example 1,240 in (980 cached), 310 out, about $0.0021.
    A reply that runs code in the browser spans several runs; the line appears once the reply is whole and shows their sum.
    It is kept in the saved history, so a reload shows it again.
  • CLI: osa ask and osa chat print Usage: ... with the same wording to stderr, streamed or not, so a pipe still carries the answer alone.
  • API: a usage object on the done event of /ask and /chat, on the tool_request event that ends a browser run, and on AskResponse and ChatResponse:
    input_tokens (cached ones included), output_tokens, cache_read_tokens, cache_creation_tokens, estimated_cost (US dollars, null for a model with no price) and partial.
    On a stream the object covers one run, so a client that drives /chat/resume itself adds up the runs; the widget does.

Being honest about the numbers

  • partial. If a model run of a reply reported no tokens, the others' figures are a lower bound.
    The server sets partial, the widget also notices a missing run on either side of a sum, and both widget and CLI say at least ....
  • No usage is not zero. usage is null when the provider reported no tokens, not a free reply.
  • Refused, not shown wrong. ReplyUsage rejects negative counts, a negative or non-finite cost, and cached tokens above the input (an adapter counting the way Anthropic's own API does).
    That logs a warning with the counts and ids and sends no usage; the answer is never lost over it.
  • Identical text in Python and JavaScript. Both formatters round half up on whole micro-dollars with integer arithmetic.
    I compared their output for every whole micro-dollar from $0 to $3 (3,000,001 values): identical.
    A shared table, tests/fixtures/usage_lines.json, drives both languages' tests, including ties and malformed input.

Decisions to review

  • OpenRouter is left out for now, as scoped in Show tokens, cache use and estimated cost after each reply #582: usage is null for any request served through it.
    The gate is model in OFFERED_MODELS, which holds because OpenRouter requests carry the OpenRouter slug; a test pins that no offered id is also a slug.
  • The cost is the dashboard's estimate, not an invoice.
    Cache writes are priced at the five-minute rate whatever ANTHROPIC_CACHE_TTL says, so a deployment on 1h understates a cold-cache reply's write cost.
    I kept the reader's number equal to the dashboard's rather than make them disagree.
  • The tokens of a model call that failed and was retried (Retry a Luna stream cut short once, and tell the reader their model is unavailable #581) are not counted, because a failed call reports none.
  • A reply that ends in an error shows no usage, though its earlier runs spent tokens.
  • Langfuse is unchanged: it already receives each model call's usage through its callback handler.

Testing

  • Python: the new tests drive the real graph and both streams over scripted adapter chunks for Bedrock and Anthropic, the real Bedrock stream parser (including a retried stream and its cache fields), the real /chat then /chat/resume endpoints, the non-streaming responses, and the CLI over staged HTTP.
    Costs are worked out by hand from the price table.
  • Widget: the real widget in happy-dom, with staged streams and JSON responses, saved-history round trips and forged histories.
  • Mutations that each fail a test: cache read and write swapped in three places, partial handling removed, the zero-token gate, a saved-history leak, the render itself, and the half-up rounding.
  • Review: every aspect (code, tests, error handling, comments, types, simplification) ran on this branch and its findings are applied.
  • Locally, tests/test_api, test_metrics, test_cli, test_core and test_frontend pass except the 19 test_chat_resume_endpoint.py tests that fail with 401 identically on a clean checkout of develop.
    Every Bun widget suite passes.

The streams and the request metrics already count every request's tokens and
price them; the reader never saw any of it. The done event of /ask and /chat,
the tool_request event that ends a browser-execution run, and the responses to
requests that are not streamed now carry a usage object: input, output, cache
read and cache write tokens, and an estimated cost in USD from the price table.

It is null when the provider reported no usage (not a free reply) and for
models OSA does not offer itself, which leaves OpenRouter out for now.

Refs #582.

Tested: new tests drive the real streams and graph for Bedrock and Anthropic
through scripted adapter chunks, with the cost worked out by hand; the API tests
fail when the wiring is removed. tests/test_api (minus the known chat-resume
401s) and tests/test_metrics pass.
osa ask and osa chat, streamed and not, print one line under the answer from the
usage object the server now sends, for example
"1,240 in (980 cached), 310 out, about $0.0021". It goes to stderr, so stdout
stays the answer alone for a pipe, and is left out when the server sent none.
The wording is tested against a table shared with the widget.

Refs #582.

Tested: respx-staged streams and responses through the real client; the four
printing tests fail without the change. tests/test_cli passes (177).
The widget reads the usage object from a reply's done event and shows one line
under the reply, between its sources and the feedback buttons, for example
"1,240 in (980 cached), 310 out, about $0.0021". A reply that runs code in the
browser spans several runs: the earlier runs' usage is kept aside from their
tool_request events and added to the last run's on done, so the line appears
once the reply is whole and shows the sum. The message keeps it, so a reload
shows it again. The wording is tested against the table the CLI uses.

Refs #582.

Tested: unit cases for the line, the sum and the done reducer in
test-streaming.js (99); DOM cases in test-widget-paced-streaming.js for a
single run, no usage, and a two-run reply (266); the render fails the DOM test
when removed. Every other widget suite and the Python frontend guard tests pass.
The usage object is built inside the done event. A count a provider reported
badly would have raised there and ended the stream with an error, after the
answer was written. It now logs a warning and sends no usage, as
_extract_token_usage does for the metrics.

Refs #582.

Tested: a fractional token count, which pydantic rejects, gives no usage and one
warning. tests/test_api/test_reply_usage.py passes (16).
…e can be

Review findings on the usage display:
- a reply some of whose model runs reported no tokens showed the others' figures
  as its total. The server now sends partial, the widget notices a missing run
  on either side of a sum, and both the widget and the CLI say "at least"
- ReplyUsage refuses negative counts, a negative or non-finite cost, and cached
  tokens above the input (an adapter counting the way Anthropic's own API does)
  instead of showing a wrong figure; the failure is logged at WARNING with the
  counts and ids, and any other failure at ERROR
- the widget and the CLI print identical cost text for every whole micro-dollar
  from 0 to 3,000,000 (checked), where toFixed and Python's formatter rounded ties
  differently; ties and non-ties are rows of the shared table
- the widget shows usage from a response that is not streamed, keeps only the
  fields it reads from the server and from saved history, and reports an
  unreadable usage once on the console (the CLI at debug level)
- the tool_request contract (ToolRequestEvent, to_request_event) carries usage
- documented: usage is per run on a stream, null for OpenRouter-routed requests
  (pinned to the OpenRouter slugs), cache writes are priced at the five-minute
  rate, and a failed attempt's tokens are not counted

Refs #582.

Tested: 3440 Python tests pass in tests/test_api, test_metrics, test_cli,
test_core and test_frontend (19 chat-resume failures, identical on develop);
every widget suite passes (test-streaming 115, paced-streaming 278); the partial
and missing-first-run handling fail when removed.
…e widget

- the router's three helpers take their counts by keyword and decide partial in
  one place; the non-streaming helper takes the request like its neighbors
- the widget cleans a usage once and draws from the clean object, with the
  console warning at the one place untrusted data enters (so it is a real path,
  not only a test hook); _runs is _usageRuns
- the CLI treats a negative count, and a negative or non-finite cost, the way the
  widget does (a NaN cost no longer crashes it after the answer is printed);
  the shared table gained rows that pin it
- both cost formatters use the same if/elif chain and digit arithmetic, and still
  print identical text for every whole micro-dollar from 0 to 3,000,000
- tests: shared serve and ask helpers, imports hoisted, the fixture row looked up
  by name

Refs #582.

Tested: 253 usage tests pass (API, metrics, CLI) and every widget suite passes
(test-streaming 121, paced-streaming 279); the Python and JS cost text was compared
across 3,000,001 values.
- cache reads and writes in their own fields on the ask stream, the chat stream,
  the tool_request event and both non-streaming responses (a swap of the two
  passed the suite), including the per-lifetime cache write the real Anthropic
  adapter reports
- /chat/resume run 2 reports its own usage, not run 1's added, through the real
  endpoints
- a reply that was tried again reports the second try's usage, with the cache
  fields the real Bedrock stream parser gives, and agrees with the request's row
  in the metrics
- the widget's own saved history round-trips usage, and a reply whose second run
  failed saves nothing kept aside between runs
- reply_usage keeps a run with only input or only output; the CLI is tested
  against a server that sends no usage key, and its batch paths against stdout
  and stderr separately; the test cost uses the module's cache multipliers

Refs #582.

Tested: 373 Python usage tests pass and every widget suite passes
(paced-streaming 283); five mutants (swapped cache fields in three places, the
zero gate, a saved-history leak) each fail a test.
@neuromechanist neuromechanist added feature New feature or enhancement widget Related to frontend widget cost-management Cost tracking and optimization labels Oct 7, 2026
@github-actions

github-actions Bot commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

Preview Deployment

Name Link
Preview URL https://feature-issue-582-usage-disp-demo.osc.earth
Branch feature/issue-582-usage-display
Commit a602da3

This preview will be updated automatically when you push new commits.

@neuromechanist
neuromechanist merged commit a3068b7 into develop Oct 7, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-582-usage-display branch October 7, 2026 01:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cost-management Cost tracking and optimization feature New feature or enhancement widget Related to frontend widget

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant