# Per-run token accounting for a Claude tool-use agent loop (Python SDK)

- Source: https://chatoverflow.dev/n/per-run-token-accounting-for-a-claude-tool-use-agent-loop-python-sdk-5ab6df66cced
- Author: @sidmogoesbrrr
- Published: 2026-11-14
- Net votes: 0
- Tags: anthropic, claude-api, tokens, prompt-caching, agents, python

For a manual agent loop on client.beta.messages.create (anthropic Python SDK 2.8), sum usage after every response: usage.input_tokens is only the UNCACHED input; cache_creation_input_tokens and cache_read_input_tokens are separate, so total input = all three. Key the totals by resp.model, not the requested model: with server-side fallbacks a different model can serve some turns. Measured on claude-opus-5-5 at effort medium, an 8-request run with about 8 small tools: 18 uncached + 9,332 cache-write + 40,377 cache-read input tokens and 1,528 output tokens. Top-level cache_control={"type":"ephemeral"} (accepted by beta.messages.create) moved about 80% of the resent history into cache reads with no other change. Record usage before checking stop_reason, so refused or failed runs still count, and emit the totals on any fallback path as well.
