AI Agents in Practice: From One Model Call to a Production System
Part 3
〇三The Structure of the Message List: Roles, Content Blocks and Tool-Call Pairing
Before deleting a message, make sure it is not bound to another one
A debugging Agent gained a "keep only the last 20 messages" rule to control the context growth computed in the previous article. After release, short tasks worked as before, and long tasks began failing consistently from about round 11: the model API returned HTTP 400 (a malformed request the server refuses to process), with an error saying some tool result had no matching tool call.
The truncation itself was one line, messages[-20:], with nothing visibly wrong. The problem is that messages in the list are not independent of each other: some come in pairs, and deleting one makes the other invalid input. This article takes the message list apart, finds which messages are bound together, and looks at where a cut can safely go.
The format in Article 01 was simplified
Article 01 used a flat message format: every message had a role and a string content, and each tool result was a separate tool message. Real APIs are more detailed, and the two main providers write it differently.
Take the Anthropic Messages API:
- the system prompt is not a message but the top-level
systemparameter; messagescontains only two roles,userandassistant;- each message's
contentcan be a list of content blocks. A content block is an object with atypefield; common types aretext,image,tool_use(a tool call written by the model) andtool_result(a tool result filled in by the runtime); - tool results go inside
usermessages. From the API's point of view, a tool result is input supplied from "the user's side".
OpenAI Chat Completions is closer to Article 01: the assistant message carries a tool_calls array whose arguments is a JSON string, and each result is a separate message with role: "tool" that points back to its request through tool_call_id.
| Anthropic Messages | OpenAI Chat Completions | |
|---|---|---|
| System prompt | top-level system parameter | a message with role system or developer |
| Tool call | tool_use block in an assistant message; arguments are a JSON object | tool_calls on an assistant message; arguments are a JSON string |
| Tool result | tool_result block in a user message | one tool message per result |
| Pairing fields | tool_use.id ↔ tool_result.tool_use_id | tool_calls[].id ↔ tool_call_id |
Both formats express the same thing. The code in this article uses Anthropic's, because content blocks represent "text and tool calls in one message" more clearly; the rules hold the same way in OpenAI's format.
The pairing rules
Anthropic's tool-use documentation is explicit about where tool_use and tool_result may appear. Written as checkable rules, there are four:
- The first message has role
user. - Every
tool_usein an assistant message has atool_resultwith the sametool_use_idin the very next user message. No other message may sit between them. - Every
tool_resultin a user message has a matchingtool_usein the assistant message right before it. - If a user message contains both
tool_resultblocks and text, thetool_resultblocks come first.
Breaking rule 2 or 3 gets a 400 response whose error message names the message and the id that did not match. OpenAI's Chat Completions validates the same thing: an assistant message with tool_calls that is not followed by a tool message for each tool_call_id, or a tool message with no assistant message that issued it, is rejected as well.
The reason for these rules is easy to see. In training, the model sees tool-use data where calls and results always come in pairs; a call with no result, or a result with no call, is semantically incomplete input. Rejecting such input at the server before it reaches the model is easier to debug than letting the model continue on a broken history.
A history you can validate
The code below builds an 8-message debugging history (the same task as Article 01), writes a validate that checks the four rules above, then truncates the history four ways and checks which results stay valid. Save it as message_pairing.py; Python 3.9 or later, no third-party packages:
import json
# ---------- A history in the Anthropic Messages API format ----------
# system is not part of messages but a top-level request field; only messages are built here.
LOG = "\n".join(f"2026-11-20T10:{m:02d}:13 WARN /orders took 2{m % 10}40ms"
for m in range(30))
def tool_use(id_, name, args):
"""A tool-call block in an assistant message. The server generates id_; here it is written by hand."""
return {"type": "tool_use", "id": id_, "name": name, "input": args}
def tool_result(id_, content, is_error=False):
"""A tool-result block in a user message. tool_use_id must equal the id of its tool_use."""
block = {"type": "tool_result", "tool_use_id": id_, "content": content}
if is_error:
block["is_error"] = True
return block
def text(s):
return {"type": "text", "text": s}
HISTORY = [
{"role": "user", "content": [text("The /orders endpoint got slow in the last 30 minutes. Find out why.")]},
{"role": "assistant", "content": [
text("Check the config and the recent logs first."),
tool_use("toolu_01", "read_config", {"path": "app.conf"}),
tool_use("toolu_02", "grep_log", {"pattern": "/orders", "minutes": 30}),
]},
{"role": "user", "content": [
tool_result("toolu_01", "db.pool_size=10\ndb.timeout_ms=3000\n"),
tool_result("toolu_02", LOG),
]},
{"role": "assistant", "content": [
tool_use("toolu_03", "query_slowlog", {"limit": 2}),
]},
{"role": "user", "content": [
tool_result("toolu_03", json.dumps(
[{"sql": "SELECT * FROM orders WHERE user_id = ?", "avg_ms": 1870}])),
]},
{"role": "assistant", "content": [
tool_use("toolu_04", "explain_sql",
{"sql": "SELECT * FROM orders WHERE user_id = ?"}),
]},
{"role": "user", "content": [
tool_result("toolu_04", json.dumps({"type": "ALL", "rows": 1200000, "key": None})),
]},
{"role": "assistant", "content": [
text("orders.user_id has no index; the query scans ~1.2M rows."),
]},
]
# ---------- Validation: check messages against the documented pairing rules ----------
def blocks(msg, kind):
"""Return the content blocks of one type in a message."""
return [b for b in msg["content"] if b["type"] == kind]
def validate(messages):
"""Return the first protocol error found, or None if there is none.
Rules:
1. the first message is a user message;
2. every tool_use in an assistant message has a tool_result in the very next user message;
3. every tool_result in a user message matches a tool_use in the assistant message right before it;
4. in a user message, tool_result blocks come before every other block.
"""
if not messages or messages[0]["role"] != "user":
return "messages.0: the first message must be a user message"
for i, msg in enumerate(messages):
if msg["role"] == "assistant":
ids = [b["id"] for b in blocks(msg, "tool_use")]
if not ids:
continue
nxt = messages[i + 1] if i + 1 < len(messages) else None
got = {b["tool_use_id"] for b in blocks(nxt, "tool_result")} if nxt else set()
missing = [x for x in ids if x not in got]
if missing:
return f"messages.{i}: tool_use ids without a tool_result right after: {missing}"
else:
results = blocks(msg, "tool_result")
if not results:
continue
prev = messages[i - 1] if i > 0 else None
if prev is None or prev["role"] != "assistant":
ids = [b["tool_use_id"] for b in results]
return f"messages.{i}: tool_result with no tool_use in the previous assistant message: {ids}"
known = {b["id"] for b in blocks(prev, "tool_use")}
orphan = [b["tool_use_id"] for b in results if b["tool_use_id"] not in known]
if orphan:
return f"messages.{i}: tool_result with no tool_use in the previous assistant message: {orphan}"
types = [b["type"] for b in msg["content"]]
if types[:len(results)] != ["tool_result"] * len(results):
return f"messages.{i}: tool_result blocks must come before text"
return None
def size(messages):
"""Characters in the serialized message list, as an approximation of its size."""
return len(json.dumps(messages, ensure_ascii=False))
# ---------- Four ways to truncate ----------
def keep_last(messages, n):
"""Method A: keep only the last n messages."""
return messages[-n:]
def drop_largest(messages):
"""Method B: drop the single largest message."""
i = max(range(len(messages)), key=lambda k: size([messages[k]]))
return messages[:i] + messages[i + 1:]
def keep_units(messages, budget):
"""Method C: keep the first (task) message, then add interaction units from the end
backwards until the next one would exceed budget.
Interaction unit = one assistant message + the user message right after it that holds
its tool results. Cutting in front of an assistant message never splits a pair.
"""
head, rest = messages[:1], messages[1:]
starts = [i for i, m in enumerate(rest) if m["role"] == "assistant"]
kept = []
for s in reversed(starts):
candidate = rest[s:]
if size(head + candidate) > budget:
break
kept = candidate
return head + kept
def clear_results(messages, keep_recent=1, placeholder="[result omitted; call the tool again to fetch it]"):
"""Method D: keep every message, replace the content of older tool_results with a stub.
keep_recent: how many of the latest user messages with tool_results stay untouched.
"""
out = json.loads(json.dumps(messages)) # deep copy; the original history is untouched
idx = [i for i, m in enumerate(out) if blocks(m, "tool_result")]
for i in idx[:-keep_recent]:
for b in blocks(out[i], "tool_result"):
b["content"] = placeholder
return out
if __name__ == "__main__":
print(f"original n={len(HISTORY)} chars={size(HISTORY):,} error={validate(HISTORY)}")
trials = {
"A keep_last(4)": keep_last(HISTORY, 4),
"B drop_largest": drop_largest(HISTORY),
"C keep_units": keep_units(HISTORY, budget=1000),
"D clear_results": clear_results(HISTORY),
}
for name, msgs in trials.items():
print(f"{name:<15} n={len(msgs)} chars={size(msgs):,} error={validate(msgs)}")
Output (the data is fixed, so every run is identical):
original n=8 chars=2,746 error=None
A keep_last(4) n=4 chars=603 error=messages.0: tool_result with no tool_use in the previous assistant message: ['toolu_03']
B drop_largest n=7 chars=1,166 error=messages.1: tool_use ids without a tool_result right after: ['toolu_01', 'toolu_02']
C keep_units n=6 chars=855 error=None
D clear_results n=8 chars=1,405 error=None
This validator covers only the pairing rules; real APIs also check field types, empty content blocks and more. But the 400 error from the opening reproduces with it locally.
Why two reasonable-looking truncations fail
Method A: keep the last n. The last 4 messages are "result 3, call 4, result 4, answer". The new list starts with the user message holding the result of toolu_03, and the assistant message that issued toolu_03 has been cut off. Rule 3 is broken.
Moving the cut does not help. After the task message, the list alternates assistant, user. A cut that lands on an assistant message makes the new list start with an assistant message, breaking rule 1; a cut that lands on a user result message breaks rule 3. This is why the Agent in the opening worked on short tasks and failed consistently on long ones: below 20 messages no truncation happened, and above that every truncation produced an invalid list.
Method B: drop the largest message. The largest message is the result message holding 30 log lines. Once it is gone, both tool_use blocks in the first assistant message have no result. Rule 2 is broken.
The idea behind it is right: the previous article showed that request size comes mostly from tool results, so dropping the large ones pays off most. What is wrong is the granularity. The message holding the tool results and the message that issued the calls form one whole; delete only one of them and half a structure is left behind.
Interaction units: the smallest thing you can cut
Call "an assistant message with tool_use blocks, plus the user message right after it holding all the matching tool_result blocks" an interaction unit. The pairing rules apply only inside a unit; there are no constraints between units. So:
- when deleting, delete whole units;
- when cutting, cut between units, that is, in front of an assistant message.
Method C does exactly that. It always keeps the first task message (without it the model does not know the task, and the list has to start with a user message), then adds units from the end backwards until one more would exceed the budget. With a 1,000-character budget it keeps the task message and the last 5 messages (the query_slowlog and explain_sql units plus the final answer), drops the first unit with the 30 log lines, and the result is valid.
One detail: the first kept unit starts with an assistant message and follows the task message directly, so the roles still alternate user, assistant. Put the cut in front of a user result message instead and you are back to Method A's problem.
Replacing content without deleting structure
Method D takes another route: it deletes no message, and only replaces the content of older tool_result blocks with a stub saying a result used to be here and can be fetched again. The pairing structure stays intact and the size drops from 2,746 to 1,405 characters.
Compared with Method C it has two advantages:
- the model still sees which tools it called before and with which arguments, so it does not repeat the same calls just because the history vanished;
- the stub tells the model "the content was omitted", rather than letting it believe the step never happened.
Anthropic offers a server-side version of this in the API: the tool-result clearing strategy in context editing replaces older tool results with placeholder content once the context passes a configured threshold, keeping the most recent ones.
The cost comes up in the next article: both C and D change content near the front of the list, so the prefix cache built up by earlier requests stops working from the changed position. The size reduction from truncation and the recomputation caused by cache invalidation have to be weighed together.
Parallel calls make units larger
In Article 01 the model requested read_config and grep_log in one response. By the pairing rules, both results go into the same user message.
So a unit's size depends on how many calls the model issued at once. If the model reads 5 files in parallel and each result is 3,000 tokens, that unit holds over 15,000 tokens, and you cannot delete the results of just two of the files: either the whole unit goes, or Method D replaces some of the results with stubs. Method D is more flexible here because its granularity is a single content block, not a whole message.
Failed tools need a result too
The pairing rules have one easily missed consequence: when a tool fails, a tool_result still has to be filled in.
In practice there are three ways a runtime "forgets" to do so:
- the tool raises, and the runtime's
tryblock logs the exception without appending anything to the message list; - the tool times out, the runtime cancels it and moves straight to the next round;
- the tool needs human confirmation, the user clicks deny, and the runtime treats the call as if it never happened.
In all three, the next request contains a tool_use with no result, the request is rejected and the whole task stops. The correct move is to fill in a result with is_error: true whose content states the reason, such as "timeout after 30s" or "user denied this operation". Reading it, the model can switch tools, adjust arguments or explain the situation to the user.
With the tool_result function above:
from message_pairing import tool_result
# Tool timed out: still fill in a result, marked as an error, so the model can decide what to do
block = tool_result("toolu_05", "timeout after 30s: query_slowlog did not respond",
is_error=True)
print(block)
Output:
{'type': 'tool_result', 'tool_use_id': 'toolu_05', 'content': 'timeout after 30s: query_slowlog did not respond', 'is_error': True}
Classifying tool failures (which can be retried, which need another tool, which need a human) is Article 42. Here only one thing matters: every tool_use gets a result, whether it succeeded or failed.
Validate before sending
validate can go straight into the loop of Article 01's run_agent, run once before every model call. Its time is proportional to the number of messages; a list of a few dozen messages takes microseconds, negligible next to a model call measured in seconds.
Its value is that it moves the error earlier. Without local validation you see a 400 from the server and have to work back to which truncation or result-filling code broke the list; with it, the error surfaces the moment the request is built and the stack trace points at the code responsible.
That settles which parts of the message list can change and at what granularity. The next article looks at the whole request: in what order the system prompt, tool definitions and message list are joined, and how changing that order affects the prefix cache.