Overview
The Claude Agent SDK reports detailed token usage for each interaction. This
guide covers reading cost and usage correctly, especially with parallel tool use
and multi-step conversations.
Scopes
- query() call: one
query() invocation; produces one result message.
- Step: one request/response cycle within a call; produces assistant messages
with usage.
- Session: multiple
query() calls linked by a session id (resume); each
call reports its own cost.
Get the total for a call
The result message includes total_cost_usd (estimated) and cumulative usage:
for await (const message of query({ prompt: "Summarize this project" })) {
if (message.type === "result") {
console.log(`Total cost: $${message.total_cost_usd}`);
}
}
This is a client-side estimate from a bundled price table, not authoritative
billing. Use the Usage and Cost API or the Console for real charges.
Per-step and per-model usage
Each assistant message carries usage (input/output tokens) and an id. Parallel
tool calls in one turn share an id, so deduplicate by id to avoid double
counting:
const seen = new Set();
let input = 0, output = 0;
for await (const message of query({ prompt: "..." })) {
if (message.type === "assistant" && !seen.has(message.message.id)) {
seen.add(message.message.id);
input += message.message.usage.input_tokens;
output += message.message.usage.output_tokens;
}
}
The result message's modelUsage (TS) / model_usage (Python) breaks cost and
tokens down per model, useful when subagents run a cheaper model.
Accumulate across calls
The SDK has no session-level total; sum each call's total_cost_usd yourself when
running multiple query() calls.
Cache tokens and failures
The SDK uses prompt caching automatically. The usage object includes
cache_creation_input_tokens (written, higher rate) and cache_read_input_tokens
(read, reduced rate); track them to understand caching savings. Both success and
error results include cost, so always read it regardless of subtype. To extend
cache TTL to one hour on API-key/Bedrock/Vertex/Foundry, set
ENABLE_PROMPT_CACHING_1H.
Source