Repository navigation
feat: count cache writes, reasoning tokens, usage per model and durations - #139
Conversation
e04dfa9 to
12f076e
Compare
gopaljigaur
left a comment
There was a problem hiding this comment.
Checked against LiteLLM 1.101.0 and 1.105.1: prompt_tokens_details.cache_write_tokens is the canonical field in both, mirrored from Anthropic's and Bedrock's cache_creation_input_tokens, and both add cache reads and writes into prompt_tokens, so cached_tokens and cache_write_tokens are disjoint subsets of prompt_tokens on Anthropic and OpenAI alike, with no double count. Names match Pydantic AI (cache_write_tokens), LiteLLM and the OpenAI Agents SDK (reasoning_tokens). The new tests fail on main (14 failures) and pass here; origin/main (with #136) is an ancestor of the head; pytest -n 4, pre-commit, mypy, the site build and CI pass; the confidentiality and dash checks are clean. Three findings inline.
… durations Usage gains cache_write_tokens and reasoning_tokens, read from the prompt_tokens_details and completion_tokens_details LiteLLM normalizes, and api_duration, the seconds from each completion's request to its whole response. RunResult gains usage_by_model, keyed by the configured model that made each completion, so fallback models, subagents on other models and a compaction model each keep their own usage, and duration, the run's wall-clock seconds.
12f076e to
d279bae
Compare
What changed
Usagegains three fields, all summed by+and so by runs, nested runs and sessions:cache_write_tokens: prompt tokens written to the provider's cache, from LiteLLM'sprompt_tokens_details.cache_write_tokens(its canonical field since before our 1.101.0 floor, mirrored from Anthropic's and Bedrock'scache_creation_input_tokens).reasoning_tokens: fromcompletion_tokens_details.reasoning_tokens, which LiteLLM fills for OpenAI, Anthropic, Bedrock, Gemini and xAI.api_duration: seconds from each completion's request to its whole response, retries included, timed withtime.perf_counter()around the call. A paced stream (stream(),astream(),stream_events(),astream_events()) reads only a few chunks ahead of the caller, so the caller's reading time counts too; the field and the docs say so. LiteLLM's own_response_msis missing from assembled streams, so it is not used.cached_tokenskeeps its name. As LiteLLM reports them, cached and cache-written tokens are counted inprompt_tokens, and reasoning tokens incompletion_tokens.RunResultgains:usage_by_model: Dict[str, Optional[Usage]], keyed by the configured model that made each completion. A refused completion counts under the model that refused, the answer under the fallback, a subagent's completions under its model in every run above it, and a compaction summary under the summarizing model. An entry isNoneonce one of that model's completions reported no usage, like the run's total.duration: the run's wall-clock seconds, tool calls included.Telemetry:
chatspans setgen_ai.usage.cache_read.input_tokens,gen_ai.usage.cache_write.input_tokensandgen_ai.usage.reasoning.output_tokenswhen the response reports them. Span durations already cover latency.These are the names on main of open-telemetry/semantic-conventions-genai, where the GenAI conventions now live. That repository has no release or tag yet: its
changelog.d/440.breaking.mdrenamesgen_ai.usage.cache_creation.input_tokens(what theopentelemetry-semantic-conventions0.62b1 package still ships) togen_ai.usage.cache_write.input_tokens, unreleased. With no release to follow, main's names are the current ones, so the spans use those instead of the name about to go.gen_ai.usage.reasoning.output_tokensis released, in semantic-conventions v1.41.0.Decisions
reasoning_tokens(OpenAI Agents SDK, Vercel AI SDK, LiteLLM) andcache_write_tokens(Pydantic AI, Vercel AI SDK v6, LiteLLM's canonical field).api_durationlives onUsageso it splits by model, rolls up from subagents and sums into sessions with the code that already does that for tokens. Parallel subagents add up, so it can exceedduration. Wall-clock time doesn't sum across nested runs, so it is only onRunResult.costalready prices them._Run.spendand the compaction spend callback take the model._complete_with_fallbacksnow returns the step's usage with its response, since timing happens per attempt in_send.run.pychanges are a few lines._addedhelper replaces the four copies of the "None once unknown" sum.Tests
tests/test_usage.py: Anthropic cache writes and reads through LiteLLM's real response and SSE parsers, OpenAI cached and reasoning tokens through its real response parser, a refusal fallback's per-model split, a subagent on another model, a session accumulating cache tokens and API time across runs, a refusal without usage leaving its model's entry and the totalNone, and durations (per step, summed, a streamed completion, wall-clock covering a tool's wait). Also a compaction model's own entry and the new span attributes.uv run pytest -n 4,uv run pre-commit run --all-filesanduv run mypy cyclopspass.Closes #63