Sub topic 7
Cutting on Turn Boundaries and Keeping Tool Calls Paired
The earlier chapters trim history by token count. A token count doesn't know that some messages only make sense next to others. If you cut between two messages that belong together, the request can fail, or the model can see half of an exchange and answer from a distorted picture.
This chapter assumes you have read the sliding-window and pinning chapters. You should know the message roles (system, user, assistant, tool) and the shape of a tool call in a chat API. The examples use the OpenAI-style format, where an assistant message carries a tool_calls list and results come back as role: "tool" messages. The ideas carry over to other formats, and the differences are noted where they matter.
What a turn is
A turn is one user request plus everything the system does until it is ready for the next user message. In a plain chat, that is a user message and an assistant reply. In an application with tools, a turn can contain many messages:
- The user message.
- An assistant message that requests one or more tool calls.
- One tool message per requested call.
- Possibly more rounds of steps 2 and 3.
- A final assistant message with the answer.
The cut points that are always safe fall immediately before a user message that starts a new turn. Cutting anywhere else risks separating messages that depend on each other.
Why a cut in the wrong place causes trouble
| Cut falls... | What the model or API sees | Typical result |
|---|---|---|
| Between a tool call and its result | A call with no answer, or a result with no call | The API rejects the request with a validation error |
| Between the user message and the assistant reply | An assistant reply with no question | Accepted, but the model may answer oddly or repeat itself |
| Right before an assistant message | The window starts with an assistant message | Rejected by some APIs, confusing for others |
| Before a user message that starts a turn | A complete turn | Safe |
The first row is the serious one. Most providers enforce pairing. A tool result must refer to a tool call that appears earlier in the same request, and a tool call must be followed by its results before the conversation continues. A request that breaks this rule fails with an error, and the same history fails again on every retry until you fix it. That makes it worse than a bad answer, because the user's conversation stops working.
The cut position is not the only way to break pairing. Any code that removes or reorders individual messages can do it. That includes pinning code that copies "important" messages from the middle of the history, and code that shrinks a large tool result by deleting the message.
The pairing rules in detail
In the OpenAI-style format:
- Each entry in an assistant message's
tool_callshas anid. - Each tool message has a
tool_call_idthat must match one of those ids. - The tool messages must come right after the assistant message that made the calls.
- Parallel calls produce several tool messages after one assistant message. All of them must be present.
In the Anthropic-style format, the assistant message holds tool_use blocks, and the answers are tool_result blocks inside the next message, which has the user role. This matters for turn detection. A user message that contains only tool results does not start a new turn. It continues the current one. Counting every user message as a turn start would split pairs apart.
This helper handles both formats:
def starts_turn(message):
"""True if the message begins a new user turn."""
if message["role"] != "user":
return False
content = message["content"]
if isinstance(content, str):
return True
# Block format: a user message made only of tool results continues the turn.
return not all(block.get("type") == "tool_result" for block in content)Cutting by turns instead of by messages
The sliding window from the earlier chapter walks backward one message at a time. The turn-based version walks backward one turn at a time, and a turn is accepted or rejected as a whole. The code below is self-contained and uses the OpenAI-style format.
def estimate_tokens(message):
# About 4 characters per token, plus a small per-message overhead.
text = message.get("content") or ""
for call in message.get("tool_calls", []):
text += call["function"]["name"] + call["function"]["arguments"]
return len(text) // 4 + 4
def starts_turn(message):
if message["role"] != "user":
return False
content = message["content"]
if isinstance(content, str):
return True
return not all(block.get("type") == "tool_result" for block in content)
def group_turns(messages):
turns = []
for message in messages:
if starts_turn(message) or not turns:
turns.append([])
turns[-1].append(message)
return turns
def truncate_by_turns(messages, max_input_tokens):
system = [m for m in messages if m["role"] == "system"]
rest = [m for m in messages if m["role"] != "system"]
budget = max_input_tokens - sum(estimate_tokens(m) for m in system)
kept = []
for turn in reversed(group_turns(rest)):
cost = sum(estimate_tokens(m) for m in turn)
if cost > budget:
break
kept.append(turn)
budget -= cost
kept.reverse()
# A leading group that does not start with a user message is an orphan.
while kept and not starts_turn(kept[0][0]):
kept.pop(0)
if rest and not kept:
raise ValueError("The latest turn alone does not fit in the budget.")
return system + [m for turn in kept for m in turn]Two details are worth noting. The loop stops at the first turn that does not fit. It does not skip it and try an older, smaller one, because that would leave a gap in the conversation. And when even the newest turn is too big, the function raises an error. Silently sending a request without the user's current message would be worse.
Checking the result with a validator
A small validator makes pairing bugs visible. Run it in tests, and in production just before sending a request. A cheap check there turns a confusing provider error into a clear message from your own code.
def find_pairing_errors(messages):
errors = []
pending = set() # tool call ids that are still waiting for a result
for i, message in enumerate(messages):
role = message["role"]
if role == "tool":
call_id = message["tool_call_id"]
if call_id in pending:
pending.discard(call_id)
else:
errors.append(f"message {i}: tool result {call_id} has no matching call")
continue
if pending:
errors.append(f"message {i}: calls {sorted(pending)} have no result")
pending = {c["id"] for c in message.get("tool_calls", [])}
if pending:
errors.append(f"end of list: calls {sorted(pending)} have no result")
return errors
def tool_call(call_id, city):
return {
"role": "assistant",
"content": None,
"tool_calls": [{
"id": call_id,
"type": "function",
"function": {"name": "get_weather", "arguments": '{"city": "%s"}' % city},
}],
}
history = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What's the weather in Oslo?"},
tool_call("call_1", "Oslo"),
{"role": "tool", "tool_call_id": "call_1", "content": "4 C, light snow"},
{"role": "assistant", "content": "It is 4 C with light snow in Oslo."},
{"role": "user", "content": "And in Bergen?"},
tool_call("call_2", "Bergen"),
{"role": "tool", "tool_call_id": "call_2", "content": "7 C, rain"},
{"role": "assistant", "content": "It is 7 C and raining in Bergen."},
]
naive = history[-6:] # keep the last six messages, ignoring structure
print(find_pairing_errors(naive))
safe = truncate_by_turns(history, max_input_tokens=60)
print([m["role"] for m in safe])
print(find_pairing_errors(safe))The output is:
['message 0: tool result call_1 has no matching call']
['system', 'user', 'assistant', 'tool', 'assistant']
[]The naive tail starts with the result for call_1, but the call that produced it was cut off. The turn-based version dropped the whole Oslo turn and kept the Bergen turn intact.
Edge cases
The turn in progress. While the application runs a tool loop, the newest turn ends with a tool call or a tool result, not an assistant answer. That turn must always stay whole, because the model needs it to continue. If you truncate between tool rounds, make sure the current turn is never the one that gets cut.
One huge turn. An agent that makes thirty tool calls can produce a single turn larger than your whole budget. Dropping the turn removes the user's request along with it. A better option is to shrink the turn while keeping its structure. Replace the content of older tool results with a short placeholder such as [result omitted: 12,000 characters]. The call and result stay paired, and the model still sees what was attempted.
Parallel calls. If an assistant message requests three calls, all three results travel with it. A turn-based cut handles this for free. Code that removes messages one at a time does not.
Pinned messages. If you pin a message from the middle of the history, pin the whole turn it belongs to. Pinning a single tool result brings back the orphan problem.
Summaries. When you fold old messages into a summary, the boundary between "old" and "recent" must also fall on a turn boundary. The compact function shown earlier moves leading non-user messages from the recent window into the old group for this reason. If you use the block format, replace its role check with starts_turn. A summary of a half-finished tool exchange can record a call as pending when it actually finished.
Exercise
A history ends with a user message, then an assistant message requesting two parallel tool calls, then only one of the two tool results (the second tool is still running). Your window logic cuts by turns. Should the turn be kept, and what should you do before sending the request?
Show answer
Keep the turn, because it is the current turn in progress and cutting it removes the context the model needs. Do not send the request yet, though. Providers require a result for every call, so wait for the second tool to finish, or add a result that honestly reports the failure or timeout (for example "tool timed out"). Running findpairingerrors before sending would catch the missing result.
Exercise
Your application uses the block format, where tool results arrive in user messages. You group turns by checking role == "user". Describe the bug and the fix.
Show answer
Every tool-result message is treated as the start of a new turn, so a tool call and its result land in different groups. The budget loop can then keep a result group and drop the group holding the call. The fix is to use a startsturn check that returns False for a user message whose content consists only of toolresult blocks.