Sub topic 7
Cutting on turn boundaries and keeping tool calls paired
This chapter assumes you can write basic Python and know the chat message roles (system, user, assistant, tool). It also assumes you have read the sliding-window chapter, so you know how to drop old messages to fit a token budget. Here you will learn where those cuts are allowed to fall.
Why a cut can break a conversation
A token budget only counts size. It does not know which messages belong together. If you cut at an arbitrary point, the model can receive a history that makes no sense, or the API can reject the request.
Three kinds of damage are common:
- An orphaned assistant reply. The window starts with an assistant message whose question was dropped. The model sees an answer to something it cannot read.
- A split tool call. An assistant message asks to call a tool, and a later tool message returns the result. Most chat APIs require every tool result to match a tool call in an earlier message. If you keep the result and drop the call, the API usually returns a validation error.
- A dangling tool call. You keep the call but drop its result. Many APIs also reject this, and others let the model act as if the call never finished.
What a turn is
A turn is a group of messages that must stay together. A simple turn is one user message and the assistant reply. A turn that uses tools is longer:
- A user message.
- An assistant message that requests one or more tool calls.
- One tool message for each requested call.
- A final assistant message that uses the results.
Treat the whole group as one unit. You keep it or drop it, never part of it.
Grouping messages into turns
The simplest rule is that a new turn starts at every user message. Everything after it, up to the next user message, belongs to that turn. This keeps tool calls and their results together automatically, because both sit between two user messages.
def group_turns(messages):
turns = []
for message in messages:
if message["role"] == "user" or not turns:
turns.append([])
turns[-1].append(message)
return turnsIf the history begins with a non-user message, the not turns check puts it in a first turn of its own, so nothing is lost.
Truncating by whole turns
Now apply the budget to turns instead of single messages. This version reuses estimate_tokens from the earlier chapter and group_turns from above.
def estimate_tokens(message):
return len(message["content"] or "") // 4 + 4
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()
return system + [m for turn in kept for m in turn]The loop stops at the first turn that does not fit. It does not skip it and keep an older, smaller turn, because that would leave a gap in the middle of the conversation.
A message with tool calls often has empty text, so content may be None. The or "" guards against that. Tool call arguments also cost tokens, so for exact counts include them in your estimate.
Checking your work
Test the cut with a history that contains a tool call. The check below verifies that every tool message in the result has its request in the kept messages. It assumes the OpenAI-style layout, where assistant messages carry a tool_calls list and tool messages carry a tool_call_id.
def tool_pairs_intact(messages):
requested = set()
for m in messages:
for call in m.get("tool_calls", []):
requested.add(call["id"])
answered = {m["tool_call_id"] for m in messages if m["role"] == "tool"}
return requested == answeredRun this after every truncation in your tests. A mismatch means a cut landed inside a turn.
Exercise
A history has these messages in order: user, assistant (tool call), tool (result), assistant (final reply), user, assistant. The budget fits only the last four messages by size. Which messages should a turn-based cut keep, and why?
Show answer
It keeps only the last two messages, the user and the assistant. The last four messages would start with the tool result, whose matching tool call was dropped. Because the first turn (user, tool call, result, final reply) must stay whole, and it does not fit once the last turn is included, the whole first turn is dropped.