Practical technical guides

Trim Agent History Without Breaking Tool Calls and Results

Compare message slicing, whole-turn selection and conservative repair using synthetic cost budgets and pair validation.

By Sandeep Belgavi · Published 2026-12-04

Flow from Select history, to Validate call/result pairs, to Send complete structure.
Original conceptual diagram by Sandeep Belgavi.

A shorter history can be an invalid history

An agent conversation contains a user request, an assistant tool call, a tool result and a final explanation. To fit the next request within a context budget, a history processor retains the newest messages. It keeps the result but discards the call that explains why the result exists. The text is shorter, yet the protocol structure is broken. Token reduction and message validity are separate requirements.

This failure differs from summarizing poorly or retrieving an irrelevant document. The retained tool result may be perfectly accurate. The problem is that its identifier no longer refers to a retained call in the required scope. A model adapter may reject the request, or a permissive implementation may interpret a result without its original arguments. Neither outcome is fixed by making the result text more concise.

The remedy is to treat history as structured records with dependencies. Select complete conversation units, reserve space for the current request and validate the final sequence. The companion lab compares a naive newest-message policy, complete-turn selection and a conservative repair that drops incomplete turns. It never fabricates a tool result or silently re-executes a discarded tool call.

Define the unit that must remain intact

For this teaching model, a turn consists of a user message, an assistant message containing one or more calls, their results, and an assistant completion. Each call has an identifier scoped to its turn. Every retained call must have exactly one later result in that turn, and every retained result must refer to a retained call. Other provider contracts may impose additional ordering or content-block requirements.

Parallel calls make the unit larger. An assistant message can request two independent inspections. Retaining only one result changes the structure even if that result consumes most of the tokens. Do not split a multi-call assistant message into invented messages to fit a budget. A processor needs either the whole unit or an explicitly supported representation for incomplete work.

Pydantic AI's current documentation describes automatic repair before a provider request: orphan results are removed and interrupted calls receive marked synthetic returns. That can keep the request valid while changing what the model sees. Preserving complete pairs therefore remains useful even in a repairing framework. The original simulator uses simple JSON fixtures and declared token costs to make selection inspectable. It does not reproduce that framework repair or measure compressed-answer quality.

Work through a small budget

The synthetic fixture contains three completed turns. The first costs forty units, the second fifty and the third sixty. Add a ten-unit system instruction and reserve twenty units for the next user request. With a total budget of one hundred, only seventy units remain for completed history. Complete-turn selection keeps the third turn and consumes ninety units overall.

A naive newest-message policy can include the tail of the second turn as well. Depending on the individual message costs, that tail may begin with a result whose call was removed. The displayed total fits the budget, so a budget-only test passes. The structural validator must still reject it. The lab exposes both the arithmetic and the missing identifier rather than reducing the outcome to a single green status.

Conservative repair removes every retained message belonging to a structurally incomplete turn. This can leave unused capacity. That is a deliberate tradeoff: a structurally valid, smaller history is preferable to one padded with orphaned protocol records. A more sophisticated processor could summarize completed turns into ordinary text, but it must label that text as a summary and preserve any evidence needed for subsequent actions.

Reserve the current request first

Budget calculation should include fixed instructions, tool definitions, the current user input and a reserve for generated output. A history processor that spends the entire context limit on old messages leaves no room for the next step. The lab simplifies this to system cost, current-request reserve and completed history; real accounting must use the provider's supported token estimator and payload rules.

If fixed material already exceeds the budget, return an explicit configuration failure. Dropping the system instruction to make the total fit changes the contract. Silently trimming the current request can remove the user's constraint. Neither should be an automatic fallback. Present a typed error to the orchestrator, which can select a smaller tool set, ask for narrower input or choose another supported model configuration.

A declared cost fixture is useful precisely because it is controllable. Set the budget one unit below a complete turn and observe the step change in retained history. Token estimates in real systems have uncertainty, so leave headroom and record both estimated and reported usage where available. Do not describe a hand-assigned cost as a measured provider token count.

Keep validation independent from selection

The selection function chooses candidate records. A separate validator checks identifier pairing, duplicate identifiers, ordering and required fixed messages. If the same function chooses and validates using the same assumptions, a shared bug can pass unnoticed. Tests should construct invalid histories directly rather than only validating histories produced by the selector.

# Author: Sandeep Belgavi. One-call teaching invariant.
def pair_errors(messages):
    pending = set()
    errors = []
    for message in messages:
        key = (message["turn"], message.get("call_id"))
        if message["kind"] == "call":
            if key in pending:
                errors.append("duplicate call")
            pending.add(key)
        elif message["kind"] == "result":
            if key not in pending:
                errors.append("orphan result")
            else:
                pending.remove(key)
    return errors + ["missing result"] * len(pending)

assert pair_errors([{"turn": 2, "kind": "result", "call_id": "x"}])

This illustration handles a narrow record shape. A production validator must also reject reuse after a result, validate provider-specific message ordering and understand multiple content blocks. The companion model's fixture validator tracks all call identifiers as well as pending ones. That prevents a completed identifier from being reused accidentally in the same turn while permitting a separately scoped turn to use its own identifier.

Failure modes beyond the orphan result

An unfinished call may represent work still running. Trimming it away does not cancel the operation. Keep operation state in durable storage outside the model context, and reconstruct a supported continuation when the result arrives. Otherwise a late result can attach to a conversation that no longer knows which arguments produced it. History is a view of execution, not the authoritative execution record.

Another failure occurs when a summary embeds tool-looking text. A summary should remain ordinary narrative data, not a synthetic tool response with a reused identifier. If the agent needs exact evidence, keep a reference to the immutable result and retrieve it through a controlled path. Fluent paraphrase is insufficient for reconstructing a checksum, exact configuration value or authorization decision.

Preserving pairs also does not preserve meaning automatically. Removing the user's qualifying instruction while retaining the call and result can create a structurally valid but misleading context. Complete-turn selection helps, but cross-turn dependencies still require policy. Important constraints should be stored in explicit application state with provenance and precedence, rather than relying on their accidental survival in a rolling transcript.

Migration and expected tests

Instrument the existing processor to report removed message kinds and retained turn identifiers. Run it against synthetic transcripts containing single calls, parallel calls, duplicate IDs, delayed results and large outputs. Add validation after every history transformation, including summarization and retry reconstruction. A valid input can become invalid after a later middleware drops a seemingly unimportant record.

For the companion fixture, a budget of one hundred with thirty units reserved leaves enough room for the newest sixty-unit turn. At a budget of eighty, complete-turn selection retains no completed turn because the newest one no longer fits and this policy preserves a contiguous suffix. That is a documented selection choice, not the only possible algorithm. Export records the policy so the result can be interpreted correctly.

Test reset, numeric boundaries, every policy and exports alongside model invariants. Keep malformed input visible as an error instead of producing a plausible empty transcript. Use an agent only for tasks requiring interpretation; token accounting, dependency validation and selection of a deterministic suffix are ordinary software. Their behavior should remain stable when the conversational model is replaced.

Interactive experiment

History trimming: complete turns, orphan results and budget tradeoffs. Adjustable synthetic fixtures, decision traces, reset and JSON export.

Primary references and authorship

Sources read December 4, 2026. Original explanations and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/history_trim_pairs. Views are my own and do not represent any employer, past or present.