Claude Agent SDK cost tracking: two ways the numbers come out wrong
Short answer: two mistakes keep showing up in projects built on the Claude Agent SDK and
claude -p:
1. Booking total_cost_usd per call on a resumed session. Since Claude Code v2.1.277 a call
that resumes (or forks) a session reports the session's running total, earlier calls included. Add those
up and you pay for the first call again on every resume. Book the difference instead.
2. Adding up output_tokens from assistant messages. That number is a placeholder set when
the response began. The real output count is on the result message.
Below: what Anthropic's docs say, a small tested Python function that books only the difference, and how to count output tokens correctly.
Mistake 1: a resumed call reports the whole session
Every query() call (or claude -p run) ends with a result message carrying
total_cost_usd and a per-model breakdown (model_usage in Python,
modelUsage in TypeScript). For an independent call, that is the cost of that call. For a call that
passes resume, it isn't.
Anthropic's cost-tracking guide says that Claude Code saves the session's totals to its transcript when the process exits normally and restores them when a later call resumes or forks the session. Each result then already includes the session's earlier spend. The guide's advice: read the latest result for the session total, because summing results double-counts the restored spend.
An example. A session runs three times: the first call, then two resumes. The results report:
| Call | Reported total | What the call actually added |
|---|---|---|
| 1 (new session) | $0.40 | $0.40 |
2 (resume) | $0.65 | $0.25 |
3 (resume) | $0.90 | $0.25 |
| Total | $1.95 if you add them up | $0.90 |
The more often a session is resumed, the worse it gets: a run that resumes the same agent for a build and then a review fix shows the build's cost twice. This month the same bug was reported in worca-cc, claude-rollout, claude-pipeline, delega and untether (where a retry check compared the session total with a per-run budget).
Details that matter:
- It depends on the version. Before Claude Code v2.1.277, a session resumed through the SDK or
claude -pstarted its totals at zero, so each result covered only its own call. Code that was right then double-counts now. Check which version your SDK bundles before you change anything. - Forks start from the parent. A fork gets a new session ID, but its totals are restored from the session it was forked from.
- Streaming input mode works the same way inside one call. When one
query()call carries several user turns, each turn emits a result, andtotal_cost_usdandmodel_usageare the running total for the call so far. Read the latest one; don't add them up./clear,/resetor/newstarts the totals over, with a newsession_id. - The result's
usagefield is different. In streaming input mode it covers only that turn, and only the main agent loop: subagent tokens are left out. Anthropic recommendsmodel_usagefor token and cost accounting. - A spending cap doesn't see the restored spend.
max_budget_usdcounts only the call's own spend, so don't compare the restored session total with a per-call budget.
The fix: book the difference
Keep the last running total you saw for each session. When a result arrives, book what it adds over that, then
remember the new total. The function below does that for total_cost_usd and every model in
model_usage, starts a fork from its parent's totals, and books nothing for a result whose total went
down (Anthropic notes that the result emitted after a crash may carry zeroed totals), so the old baseline is kept.
(Download it, MIT licence, no dependencies.)
MODEL_KEYS = ("inputTokens", "outputTokens", "cacheReadInputTokens",
"cacheCreationInputTokens", "webSearchRequests", "costUSD")
def _numbers(model_usage):
"""{model: {key: number}} for the summable keys of model_usage."""
return {m: {k: (u.get(k) or 0) for k in MODEL_KEYS}
for m, u in (model_usage or {}).items()}
def book_result(ledger, session_id, total_cost_usd, model_usage=None, forked_from=None):
"""What one result message adds to the session, as a dict:
{"cost_usd": float, "models": {model: {key: delta}}, "note": str or None}.
ledger -- dict you keep: session_id -> last running totals seen
forked_from -- the parent session_id when this session is a fork, because a
fork starts from the parent's restored totals
"""
if total_cost_usd is None:
return {"cost_usd": 0.0, "models": {}, "note": "no total_cost_usd on this result"}
empty = {"cost_usd": 0.0, "models": {}}
last = ledger.get(session_id) or ledger.get(forked_from) or empty
if total_cost_usd < last["cost_usd"] - 1e-9:
# A running total never goes down. A zeroed result after a crash does;
# keep the old baseline so the next result isn't booked twice.
return {"cost_usd": 0.0, "models": {},
"note": "running total went down (crash result?); nothing booked"}
now = _numbers(model_usage) if model_usage is not None else last["models"]
models = {}
for m, vals in now.items():
before = last["models"].get(m, {})
d = {k: vals[k] - before.get(k, 0) for k in MODEL_KEYS}
if any(d.values()):
models[m] = d
ledger[session_id] = {"cost_usd": total_cost_usd, "models": now}
return {"cost_usd": total_cost_usd - last["cost_usd"], "models": models, "note": None}
Using it with the Python Agent SDK. The ledger is saved to a file, because if it's lost the next resumed result is booked in full again:
import json
from pathlib import Path
from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, query
from agent_sdk_cost_delta import book_result
LEDGER = Path("cost_ledger.json")
async def run(prompt, resume=None):
ledger = json.loads(LEDGER.read_text()) if LEDGER.exists() else {}
booked = []
async for message in query(prompt=prompt, options=ClaudeAgentOptions(resume=resume)):
if isinstance(message, ResultMessage):
b = book_result(ledger, message.session_id,
message.total_cost_usd, message.model_usage)
LEDGER.write_text(json.dumps(ledger))
booked.append(b)
return booked
Each item in booked is what one result added: cost_usd, and per model the added input,
output, cache and web-search counts. On the example above it books $0.40, $0.25 and $0.25.
We tested it with 20 checks: new sessions, resumes, a new model (a subagent) appearing mid-session, a zeroed
crash result followed by a resume, a result without a total, a fork, a /clear (new session ID), the
same result seen twice, and a JSON round trip of the ledger. The SDK sample above was run against the Python
Agent SDK's own ResultMessage class (v0.2.187) with a simulated message stream. One limit:
Anthropic's guide says the totals are saved when the process exits normally, so after a crash a resume
may restore a lower total than you last saw. The function then books nothing until the total passes the old
baseline, which can under-count that stretch, and never counts it twice.
Mistake 2: output tokens from assistant messages
Each step of an agent run produces assistant messages with a usage block, and it's tempting to add
those up. For input and cache tokens that works, once you count each message ID only once (when Claude calls
several tools in one turn, all of those messages share the same ID and the same usage).
For output it doesn't. Anthropic's guide explains that Claude Code builds each assistant message from the usage
the API reported when the response began (message_start), before anything was generated, so
its output_tokens is a placeholder. The API reports the real count at the end of the response, and
Claude Code adds it to the result message. In one
OpenInference report, a turn with 373 output
tokens was recorded as 2.
The fix: count input and cache tokens per unique message ID, and read output from the result:
from claude_agent_sdk import AssistantMessage, ResultMessage, query
async def count_tokens(prompt):
seen, input_tokens, output_tokens = set(), 0, 0
async for message in query(prompt=prompt):
if isinstance(message, AssistantMessage) and message.parent_tool_use_id is None:
if message.message_id not in seen: # parallel tool calls share one ID
seen.add(message.message_id)
input_tokens += (message.usage or {}).get("input_tokens", 0)
# message.usage["output_tokens"] is a placeholder: don't add it up
elif isinstance(message, ResultMessage):
output_tokens = (message.usage or {}).get("output_tokens", 0)
return input_tokens, output_tokens
That counts the main agent loop. The result's usage leaves out subagents, so for the whole run use
outputTokens from model_usage, and on a resumed session take the added amount from
book_result()'s models, since model_usage is a running total too.
- Errors still cost money. Error results carry
usageandtotal_cost_usdas well, so read every result, not onlysubtype == "success". Onerror_max_budget_usd,usageleaves out the response that crossed the budget, whiletotal_cost_usdandmodel_usageinclude it. - After a crash, output can't be rebuilt from the stream. Summing assistant messages recovers only the main loop's input and cache tokens; output and cost are lost, because of the same placeholder.
- Reading transcript files instead? Claude Code writes each response to
~/.claude/projects/<project>/<session-id>.jsonl, often over several lines with the same message ID. Count each message ID once and take the last line's usage. In our own Claude Code logs (6,111 responses written over several lines, checked November 23, 2026), the last line always carried the final output count. Why a plain sum of Claude Code logs over-counts.
Remember: these numbers are estimates
Anthropic is clear that total_cost_usd and costUSD are worked out on your machine from
a price table bundled with the SDK. They can drift from your bill when prices change, when your SDK version
doesn't know a model, or when billing rules apply that the client can't model. (One it does model: a response
served with inference_geo: "us" is priced at 1.1 times list price, on TypeScript SDK v0.3.239 or
Python SDK v0.2.144 and later.) Each model_usage entry's costBasis says which prices
were used; unknown means the model wasn't recognised. Anthropic's advice is to use these fields for
development insight and rough budgets, and not to bill end users from them. For the actual charges, use the
Claude Console's Usage and Cost pages (where to find them).
Or record each request as it happens
NeverPayTwice is a small app we make. Its live meter sits on your own computer between your code and the API:
Claude Code reads ANTHROPIC_BASE_URL, so set it to http://127.0.0.1:8098/anthropic and
every request is passed through unchanged and recorded with its tokens (cache writes and reads split out), cost
and request ID, one receipt per API request, whichever session it belongs to. It never blocks or changes a
request, and API keys are never stored. It flags every time you paid again for a request you had already
bought. It also works with OpenAI, Google Gemini and compatible APIs. Mac, Windows or Linux, $9.99 to start,
then $2.99 a month to keep (your first month is included).
Try it on your own Claude and OpenAI API calls, free for 7 days. No card needed.
Not ready to buy? Get the free one-page AI API bill checklist by email: ten checks for a bill that's higher than expected, plus a short note when Claude or OpenAI prices change. A few emails a year, never shared. Prefer no email? Download the PDF.
Sources: Anthropic's Agent SDK guide
Track cost and usage, the
Python Agent SDK reference
(AssistantMessage, ResultMessage, ModelUsage), the
sessions page (where transcripts are stored) and the
environment variables page
(ANTHROPIC_BASE_URL), checked November 23, 2026. Field names and version numbers can change; check
the current pages if something doesn't match.