Track cost and usage
기준일: 2026-07-26
공식 기준: Track cost and usage
Track cost and usage 문서는 Claude Code 공식 문서(agent-sdk/cost-tracking)를 한국어로 정리한 가이드입니다. Learn how to track token usage, estimate costs, and configure prompt caching with the Claude Agent SDK. 명령·설정 키·코드 예시는 공식 문서를 그대로 보존하며, 해석과 절차 안내는 한국어로 제공합니다. 최종 동작은 설치 버전과 공식 원문을 확인하세요.
핵심 요약
Learn how to track token usage, estimate costs, and configure prompt caching with the Claude Agent SDK.
한국어 가이드 범위: agent-sdk/cost-tracking 경로의 설정·명령·제약·예시를 학습용으로 재구성합니다.
문서 구성
공식 문서의 주요 섹션은 다음과 같습니다.
- Track cost and usage
- Understand token usage
- Get the total cost of a query
- Track per-step and per-model usage
- Track per-step usage
- Break down usage per model
- Accumulate costs across multiple calls
- Handle errors, caching, and token discrepancies
- Resolve output token discrepancies
- Track costs on failed conversations
- Track cache tokens
- Extend the prompt cache TTL to one hour
- Related documentation
상세 내용
Track cost and usage
Learn how to track token usage, estimate costs, and configure prompt caching with the Claude Agent SDK.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
주요 항목:
- pricing changes
- the installed SDK version does not recognize a model
- billing rules apply that the client cannot model
Understand token usage
The TypeScript and Python SDKs expose the same usage data with different field names:
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
주요 항목:
- TypeScript provides per-step token breakdowns on each assistant message (
message.message.id,message.message.usage), per-model cost viamodelUsageon the result message, and a cumulative total on the result message. - Python provides per-step token breakdowns on each assistant message (
message.usage,message.message_id), per-model cost viamodel_usageon the result message, and the accumulated total on the result message (total_cost_usdandusagedict). query()call: one invocation of the SDK'squery()function. A single call can involve multiple steps (Claude responds, uses tools, gets results, responds again). Each call produces oneresultmessage at the end.- Step: a single request/response cycle within a
query()call. Each step produces assistant messages with token usage. - Session: a series of
query()calls linked by a session ID (using theresumeoption). Eachquery()call within a session reports its own cost independently.
Get the total cost of a query
The result message (TypeScript, Python) marks the end of the agent loop for a query() call. It includes total_cost_usd, the cumulative estimated cost across all steps in that call. This works for both success and error results. If you use sessions to make multiple query() calls, each result only reflects the cost of that individual call.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
| Field | Subagent activity |
|---|---|
usage |
Excluded. Counts only the top-level agent loop, so tokens consumed inside subagents are not added |
total_cost_usd |
Included. Counts subagent requests alongside the top-level loop |
modelUsage / model_usage |
Included. Counts subagent requests alongside the top-level loop, broken down by model |
Track per-step and per-model usage
The examples in this section use TypeScript field names. In Python, the equivalent fields are AssistantMessage.usage and AssistantMessage.message_id for per-step usage, and ResultMessage.model_usage for per-model breakdowns.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
Track per-step usage
Each assistant message contains a nested BetaMessage (accessed via message.message) with an id and usage object with token counts. When Claude uses tools in parallel, multiple messages share the same id with identical usage data. Track which IDs you've already counted and skip duplicates to avoid inflated totals.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
Break down usage per model
The result message includes modelUsage, a map of model name to per-model token counts and cost. This is useful when you run multiple models (예를 들어, Haiku for subagents and Opus for the main agent) and want to see where tokens are going.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
Accumulate costs across multiple calls
Each query() call returns its own total_cost_usd. The SDK does not provide a session-level total, so if your application makes multiple query() calls (예를 들어, in a multi-turn session or across different users), accumulate the totals yourself.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
Handle errors, caching, and token discrepancies
For accurate cost tracking, account for failed conversations, cache token pricing, and occasional reporting inconsistencies.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
Resolve output token discrepancies
In rare cases, you might observe different output_tokens values for messages with the same ID. When this occurs:
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
Track costs on failed conversations
Both success and error result messages include usage and total_cost_usd. If a conversation fails mid-way, you still consumed tokens up to the point of failure. Always read cost data from the result message regardless of its subtype.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
Track cache tokens
The Agent SDK automatically uses prompt caching to reduce costs on repeated content. You do not need to configure caching yourself. The usage object includes two additional fields for cache tracking:
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
주요 항목:
cache_creation_input_tokens: tokens used to create new cache entries (charged at a higher rate than standard input tokens).cache_read_input_tokens: tokens read from existing cache entries (charged at a reduced rate).
Extend the prompt cache TTL to one hour
Cache entries written by the SDK use a 5-minute TTL by default when you authenticate with an API key or run on Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry. If your workload runs many short sessions against the same system prompt and context with gaps longer than 5 minutes between them, the cache expires between sessions and each new session pays full input price.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
Related documentation
주요 항목:
- TypeScript SDK Reference - Complete API documentation
- SDK Overview - Getting started with the SDK
- SDK Permissions - Managing tool permissions
실습 체크리스트
- 공식 문서와 로컬/SDK 버전을 대조합니다.
- 관련 CLI·SDK 옵션은 공식 페이지와
--help로 교차 확인합니다. - Agent SDK 예시는 TypeScript/Python 패키지 최신 API를 우선합니다.
- 권한·호스팅·보안 설정 변경 후 통합 테스트를 실행합니다.
자주 쓰는 명령·설정 예시
## Track per-step and per-model usage
The examples in this section use TypeScript field names. In Python, the equivalent fields are [`AssistantMessage.usage`](/docs/en/agent-sdk/python#assistantmessage) and `AssistantMessage.message_id` for per-step usage, and [`ResultMessage.model_usage`](/docs/en/agent-sdk/python#resultmessage) for per-model breakdowns.
### Track per-step usage
Each assistant message contains a nested `BetaMessage` (accessed via `message.message`) with an `id` and `usage` object with token counts. When Claude uses tools in parallel, multiple messages share the same `id` with identical usage data. Track which IDs you've already counted and skip duplicates to avoid inflated totals.
Parallel tool calls produce multiple assistant messages whose nested `BetaMessage` shares the same `id` and identical usage. Always deduplicate by ID to get accurate per-step token counts.
The following example accumulates input and output tokens across all steps, counting each unique message ID only once:
### Break down usage per model
The result message includes [`modelUsage`](/docs/en/agent-sdk/typescript#modelusage), a map of model name to per-model token counts and cost. This is useful when you run multiple models (for example, Haiku for subagents and Opus for the main agent) and want to see where tokens are going.
The following example runs a query and prints the cost and token breakdown for each model used:
## Accumulate costs across multiple calls
Each `query()` call returns its own `total_cost_usd`. The SDK does not provide a session-level total, so if your application makes multiple `query()` calls (for example, in a multi-turn session or across different users), accumulate the totals yourself.
The following examples run two `query()` calls sequentially, add each call's `total_cost_usd` to a running total, and print both the per-call and combined cost:
## Handle errors, caching, and token discrepancies
For accurate cost tracking, account for failed conversations, cache token pricing, and occasional reporting inconsistencies.
### Resolve output token discrepancies
In rare cases, you might observe different `output_tokens` values for messages with the same ID. When this occurs:
1. **Use the highest value:** the final message in a group typically contains the accurate total.
2. **Prefer the result message:** the `total_cost_usd` in the result message reflects the SDK's accumulated estimate across all steps, so it is more reliable than summing per-step values yourself. It is still an estimate and may differ from your actual bill.
3. **Report inconsistencies:** file issues at the [Claude Code GitHub repository](https://github.com/anthropics/claude-code/issues).
### Track costs on failed conversations
Both success and error result messages include `usage` and `total_cost_usd`. If a conversation fails mid-way, you still consumed tokens up to the point of failure. Always read cost data from the result message regardless of its `subtype`.
### Track cache tokens
The Agent SDK automatically uses [prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) to reduce costs on repeated content. You do not need to configure caching yourself. The usage object includes two additional fields for cache tracking:
* `cache_creation_input_tokens`: tokens used to create new cache entries (charged at a higher rate than standard input tokens).
* `cache_read_input_tokens`: tokens read from existing cache entries (charged at a reduced rate).
Track these separately from `input_tokens` to understand caching savings. In TypeScript, these fields are typed on the [`Usage`](/docs/en/agent-sdk/typescript#usage) object. In Python, they appear as keys in the [`ResultMessage.usage`](/docs/en/agent-sdk/python#resultmessage) dict (for example, `message.usage.get("cache_read_input_tokens", 0)`).
### Extend the prompt cache TTL to one hour
Cache entries written by the SDK use a 5-minute TTL by default when you authenticate with an API key or run on Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry. If your workload runs many short sessions against the same system prompt and context with gaps longer than 5 minutes between them, the cache expires between sessions and each new session pays full input price.
To request a 1-hour TTL on cache writes, set the [`ENABLE_PROMPT_CACHING_1H`](/docs/en/env-vars) environment variable. You can export it in your shell or container environment, or pass it through `options.env`.
The following example enables 1-hour TTL for an agent running on Amazon Bedrock. Because it sets `CLAUDE_CODE_USE_BEDROCK`, it requires working AWS credentials for [Amazon Bedrock](/docs/en/amazon-bedrock); without them the query fails.
관련 링크
- 공식 원문: agent-sdk/cost-tracking
- 문서 홈
이 가이드는 공식 문서를 한국어 학습용으로 재구성한 것입니다. 옵션 기본값·API 이름은 설치 버전에 따라 달라질 수 있습니다.