AI Agents in Practice: From One Model Call to a Production System
Part 4
〇四How a Request Is Assembled
One line with the current time in the system prompt cuts the reusable prefix of an 8-round task from 83% to 21%
Take the same 8-round debugging task and assemble its requests two ways. In the first, the system prompt is fixed text; in the second, the system prompt starts with a line Current time 2026-11-20T10:05:00., updated every round. Everything else is identical.
Measured with the script later in this article, in the first case 83% of each request on average is identical, from the first byte, to the start of the previous request and can hit the prefix cache; in the second the figure is 21%. Converted with the caching price rules, the second way's input cost is 1% higher than using no cache at all.
One timestamp makes that difference because a cache only recognizes a prefix: two requests are compared byte by byte from the start, and comparison stops at the first byte that differs. This article looks at which parts a request is made of, in what order they are joined, and which harmless-looking changes cost everything after them its cache.
A request has three parts
Apart from parameters such as the model name and max_tokens (the cap on output tokens for one response), the content of a request to an Agent with tools has three parts:
- tool definitions (tools): each tool's name, description and parameter format written in JSON Schema (a specification for describing JSON data: field names, types and which fields are required);
- system prompt (system): the behavior rules and background the developer writes;
- message list (messages): the user and assistant messages taken apart in the previous article.
In the request's JSON the three are sibling fields with no visible order. Before reaching the model, though, the server joins them into one continuous token sequence, and then they do have an order. Anthropic's prompt caching documentation states the order the cache prefix follows: tools, system, messages. Tool definitions come first and the message list last.
That order decides how far each kind of change reaches:
| Where the change is | What is invalidated |
|---|---|
| tool definitions | everything: tools, system prompt, messages |
| system prompt | the system prompt and all messages after it |
| message k in the list | message k and every message after it |
| the end of the last message | only the new part |
The earlier a piece of content sits, the more it should stay unchanged. Within one Agent task, the tool definitions and the system prompt are sent every round and have no reason to change while the task runs, which makes them the best candidates for caching.
Measuring the shared prefix of two requests
Whether the prefix cache can hit can be estimated with a simple metric: serialize two consecutive requests in sending order, compare them from the first character, and take the identical part as a share of the later request.
This metric is an upper bound. Real caches do not compare characters: Anthropic works on content blocks and the cache breakpoints the developer sets (positions marked with cache_control); OpenAI's automatic caching needs at least 1,024 tokens in a request and matches prefixes in 128-token increments. Both cache only byte-identical prefixes, so where the character-level shared prefix is zero, the real cache will not hit either.
The script below simulates an 8-round task that calls grep_log once per round with a result of about 600 characters, and compares five ways of assembling the request. Save it as request_prefix.py; Python 3.9 or later, no third-party packages:
import json
import random
# ---------- The three parts of a request ----------
TOOLS = [
{"name": "read_config", "description": "Read an application config file and return its full text.",
"input_schema": {"type": "object", "properties": {
"path": {"type": "string", "description": "path of the config file"}},
"required": ["path"]}},
{"name": "grep_log", "description": "Find matching lines in the application logs of the last few minutes.",
"input_schema": {"type": "object", "properties": {
"pattern": {"type": "string", "description": "string to match"},
"minutes": {"type": "integer", "description": "minutes to look back, 1-120"}},
"required": ["pattern", "minutes"]}},
{"name": "query_slowlog", "description": "Return the slowest SQL statements from the database slow-query log.",
"input_schema": {"type": "object", "properties": {
"limit": {"type": "integer", "description": "number of rows to return, 1-20"}},
"required": ["limit"]}},
{"name": "explain_sql", "description": "Return the execution plan of one SQL statement.",
"input_schema": {"type": "object", "properties": {
"sql": {"type": "string", "description": "SQL statement to analyze"}},
"required": ["sql"]}},
]
SYSTEM = ("You help debug production performance problems. Collect evidence before concluding. "
"Every conclusion names the tool result it rests on; when unsure, say which data is missing. "
"Never modify any configuration or data; read-only operations only. ")
def round_messages(n):
"""Message history after round n: one tool call per round and a result of about 600 characters."""
msgs = [{"role": "user", "content": "The /orders endpoint got slow in the last 30 minutes. Find out why."}]
for k in range(1, n + 1):
msgs.append({"role": "assistant", "content": [
{"type": "tool_use", "id": f"toolu_{k:02d}", "name": "grep_log",
"input": {"pattern": f"/orders shard={k}", "minutes": 30}}]})
msgs.append({"role": "user", "content": [
{"type": "tool_result", "tool_use_id": f"toolu_{k:02d}",
"content": f"shard {k}: " + "WARN /orders took 2140ms; " * 24}]})
return msgs
def build_request(tools, system, messages):
"""Assemble the request body in the order tools -> system -> messages.
Anthropic computes the cache prefix in this order. Serialization uses a fixed key
order and no ASCII escaping, so identical content always gives identical bytes.
"""
body = {"tools": tools, "system": system, "messages": messages}
return json.dumps(body, ensure_ascii=False, separators=(",", ":"))
def common_prefix(a, b):
"""Number of identical characters at the start of two strings."""
n = min(len(a), len(b))
i = 0
while i < n and a[i] == b[i]:
i += 1
return i
# ---------- Five ways to assemble, 8 rounds each ----------
def variant(name, n, rng):
"""Return the request string for round n assembled in the given way."""
msgs = round_messages(n)
if name == "stable":
return build_request(TOOLS, SYSTEM, msgs)
if name == "time_in_system":
# put the current time into the system prompt: different every round
return build_request(TOOLS, f"Current time 2026-11-20T10:{n:02d}:00. " + SYSTEM, msgs)
if name == "shuffled_tools":
# tools come from a dict or plugin registry in no fixed order
tools = TOOLS[:]
rng.shuffle(tools)
return build_request(tools, SYSTEM, msgs)
if name == "edited_history":
# rewrite the first user message every round with the latest progress
msgs[0] = {"role": "user", "content": msgs[0]["content"] + f" ({n} steps done)"}
return build_request(TOOLS, SYSTEM, msgs)
if name == "time_at_tail":
# put changing information such as the time at the end of the last message
msgs[-1]["content"].append({"type": "text", "text": f"Current time 2026-11-20T10:{n:02d}:00"})
return build_request(TOOLS, SYSTEM, msgs)
raise ValueError(name)
def evaluate(name, rounds=8, seed=7):
"""From round 2 on, measure each request's shared prefix with the previous one,
and estimate the relative cost.
relative cost = (prefix chars x 0.1 + other chars x 1.25) / all chars, i.e. the prefix
is billed as a cache read and the rest as a cache write; 1.0 means no caching.
"""
rng = random.Random(seed)
prev, ratios, costs = None, [], []
for n in range(1, rounds + 1):
cur = variant(name, n, rng)
if prev is not None:
p = common_prefix(prev, cur)
ratios.append(p / len(cur))
costs.append((p * 0.1 + (len(cur) - p) * 1.25) / len(cur))
prev = cur
return sum(ratios) / len(ratios), sum(costs) / len(costs), len(cur)
if __name__ == "__main__":
for name in ["stable", "time_in_system", "shuffled_tools",
"edited_history", "time_at_tail"]:
ratio, cost, last = evaluate(name)
print(f"{name:<15} prefix={ratio:6.1%} relative_cost={cost:.2f} last_chars={last:,}")
Output:
stable prefix= 83.2% relative_cost=0.29 last_chars=8,275
time_in_system prefix= 20.7% relative_cost=1.01 last_chars=8,309
shuffled_tools prefix= 2.1% relative_cost=1.23 last_chars=8,275
edited_history prefix= 27.0% relative_cost=0.94 last_chars=8,290
time_at_tail prefix= 82.3% relative_cost=0.30 last_chars=8,333
The 0.1 and 1.25 in the relative cost come from the price multipliers in Anthropic's documentation: reading the 5-minute cache costs 0.1 times the base input price, writing it 1.25 times. The model assumes a cache breakpoint at the end of every request, so the prefix is billed as a read and the rest as a write. It is rough, since it ignores the part billed at the normal price when no breakpoint is set, but it is enough to rank the five methods.
The five results one by one
stable: 83%. Tools and system prompt do not change, and the message list only grows at the end. The prefix does not reach 100% because the interaction unit added each round (860 characters) is not cached yet; by round 8 it is about 10% of the request, earlier rounds it is a larger share, and the average comes to 17%. This is the ceiling for a full-history resend.
time_in_system: 21%. The timestamp sits at the start of the system prompt and changes every round. What remains of the prefix is the tool definitions at the very front (1,021 characters) plus the unchanged first few characters of the system prompt. The system prompt and every message are recomputed and billed at the write price, so the cost ends up slightly above using no cache.
shuffled_tools: 2.1%. Tool definitions come in a random order each round. This is not rare in practice: tools come from a dict or a set (a Python set guarantees no order), or from several plugins or MCP servers (Article 25 covers MCP, a protocol that exposes tools to an Agent as separate services) that register asynchronously at startup in a different order each time. Tool definitions sit at the very front of the request, so changing them invalidates everything after them. The 2.1% comes from the occasional round where the first tool happens to stay the same.
edited_history: 27%. Every round appends "(n steps done)" to the first user message. The whole history after that message loses its cache; only the tools and system prompt remain reusable. The intent behind such changes is usually "keep the model aware of progress", and the price is recomputing the whole history every round.
time_at_tail: 82%. The same time information, placed at the end of the last message. The prefix rate is within 1 percentage point of stable: the timestamp changes every round, but it is at the end, and next round the new content pushes it into the history, where it becomes part of a stable prefix.
The conclusion fits in one sentence: put changing content late and unchanging content early.
Serialization can break the prefix too
Even with identical content, a different serialization produces different bytes. build_request sets two things on purpose:
ensure_ascii=False: do not turn non-ASCII characters into\uXXXXescapes. This affects size, not consistency, but the two settings must not be mixed;separators=(",", ":"): fixed separators.
A subtler source is dictionary key order. Since Python 3.7 dicts keep insertion order, but if a tool's JSON Schema is merged from several sources (read from a file first, then given a default description in code), the same tool may have a different key order in two requests. json.dumps(..., sort_keys=True) normalizes the order, but it also changes how the tool definitions are written; pick one way for the whole system and serialize in one place only.
A few lines show the effect of key order:
import json
a = {"name": "grep_log", "description": "search logs", "input_schema": {"type": "object"}}
b = {"description": "search logs", "name": "grep_log", "input_schema": {"type": "object"}}
print(a == b) # equal as Python objects
print(json.dumps(a, ensure_ascii=False) == json.dumps(b, ensure_ascii=False))
print(json.dumps(a, sort_keys=True) == json.dumps(b, sort_keys=True))
Output:
True
False
True
The two dicts are equal in Python and their serialized strings are not; to the cache they are two different prefixes.
What tempts people into the system prompt
The timestamp is one example. Information that often gets put into the system prompt yet changes every round or every task includes:
- the current time and date;
- the current user's name, permissions and preferences;
- the working directory, Git branch, recently changed files;
- task progress and remaining budget.
This information is useful to the model; the question is not whether to provide it but where. Sort it by how often it changes:
| How often it changes | Examples | Where it goes |
|---|---|---|
| not per task | behavior rules, tool definitions, output format | tool definitions and system prompt, fixed text |
| once per task | user identity, project information, working directory | start of the first user message, not changed during the task |
| every round | current time, remaining budget, latest progress | end of the last message, or returned as a tool result |
The second layer goes into the first user message, written once per task, and every later request in that task uses it as a stable prefix. The third layer, if the model really needs it every round, is attached to the end of the newest message, where it naturally becomes history next round; if the model needs it only occasionally, a tool such as get_current_time lets it ask on demand.
Changing tool definitions: loading on demand has a cache cost
Some Agents add or remove tools by task phase, for example adding the file-writing tool only in the "fix" phase. That is sound from a permissions point of view (Article 48), but it changes the very front of the request, and every change invalidates the whole cache. Anthropic's documentation also notes that changing parameters such as tool_choice (whether the model must call a tool, and which) affects the cache of the message part.
If the tool set has to change by phase, there are two compromises:
- declare the full tool set from the start and check at run time whether the current phase allows the call, filling in an error result when it does not (the
is_errorfrom Article 03); - keep phase switches to two or three per task and accept one prefix recomputation after each switch.
Article 24 discusses retrieval and on-demand loading when there are dozens of tools, and cache cost is one of the items to count then.
Assemble in one function
In code, this article's advice amounts to assembling requests in exactly one place:
- tool definitions are generated once when the task starts, sorted, and never changed;
- the system prompt is a constant;
- the message list is append-only; any rewrite of existing messages (Article 03's truncation, Article 12's summaries) is an explicit, logged operation that knows which part of the cache it invalidates;
- before every request, record the shared prefix length with the previous request as a monitoring metric.
The last item can reuse common_prefix directly. Together with the cache_read_input_tokens in the usage field mentioned in Article 02, it separates two cases: a high shared prefix with few cache reads means the cache expired (Anthropic's default lifetime is 5 minutes); a low shared prefix means the assembly is at fault.
That covers the order of request assembly. The next article returns to the loop itself: Article 01's loop has two exits, the model declaring it is done and a step limit, and in real tasks neither is enough.