Application Response Caching
Introduction
Welcome back to Reducing LLM Work and Cost in Python. Earlier, we reduced unnecessary input context and controlled output length. Now the optimization question changes: instead of making a request smaller, can we avoid making a repeated request at all?
An application-level response cache stores a completed answer in our Python application and returns it when the same model receives the exact same prompt. This provider-independent layer can skip paid work before a request reaches any API. We will create exact-match keys, record hits and misses, count avoided calls, and estimate the dollars saved through reuse.
Create Exact Match Cache Keys and Stored Result Shapes
Before contacting a provider, we need a stable definition of sameness. In this lesson, a request matches only when both the model and prompt are identical. A similar question is not enough. We combine those values with a separator, encode the result as UTF-8, and create a SHA-256 hash.
CacheEntry represents information that remains in the cache. It stores the response text and the cost of the original live call. We need that cost later to estimate avoided spending.
Result represents the value returned for the current request. It tells the application whether the answer came from the cache and whether this request created any new cost. The model belongs in the key because two models can answer the same prompt differently. Sharing one model's response with another model would produce an incorrect cache hit.
Calculate the Cost of a Live Provider Call
The cache must know how much a provider call cost before it can estimate the value of reusing that response. As in earlier billing work, provider-reported usage is our billing source of truth. We separate fresh input, cache-write input, and cached input, then charge each category at its configured rate.
Two defensive details deserve explanation, because both reflect how real usage objects behave.
First, we read the cache fields with getattr and a default. The cache_write_tokens field is not universal: on GPT-5.6 models and later, Standard pay-as-you-go deployments support prompt cache breakpoints and expose cache_write_tokens, while Provisioned Throughput managed deployments continue to support prompt caching but do not support breakpoints or expose that field. Older models behave differently again, since on models before the GPT-5.6 family there is no extra charge to write to the cache. Reading the field directly would raise AttributeError on those deployments, and defaulting to 0 degrades gracefully to the older pricing model.
Second, we clamp fresh at zero. input_tokens is the reported total, and cached_tokens and cache_write_tokens are disjoint subsets of that total, so subtracting both leaves the fresh tokens. The clamp is a defensive guard rather than a correction for overlapping categories: on deployments where cache_write_tokens is absent, getattr supplies 0, and the clamp keeps an unexpected usage shape from producing a negative token count that would silently reduce the computed cost. If you ever see fresh clamping in production, inspect the raw usage object rather than trusting the derived breakdown.
Each input category uses its own rate, and output tokens are charged at the output rate. As in earlier billing work, we charge usage.output_tokens once rather than adding reasoning tokens separately.
The returned value is the original cost of a live response. When that response is reused later, this value becomes the baseline for estimating how much a repeated provider call would have cost.
Implement the Cache Miss Path
Next, we connect the cache structure to a live provider request. The constructor prepares an empty dictionary and the counters we will report. The dictionary maps each hashed key to a CacheEntry.
This is the miss path because no reusable entry exists yet. We send the prompt to the provider, calculate the real cost from the returned usage, and store both the text and cost under the key. The miss counter increases only after the provider call succeeds.
The returned Result contains the new response, its actual request cost, and False for cache_hit. The next step is to place a lookup before this paid branch so that repeated requests can return immediately.
Supporting Image: Cache Hit and Miss Flow
The cache now has a complete miss path. Before adding the lookup, it helps to visualize the decision that must happen first: an existing key should return stored data, while an absent key should continue to the provider call. The following diagram summarizes that flow.
The diagram emphasizes that the lookup is positioned before client.responses.create(). A hit exits with the stored response and no new provider cost. A miss continues to the live call, stores the resulting entry, and returns the newly generated response. With that flow in mind, we can implement the hit branch and its avoided-spend accounting.
Implement the Cache Hit Path and Avoided Spend Tracking
A cache hit must be checked before client.responses.create() runs. If the key is present, we already have the text and the cost of the original call. We can return immediately without contacting the provider.
The hit branch returns the stored text, sets request_cost to exactly 0.0, and marks the result as a hit. It also increments hits, which represents one provider call avoided. The stored original_cost is added to estimated_savings because that is the known cost of the call we did not repeat.
This is different from provider prompt caching. Provider caching still sends a request to the model, although some input tokens may receive a lower rate. Application-level response caching skips the provider call itself, so it prevents the request cost rather than merely discounting part of it. The word estimated reminds us that a new call might have used a different number of tokens, so the saved amount uses the original call as a clear baseline.
Run the Repeated Workload and Interpret the Savings Report
Now we create one ResponseCache, send the five-prompt workload through it, and add each returned request_cost to actual_spend. The status text makes each cache decision visible.
The report uses the Result object as the accounting record. Misses contribute their live call costs, while hits contribute zero to actual spending. When the complete program runs, it produces this verified output:
There are only two unique prompts, so the first occurrence of each prompt is a miss. The remaining three requests are exact matches and become hits. Therefore, only two provider calls are made. The actual spend is the sum of the two miss costs, while the estimated savings add the original cost for each avoided repeat. The zero-dollar cost on every hit confirms that no provider request was sent.
Conclusion and Next Steps
Application-level response caching prevents redundant paid work by checking a deterministic model-and-prompt key before the provider call. A miss sends the request, calculates its real cost, stores the response, and returns a paid result. A hit returns the stored text, reports zero request cost, counts an avoided call, and adds the stored original cost to the savings estimate.
We also separated the cache entry from the current result. The entry preserves information needed for future reuse and savings analysis, while the result tells the current application whether it received a hit or miss. This makes cache behavior measurable and keeps the design independent of provider prompt-caching features. Our call_cost() helper reads provider usage defensively, so the same accounting code works across models that do and do not report cache writes.
In the practice section that follows, we will build each part of this cache and verify its accounting with repeated prompts. Next, we will explore how provider-level prompt caching can reduce the cost of requests that still need to reach the model. You are ready to make redundant model work disappear one exact match at a time.
