[BUG] Usage cache-token fields mix two incompatible conventions, over-counting cost on OpenAI/Gemini/LiteLLM cache hits
Summary
Usage.cacheReadInputTokens is populated from provider fields that do not mean the same thing, and nothing on the type says which convention applies. For Bedrock Converse and the Anthropic API, cache tokens are disjoint from inputTokens — the true prompt is inputTokens + cacheRead + cacheWrite. For OpenAI (Chat Completions and Responses), Gemini, and LiteLLM, the cache counts are a subset of the input field — the same tokens are reported twice, once in the total and once broken out.
Both are mapped onto one optional field and _accumulate_usage sums them blindly, so any consumer doing the obvious thing — total = input + output + cacheRead + cacheWrite, or cost = Σ tokens × rate — over-counts every OpenAI-style cache hit and charges those tokens twice, at the input rate and the cache rate. On agentic workloads, where most of the prompt is a cache hit, that is a multiple rather than a rounding error. The same code path is correct for Bedrock, which is what makes it hard to spot.
Reproduction
Live capture through Agent on openai.gpt-5.6-luna via Bedrock Mantle, us-east-1 (same prompt twice, second call is a cache hit):
call 1 accumulated: {"inputTokens": 6459, "outputTokens": 5, "totalTokens": 6464}
call 2 accumulated: {"inputTokens": 12936, "outputTokens": 10, "totalTokens": 12946, "cacheReadInputTokens": 6457}
sum(4 counters) = 19403 vs accumulated totalTokens = 12946 → over-counts by 6457 (+50%)
The provider's own usage for call 2 was {"input_tokens": 6452, "output_tokens": 5, "total_tokens": 6457, "input_tokens_details": {"cached_tokens": 6450, "cache_write_tokens": 0}} — 6452 + 5 == 6457, so cached_tokens is inside input_tokens.
Contrast Bedrock Converse on eu.anthropic.claude-haiku-4-5, eu-north-1, same shape of workload:
call 1 {"inputTokens": 10, "outputTokens": 4, "totalTokens": 5862, "cacheReadInputTokens": 0, "cacheWriteInputTokens": 5848}
call 2 {"inputTokens": 10, "outputTokens": 4, "totalTokens": 5862, "cacheReadInputTokens": 5848, "cacheWriteInputTokens": 0}
10 + 4 + 5848 == 5862. Here the cache counters are additional tokens and totalTokens includes them. No single interpretation of cacheReadInputTokens is correct for both providers.
Per-provider findings
| Provider | Convention | Issue |
|---|---|---|
| Bedrock Converse | disjoint ✅ [captured] | correct today; the de facto reference |
| Anthropic direct | disjoint [documented] | totalTokens is recomputed as input + output, excluding cache writes — under-reports a cached run. Anthropic's docs state total_input_tokens = cache_read + cache_creation + input_tokens |
| OpenAI Chat / Responses | subset [captured via Mantle] | cache counts are inside inputTokens, so summing over-counts. cache_write_tokens is dropped (it exists first-party from GPT-5.6, billed at 1.25× input) |
| Gemini | subset [captured] | cached_content_token_count is inside prompt_token_count. Separately, outputTokens was inferred as total - prompt, which silently counted tool_use_prompt_token_count (an input type) as output |
| LiteLLM | subset [verified in litellm source] | folds cache into prompt_tokens for every backend including Anthropic (prompt_tokens += cache_creation_input_tokens + cache_read_input_tokens), so the existing "only LiteLLM over Anthropic supports cache write tokens" comment is inverted |
| Vercel AI SDK | either | reads inputTokens.total (inclusive) when the AI SDK also provides inputTokens.noCache, which is exactly the disjoint value |
| TS Chat Completions | — | drops prompt_tokens_details entirely, so cache reads are invisible (Python's does read it — a py/ts parity gap) |
| Reasoning tokens | — | completion_tokens_details.reasoning_tokens / thoughts_token_count are billed but never surfaced |
Gemini's own field docs confirm total_token_count is "the sum of prompt_token_count, candidates_token_count, tool_use_prompt_token_count, and thoughts_token_count" — verified live: 23293 + 1 + 0 + 80 == 23374.
Blast radius beyond cost reporting
Usage is not only a metric. Anything derived from inputTokens or totalTokens inherits the ambiguity:
limits.total_tokensis an agent-loop stopping condition (_check_limits), so the convention decides when a run halts.latest_context_size/projected_context_size(public API viaAgentResult.context_size) are context-window quantities, not cost quantities — cached tokens occupy the window regardless.- Proactive compression gates on that same estimate (
_estimate_input_tokens→BeforeModelCallEvent.projected_input_tokens→ConversationManager). Under a subset-convention provider a mostly-cached 100k prompt reads as ~5k, so compaction never fires and the run hits a hard context-window error instead. - Multi-agent aggregation (
Graph/Swarm._accumulate_metrics) sums only the three required counters, dropping the cache counts while still adding theirtotalTokens— the total then reports tokens no counter accounts for. - OTel (
telemetry/tracer.py) emitsgen_ai.usage.input_tokens, which the GenAI semconv defines as including cached tokens ("This value SHOULD include all types of input tokens, including cached tokens"), with the cache attributes as breakdowns of it. So the SDK's field and the emitted attribute genuinely should differ, which needs stating rather than leaving to chance.
Proposed fix
- Write the contract down on
Usage. Whichever convention is chosen, the doc comment must say whether the cache counters are also ininputTokens, and whethertotalTokensincludes them. This is the cheapest half and the half that stops the next adapter repeating it. - Normalize to disjoint, i.e.
inputTokens + outputTokens + cacheReadInputTokens + cacheWriteInputTokens == totalTokens. Bedrock Converse is already disjoint, so the flagship provider's numbers do not move; cost becomes a plain weighted sum, which is the point. Route every adapter through one shared helper taking a singleinput_includes_cacheflag, so a new provider makes one decision instead of re-deriving the arithmetic. - Keep OTel conformant separately — add the cache counters back when emitting
gen_ai.usage.input_tokens, per semconv. - Fix the context-window consumers to use the full prompt, not
inputTokens. - Surface reasoning tokens as a field documented as a subset of
outputTokens(so it must not be added to a total). - Test the invariant, not field presence. A test asserting only
cacheReadInputTokens == 1920passes under both conventions and proves nothing — that is how this got in.
This changes the value of inputTokens for OpenAI/Gemini/LiteLLM users and of totalTokens for Anthropic-direct users. It is a behaviour change on metrics fields rather than an API break, but it deserves a release note: anyone charting those fields will see a step.
Environment
harness-sdk@main. Captures on Bedrock Converse (eu-north-1), Bedrock Mantle Responses (us-east-1), and Gemini (AI Studio) were taken directly against the live APIs. Anthropic-direct and first-party OpenAI are not wire-captured — those rows are from vendor docs and the installed SDK type definitions.
I have a fix ready for both SDKs and will open a PR referencing this issue.
Related reports and how the two conventions diverged
While preparing a fix I went looking for prior reports. Collecting them here since this issue is tracking the work.
One label request: this is currently tagged typescript, but it affects both SDKs — the Python adapters carry the same two conventions, and the fix touches both. Could someone with triage rights add python and sdk-parity? I don't have permission to do it myself.
A duplicate, reported ten months ago
#797 — "totalTokens not equal to inputTokens + outputTokens" (closed unfixed after 7 days of no response) is the same bug seen from the other side. The reported numbers:
{'inputTokens': 4674, 'outputTokens': 328, 'totalTokens': 5746}
4674 + 328 = 5002, leaving 744 tokens unaccounted for. That gap is the cache counters. The reporter was using agents-as-tools, which is why it surfaced there: Graph._accumulate_metrics and its Swarm equivalent sum inputTokens/outputTokens/totalTokens and drop the cache counters, so the cache tokens disappear from the breakdown while remaining inside the provider-reported total.
The thread read the gap as provider overhead ("guardrails, caching, safety checks") and proposed computing totalTokens = inputTokens + outputTokens locally. That would have made the arithmetic self-consistent by discarding real billed tokens — worth flagging as a tempting dead end for anyone who finds this later.
How the conventions came to coexist
Not a mistake in any single PR — each was correct for its own provider. The problem is that nothing recorded which convention a given Usage was carrying:
- #529 added
cacheReadInputTokens/cacheWriteInputTokens, modelled on Bedrock Converse, where the counters sit alongsideinputTokensand are already insidetotalTokens. - #2116 (OpenAI), #2287 (Gemini), #2302 (Anthropic), #2555, #2663, #2782 then plumbed the same two fields through for providers that report the whole prompt in their input field with the cache as a subset of it.
The example payload in #2116's own description shows the consequence: prompt_tokens=1861 with cached_tokens=1792. Summing the four counters gives 3663 against a true total of 1871 — 1.96x over.
- strands-agents/sdk-typescript#895 is the mirror image: TypeScript reported Anthropic cache tokens while Python dropped them. The two SDKs had drifted in opposite directions.
Downstream
#1428 and #1216 both propose exposing dollar cost derived from accumulated_usage. Either would inherit the over-count into a headline number, so they're worth sequencing after this.
Not related, despite appearances
For the record, since the search terms overlap: the Langfuse double-counting reports (langfuse/langfuse#7549, plus #1267 and #2010 here) are a different bug — token counts are summed at both the parent and child span. The counts themselves are internally consistent there. langfuse/langfuse#8808 is Strands-specific but its payload reconciles (47 + 3041 == 3088, no cache counters present). A cached-provider user could see both problems at once, but they are independent.
Opened #3561 with a fix for this.
It makes the four billed counters disjoint for every provider in both SDKs — inputTokens + outputTokens + cacheReadInputTokens + cacheWriteInputTokens == totalTokens — by routing every adapter through one normalization helper per SDK with a single input_includes_cache flag. That is what makes cost a plain weighted sum regardless of which provider produced the numbers.
Two things worth flagging for whoever picks it up:
- It is large (84 files), because a contract that holds for only some providers is not a contract. The description proposes a concrete four-way split if maintainers prefer that, along with the one caution I have about splitting it — landing the contract without its consumers would leave a live compaction bug that does not exist today.
- The
litellmextra's floor moves to>=1.78.0, which is a breaking change for existing installs. The reasoning is in the description and I would like a maintainer to weigh it explicitly rather than accept it.
Also closes #797, whose reported numbers reconcile exactly under this change.
Independent confirmation, plus a correction to one row of the per-provider table.
The table lists Bedrock Converse as disjoint ✅ correct today; the de facto reference, with the OpenAI capture taken via Mantle. That holds for Anthropic models on Converse, but not for Converse itself. The convention follows the model family, not the API.
Measured on bedrock-runtime (not Mantle), eu-south-1, through BedrockModel → ConverseStream, one conversation, turn 1 cold and turn 2 warm:
global.openai.gpt-5.6-luna
turn 1 inputTokens=5020 outputTokens=32 cacheRead=0 cacheWrite=5018
turn 2 inputTokens=5072 outputTokens=42 cacheRead=5018 cacheWrite=52
5072 ≈ 5018 + 52 + 2, so cache counts are INSIDE inputTokens (subset)
global.anthropic.claude-haiku-4-5-20251001-v1:0 (same code path, same stack, same session)
turn 1 inputTokens=3 outputTokens=44 cacheRead=0 cacheWrite=6987
cache counts are ADDITIONAL to inputTokens (disjoint)
Same SDK, same BedrockModel, same Converse API, same region, opposite conventions, decided by whether the model behind the inference profile is OpenAI or Anthropic. A consumer cannot branch on the provider class or the API; it has to branch on the model.
This supports fix (1) in the proposal, writing the contract onto Usage, since there is no adapter-level place where "Bedrock Converse" can be labelled one way.
Two further data points from the same session:
-
cache_write_tokensbeing dropped is observable from the Converse side too. Bedrock does returncacheWriteInputTokensfor OpenAI models on Converse (5018 and 52 above), so on this path the field is available and only the Responses adapter drops it. -
CloudWatch is not a workaround.
AWS/BedrockpublishesCacheReadInputTokenCountandCacheWriteInputTokenCountforglobal.anthropic.claude-haiku-4-5-*but not forglobal.openai.gpt-5.6-luna, which exposes onlyInputTokenCount,OutputTokenCount,Invocations,InvocationLatency,TimeToFirstTokenandEstimatedTPMQuotaUsage. The SDK'sUsageis the only place these counts surface for OpenAI on Bedrock.
Cost impact from the turn 2 numbers at Luna's published Global CRIS rates: billing inputTokens as uncached gives ~0.11c, against ~0.016c when the cached tokens are subtracted first, a ~7x over-report on a single warm turn.
Status update, verified against main @ 01a5aad (Aug 28): the user-facing symptoms tracked here have been fixed in 5 small merged PRs (#3884, #3885, #3892, #3886, #3964) — the SDK's own Usage consumers (compaction, context-size, telemetry, multi-agent aggregation) are now convention-aware and produce correct numbers regardless of which convention an adapter emits.
The core bug is still in main: adapters emit two different conventions and nothing on Usage records which, so summing the four counters still over-counts cache hits on subset providers (OpenAI/Gemini/LiteLLM, up to ~2x), and Anthropic-direct still under-reports totalTokens. Remaining work continues as small, independently-reviewable PRs.
What has landed
| PR | Fix | Merged |
|---|---|---|
| #3884 | Graph/Swarm metric accumulation no longer drops cacheReadInputTokens/cacheWriteInputTokens — the visible symptom of #797 (input + output != total in multi-agent results) |
Aug 20 |
| #3885 | TS OpenAI Chat Completions now reads prompt_tokens_details, so cache reads are no longer invisible (Python/TS parity) |
Aug 19 |
| #3892 | Gemini adapter no longer counts tool_use_prompt_token_count (an input type) as output; thinking tokens counted as output |
Aug 21 |
| #3886 | Context-size estimation and proactive compaction now count cached tokens correctly — the baseline reconciles against totalTokens instead of assuming one convention, so it is correct under both the disjoint and subset conventions (including the model-family split @aristide1997 measured on Converse). Before this, compaction effectively never fired on Bedrock/Anthropic cache hits. |
Aug 27 |
| #3964 | OTel cache usage now emitted under the semconv attribute names (gen_ai.usage.cache_read.input_tokens / cache_creation.input_tokens), with the old names kept as deprecated aliases — closed #3754 |
Aug 25 |
What is still in main
- The headline bug is unfixed: adapters still emit two different conventions, and nothing on
Usagerecords which one. Summing the four counters still over-counts every cache hit on subset providers (OpenAI, Gemini, LiteLLM, …) — up to ~2x per #2116's own payload, ~7x cost over-report in @aristide1997's warm-turn measurement. - Anthropic direct still under-reports
totalTokens(cache writes excluded). - The Responses adapter still drops
cacheWriteInputTokensthat Bedrock does return for OpenAI models on Converse. - There is still no normalization helper / documented contract on
Usage, so external consumers ofaccumulated_usage(including the cost proposals in #1428/#1216) inherit the ambiguity.
One design constraint confirmed by @aristide1997's Converse data: the convention follows the model family, not the adapter, so a static per-adapter flag can't fully resolve this for Bedrock — normalization needs to reconcile against totalTokens per payload (the approach #3886 already uses internally) and/or be model-aware.
I’m seeing a behavior after the recent telemetry changes around #3886 that are causing an interoperability issue with AgentCore GenAI Observability.
After the change, gen_ai.usage.input_tokens appears to represent the full prompt size, including cache-read and cache-write tokens, while the cache token counts are also emitted separately.
For example: gen_ai.usage.input_tokens: 12,737 cache read: 11,634 cache write: 1,099 derived uncached input: 4
AgentCore GenAI Observability appears to interpret the full input_tokens value as normal billable input and then adds the cache-read/write costs separately, which results in apparent double-counting in the cost display.
Thanks for reporting this @codefre !
The cache numbers in your example are correct according to the OTEL standards, which is what we're migrating to. We will work on aligning the cost display in AgentCore GenAI Observability.
For now, you can use Strands SDK python version v1.53.0 to avoid this issue.
@opieter-aws thanks for the run of small PRs on this (#3884, #3885, #3892, #3886, #3964, #4080). I re-verified against main today and the consumer side is in good shape: context sizing, compaction, telemetry and multi-agent totals all handle both conventions now. Also thanks to @aristide1997 for the Converse measurement; the model-family split is a genuine correction to my table and I agree it rules out a static per-adapter flag for Bedrock.
Following the bite-size approach, I've opened #4219 for the one remaining place where the SDK computes a total itself rather than passing the provider's through: the Anthropic adapter. It reports input_tokens net of the cache, so input + output drops every cached token, and that is exactly the payload the _total_prompt_tokens / totalPromptTokens helper cannot classify (the "known limitation" tests from #3886). It is also the total that #2302 described in its own write-up but did not ship. The change is two lines per SDK plus the test flips, and I verified it live with Claude Haiku 4.5 and Sonnet 5 through both BedrockModel on Converse and AnthropicModel against Mantle's Anthropic Messages endpoint; the fixed adapter now produces the same numbers as Converse for the same prompt, and the four counters sum to the total on every call.
Suggested sequencing from here, happy to take either or both if useful:
- Once #4219 lands, a docstring/TSDoc-only PR that writes the current contract onto
Usage:totalTokensis always the full billed count, the cache counters may or may not be insideinputTokens, andinputTokens + outputTokens == totalTokenstells you which. That only becomes truthful once every provider's total is reliable, which is why I'd land it second. - Then pick up the wider question (normalise adapters to one convention vs. expose the reconciliation helper publicly) on this thread with solid ground under it. I'll treat my closed #3561 as reference material only.
One adjacent note for whoever is tracking OTel: #3602 (container spans duplicating usage) had a contributor defer to #3561, which is now closed, so that item is unowned.
Thanks @niklas-palm @Ryutaro-A and @philmerrell for helping closing the gaps here! With #4617 the reporting inaccuracies should be resolved, and this bug report can be closed once that's merged.
The larger story of normalizing all token usage centrally according to semconv will be tracked in #4618