Repository navigation
Show tokens, cache use and estimated cost after each reply - #583
Merged
Merged
Conversation
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.
Contributor
Preview Deployment
This preview will be updated automatically when you push new commits. |
10 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
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.
osa askandosa chatprintUsage: ...with the same wording to stderr, streamed or not, so a pipe still carries the answer alone.usageobject on thedoneevent of/askand/chat, on thetool_requestevent that ends a browser run, and onAskResponseandChatResponse:input_tokens(cached ones included),output_tokens,cache_read_tokens,cache_creation_tokens,estimated_cost(US dollars, null for a model with no price) andpartial.On a stream the object covers one run, so a client that drives
/chat/resumeitself 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 sayat least ....usageis null when the provider reported no tokens, not a free reply.ReplyUsagerejects 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.
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
usageis 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.Cache writes are priced at the five-minute rate whatever
ANTHROPIC_CACHE_TTLsays, so a deployment on1hunderstates a cold-cache reply's write cost.I kept the reader's number equal to the dashboard's rather than make them disagree.
Testing
/chatthen/chat/resumeendpoints, the non-streaming responses, and the CLI over staged HTTP.Costs are worked out by hand from the price table.
partialhandling removed, the zero-token gate, a saved-history leak, the render itself, and the half-up rounding.tests/test_api,test_metrics,test_cli,test_coreandtest_frontendpass except the 19test_chat_resume_endpoint.pytests that fail with 401 identically on a clean checkout of develop.Every Bun widget suite passes.