Sub topic 3
Tools, System Prompts, and Growing Conversation History
Assume you can call an LLM API, understand tokens, and read short Python code. Prompt caching reuses the provider’s work only when the cached prefix remains identical.
Tools and conversation history
Tool definitions usually belong near the start of a request. Their names, descriptions, parameter schemas, and order must stay unchanged. A system prompt should also remain stable. Put changing data, the latest user message, and tool results after these stable sections.
In a multi-turn conversation, earlier messages become part of the prefix. Editing, summarizing, or reordering old messages can invalidate the cache from the edit onward.
Finding and fixing cache misses
Log the prompt components and usage counters for representative requests. Common causes include:
- A current timestamp placed before the cached content.
- A request ID, random value, or changing policy version in the prefix.
- Reordered tools or modified tool descriptions.
- Edited conversation history.
- A different model, account, region, or routing key.
- A prompt shorter than the provider’s cache minimum.
Move per-request values to the end. Freeze tool ordering and system-prompt formatting. Compare the first differing token or serialized block between a hit and a miss.
Parallel requests and warming
A first request may create the cache while concurrent requests arrive before the entry is available. Providers differ in whether those requests share the warming operation. At high volume, expect a few initial misses and measure the result rather than assuming every request hits.
Routing hints and cache keys
Some providers expose routing or prompt-cache key fields. Use a stable key for requests that share the same long prefix. Do not put a user ID into a shared key unless isolation requires it. A key that is too broad can mix incompatible prompts; one that is too specific reduces reuse.
When caching is worth it
Caching pays when the reusable prefix is long, repeated often, and expensive to process. Compare:
- Input-token savings on cache hits.
- Cache-write cost on the first request.
- Cache lifetime and expected hit rate.
- Added complexity and monitoring work.
A short prompt, low request repetition, or rapidly changing history may cost more to cache than it saves.
def cache_hit_ratio(cache_read, cache_written, uncached):
total = cache_read + cache_written + uncached
return cache_read / total if total else 0.0
print(cache_hit_ratio(4000, 0, 60)) # 0.9852...Exercise
A request changes only the order of two tool definitions. Why might the cache miss, and what is the fix?
Show answer
The serialized prefix changed. Preserve a deterministic tool order across requests.