fix: log full-turn token usage from model_usage in claude-agent-sdk wrapper#565
Open
lsuarez-ekline wants to merge 1 commit into
Open
Conversation
…rapper ResultMessage.usage covers only the orchestrator agent, so turns that spawn subagents under-count tokens on the trace. Prefer the per-model model_usage breakdown (which includes subagent calls) for the logged token metrics; metadata (service tier, etc.) still comes from usage.
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.
What
ContextTracker._handle_resultlogs the turn's token metrics fromResultMessage.usage, which is the cumulative usage for the orchestrator agent only. On a turn that spawns subagents (theTask/Agent tool), the subagent tokens are billed but missing from the trace, so the logged totals under-count — often heavily.This prefers the token counts from
ResultMessage.model_usage(the per-model breakdown, which is per-agent and includes subagent calls), summed across models, for the logged metrics. Metadata (service tier, inference geo) still comes fromusage. Whenmodel_usageis missing or unusable it falls back tousage, so single-agent turns and older SDKs are unchanged.Fixes #564.
Details
_aggregate_model_usage()sumsmodel_usageinto an Anthropic-usage-shaped dict, then reusesextract_anthropic_usagefor the metric mapping — so cache-read / cache-creation / completion all flow through the same path as before.usage == model_usage).model_usage.Testing
nox -s "test_claude_agent_sdk(latest)"— 50 passed (existing suite + 2 new unit tests for_aggregate_model_usage).ruff format/ruff checkclean.Notes
Alternative considered: attribute tokens onto per-subagent spans instead of aggregating onto the turn's LLM span. Happy to take that direction if you'd prefer — this PR takes the minimal approach that makes the trace-level token total correct.