Sub topic 9
Reading usage fields and computing a hit ratio
This chapter assumes you can call an LLM API from Python, know what tokens are, and understand that a cache hit needs an identical prompt prefix. Here you learn to read the usage data a provider returns and turn it into one number you can track.
Why measure at all
A cache miss is silent. The response looks the same, and only the bill and the latency change. The only reliable signal is the usage data attached to each response. If you don't log it, you won't know whether your layout work paid off.
The three counters
With Anthropic's Messages API, each response reports input tokens in three separate fields:
| Field | Meaning |
|---|---|
| `cache_creation_input_tokens` | Tokens written to the cache on this call |
| `cache_read_input_tokens` | Tokens served from the cache |
| `input_tokens` | Tokens after the last breakpoint, not cached |
Total input for the call is the sum of all three. Other providers use different names. Some report a single "cached tokens" count inside the usage object, and the remaining input is the total minus that count. Check your provider's documentation, and confirm whether its prompt token total already includes the cached part before you add anything up.
Reading the fields from a call
This call marks the policy text as a stable block with a breakpoint, then prints the counters.
import anthropic
client = anthropic.Anthropic()
POLICY = open("policy.md").read() # must meet the model's minimum cacheable length
response = client.messages.create(
model="YOUR_MODEL_NAME",
max_tokens=512,
system=[
{
"type": "text",
"text": POLICY,
"cache_control": {"type": "ephemeral"},
}
],
messages=[{"role": "user", "content": "Summarize the refund rules."}],
)
u = response.usage
print("written:", u.cache_creation_input_tokens)
print("read:", u.cache_read_input_tokens)
print("uncached input:", u.input_tokens)On the first call you expect a large written value and a small uncached input. On a repeat call within the cache lifetime you expect read to hold the large value instead.
Computing the hit ratio
A hit ratio is the share of input tokens served from the cache.
def cache_hit_ratio(cache_read, cache_written, uncached):
total = cache_read + cache_written + uncached
return cache_read / total if total else 0.0
# First call: the prefix is written. Second call: the prefix is read.
print(cache_hit_ratio(0, 4000, 50)) # 0.0
print(cache_hit_ratio(4000, 0, 60)) # about 0.99Log this per request, along with the three raw counters. Then aggregate over time, for example per hour and per prompt template.
Interpreting the number
- First call after a quiet period. A ratio near 0 with a large written count is normal. The cache is being filled.
- Steady traffic. Expect a ratio close to the share of your prompt that is stable. If 90% of the prompt is a fixed prefix, a ratio near 0.9 is healthy.
- Written tokens on every call. If
writtenstays large on repeat calls, the prefix is changing or the entry is expiring between requests. - Zero read and zero written. Nothing is being cached. The prompt may be under the minimum length, or the breakpoint may be missing or misplaced.
A ratio of 0.99 does not mean you saved 99% of the cost. Written tokens usually cost more than normal input, and read tokens cost less. For money, multiply each counter by its own price. The pricing chapter covers that calculation.
Common mistakes
- Reading only
input_tokensand concluding the prompt is small. With caching on, most tokens sit in the other two fields. - Judging the ratio from a single call. Measure over many calls on the same template.
- Mixing templates in one metric. A well-cached chat prompt hides a badly cached batch job.
Exercise
A request reports cachereadinputtokens = 3000, cachecreationinputtokens = 0, and input_tokens = 1000. What is the hit ratio, and what does it suggest about the prompt?
Show answer
The ratio is 3000 / (3000 + 0 + 1000) = 0.75. The stable prefix was read from the cache, and 25% of the input was uncached, which is likely the per-request content after the breakpoint. Nothing was written, so this was a repeat call within the cache lifetime.
Exercise
Your logs show cachecreationinputtokens = 5000 on every request, and cachereadinputtokens = 0. Name two likely causes.
Show answer
The prefix changes between calls, for example a timestamp placed before the static text. Alternatively, the entry expires before the next request arrives because traffic is too sparse for the cache lifetime.