Sub topic 5
Laying out prompts: stable content first, variable content last
This chapter assumes you can call an LLM API, know what tokens and context windows are, and can read short Python snippets. It also assumes you know that a cache hit needs an identical prompt prefix, which an earlier chapter covered. Here you will apply that rule to the way you build prompts.
The layout rule
The provider matches your prompt from the first token onward. The first token that differs ends the reusable part. Everything after it must be processed again.
So order the prompt by how often each part changes:
- Tool definitions and system instructions, which change only when you deploy.
- Reference material such as policies, documents, and few-shot examples, which change per customer or per document.
- Conversation history, which grows by appending.
- The current user question and any per-request values, which change on every call.
A common mistake: the timestamp at the top
Many prompts start with the current time. The value changes on every call, so the first token that differs is near the start, and no two prompts share a useful prefix.
from datetime import datetime, timezone
STATIC_INSTRUCTIONS = "You are a support assistant. Follow the policy below.\n" + open("policy.md").read()
def bad_prompt(question):
# The timestamp changes on every call, so no two prompts share a prefix.
now = datetime.now(timezone.utc).isoformat()
return f"Current time: {now}\n{STATIC_INSTRUCTIONS}\nQuestion: {question}"
def good_prompt(question):
# Stable text first, per-request values last.
now = datetime.now(timezone.utc).isoformat()
return f"{STATIC_INSTRUCTIONS}\nCurrent time: {now}\nQuestion: {question}"good_prompt produces the same long opening on every call. Only the last two lines differ. The model sees the same information either way, so you lose nothing by moving the timestamp.
Other values that belong at the end
Anything that varies per request should go after the stable part:
- Request IDs and session IDs.
- The user's name, locale, or account details.
- Retrieved search results, when they differ on each query.
- The date, if the model needs it.
If a value is needed early for the model to behave correctly, ask whether a coarser version would do. A date changes once a day, while a full timestamp changes every second. A date-only value gives a prefix that stays valid for a whole day.
Placing the breakpoint
With explicit caching, you mark the end of the stable part. Put the marker on the last block that is identical across requests, not on the final block of the prompt.
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)The policy carries the marker. The user question comes after it and changes freely. If you put the marker on the question instead, the provider would try to store a prefix that never repeats.
With automatic caching, you place no markers. The same layout rule applies, because the provider looks for the longest matching prefix itself.
Trade-offs in ordering
Static-first ordering sometimes conflicts with prompt quality. Some guidance for the model works better near the question, such as a reminder of the output format. You can put a short reminder after the variable part. It adds a few tokens that are never cached, but the large block before it stays reusable.
Also keep serialization stable. A document built from a dictionary with unordered keys, or from a list sorted in a different order each time, looks the same to you but not to the provider. Sort keys and use a fixed format.
Exercise
A prompt has this order: system instructions, the user's name, a 5,000-token policy document, then the question. Why does it cache poorly across users, and how would you fix it?
Show answer
The user's name differs between users and sits before the policy, so the shared prefix stops right after the system instructions and the policy is reprocessed every time. Move the name after the policy, next to the question, so the system instructions and policy form one long identical prefix.