Expand description
Real provider-reported token usage extraction.
The proxy already rewrites requests; this module reads the response so the dashboard/terminal can show measured cost (the user’s real provider bill) instead of an estimate. All three providers report the exact model and the billed token breakdown — including prompt-cache reads/writes — in the final event of a stream (or the body of a non-streaming response):
- Anthropic:
message_startcarries model + input/cache tokens, the finalmessage_deltacarriesoutput_tokens. Non-streaming: oneusageobject. - OpenAI Responses: the
response.completedevent nestsresponse.usage. - OpenAI Chat Completions: the final chunk carries
usage(needsstream_options.include_usage, which the proxy injects). - Gemini: every chunk carries
usageMetadata; the last one has the totals.
RealUsage normalizes every provider onto the four billable buckets that
crate::core::gain::model_pricing::ModelCost::estimate_usd prices:
uncached input, output (incl. reasoning/thoughts), cache-read, cache-write.
Structs§
- Real
Usage - One LLM turn’s real, provider-reported usage, normalized to billable buckets.
- Scanner
- Incrementally extracts
RealUsagefrom a response stream (or a full body).
Enums§
Functions§
- gemini_
model_ from_ path - Extracts the model from a Gemini request path
(
/v1beta/models/{model}:generateContent). ReturnsNonefor other paths. - tee_
stream - Wraps a response byte stream so every chunk is forwarded byte-for-byte
while a
Scannerobserves it; on stream end the merged usage is recorded. Memory overhead is one buffered SSE line, never the whole response.