A Python agent that triages GitHub issues hit 658,594 tokens at turn 40. By turn 20, tool results accounted for 99.1 percent of the context window. The agent did not crash. It kept calling the GitHub API, but it lost track of earlier decisions and started repeating suggestions.
This is not a theoretical problem. Edward Izgorodin replayed 40 turns of a real triage bot, alternating between two repositories (pydantic/pydantic-ai and openai/openai-agents-python), and measured token counts at every step. The replay used tiktoken's o200k_base encoding and real GitHub REST API responses. Each turn included a user question, a tool call, a JSON result, and a 90-token answer. The instructions were 94 tokens.
The failure mode is predictable: when tool output dominates the context, the agent forgets its own reasoning. It cannot see the user's earlier preferences or the labels it already suggested. It repeats API calls and generates redundant answers.
Tool results are the primary culprit. At turn 20, the GitHub API responses consumed 99.1 percent of the token budget. Each response contained full issue objects with fields the agent never used: timestamps, author metadata, reaction counts, nested comment threads.
The second contributor is the conversation history itself. Every turn adds four messages: user input, assistant tool call, tool result, assistant answer. Without pruning, the history grows linearly. With full tool results, it grows faster than the agent can reason.
Instructions are the third risk. If they live in the history (as a system message at the top), a naive sliding window or summarization pass can truncate them. The agent then forgets its core task.
Cut each tool result to the fields the agent actually reads before it enters the history. In the replay, reducing each GitHub issue to five fields (number, title, labels, state, body excerpt) dropped the turn-40 token count from 658,594 to 36,934.
This is the highest-leverage intervention. It does not change the agent's reasoning. It just removes noise.
def shape_github_issue(raw_issue: dict) -> dict:
"""Keep only fields the agent uses for triage."""
return {
"number": raw_issue["number"],
"title": raw_issue["title"],
"labels": [label["name"] for label in raw_issue.get("labels", [])],
"state": raw_issue["state"],
"body_preview": raw_issue.get("body", "")[:200]
}
Drop the oldest turns when the context exceeds a threshold. Always drop whole turns so no tool call loses its result. A six-turn window still sent 99,000 tokens per call after turn six in the replay, but it kept the agent's recent reasoning intact.
The failure mode: the agent forgets decisions made before the window. If it suggested labels at turn 3 and the window starts at turn 7, it may re-suggest the same labels.
Replace old tool results with a one-line summary. For example, replace a 21,583-token GitHub API response with "Fetched 5 issues from openai/openai-agents-python". Keep the tool call and the assistant's answer. This preserves the reasoning chain without the raw data.
This works when the agent's answer already distills the important facts. It fails when the agent needs to cross-reference old data.
Generate a summary of dropped turns and prepend it to the history. In the replay, this saved almost nothing after tool result shaping. The summary itself consumed tokens, and the agent rarely referenced it.
Summarization is useful when the user's decisions matter more than the tool output. For example, if the user said "never suggest the 'bug' label for feature requests," that preference should survive pruning.
Move instructions out of the history. Send them with every request as a system message or a fixed prefix. This prevents sliding windows and summarization from truncating the agent's core task.
| Strategy | Token Savings | Latency Impact | Reasoning Accuracy | Implementation Complexity |
|---|---|---|---|---|
| Tool result shaping | 95%+ | None | High (no information loss for agent) | Low (filter at tool boundary) |
| Sliding window (6 turns) | 85% (after turn 6) | None | Medium (forgets old decisions) | Low (slice message list) |
| Tool result stubbing | 70-90% | None | Medium (loses raw data) | Medium (requires per-tool logic) |
| Summarization | 10-30% | +200-500ms per summary | Low (agent ignores summaries) | High (LLM call + prompt tuning) |
| Instruction placement | N/A | None | High (prevents instruction loss) | Low (refactor message structure) |
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β User Input β
ββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Orchestrator β
β - Prepend instructions (not in history) β
β - Check token count (tiktoken) β
β - Prune if > threshold β
ββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β LLM Call (OpenAI, Anthropic, etc.) β
ββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Tool Call (list_open_issues) β
ββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β GitHub API β
ββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Tool Result Shaper β
β - Extract 5 fields per issue β
β - Truncate body to 200 chars β
ββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β History Manager β
β - Append shaped result β
β - Stub old tool results if > 10 turns β
β - Slide window if > 50k tokens β
ββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Response to User β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Track these metrics to detect context bloat before it breaks reasoning:
The user says "only suggest labels for bugs, not features." The agent suggests labels for both. The sliding window dropped the turn where the user set the preference.
Mitigation: Extract user preferences into a separate state object. Pass it with every request.
The agent says "I will fetch issues, then filter by label." It fetches issues. The window slides. It forgets the filter step.
Mitigation: Use a task queue or state machine to track multi-step plans outside the conversation history.
The agent calls list_open_issues at turn 5 and turn 15 with identical parameters. It forgot the first result.
Mitigation: Cache tool results by call signature. Return the cached result if the agent repeats a call within N turns.
The agent starts suggesting labels it should never use. The sliding window truncated the system message.
Mitigation: Move instructions out of the history. Send them as a fixed prefix or system message with every request.
Tool result shaping: Always. It is the highest-leverage, lowest-risk intervention.
Sliding window: When the agent does not need to reference old turns and the user does not set long-lived preferences.
Tool result stubbing: When the agent's answers already distill the important facts and you need to preserve the reasoning chain.
Summarization: When user decisions matter more than tool output and you can afford the latency of an extra LLM call.
Instruction placement: Always. Never let pruning logic touch the agent's core task definition.
Start with tool result shaping. Measure token counts per turn and per message type. If shaping alone does not keep you under budget, add a sliding window with turn boundaries. Stub old tool results only if you need to preserve the reasoning chain beyond the window. Use summarization last, and only for user preferences.
Move instructions out of the history. Track repeated tool calls and alert on them. Cache tool results by call signature.
Avoid summarization as a first resort. In the replay, it saved almost nothing after shaping and added latency. Avoid naive message truncation (cutting mid-turn or mid-result). The agent will lose coherence.
This is not a model-specific problem. Every LLM has a context limit. Every agent that calls tools will hit it. The replay used real GitHub data and real token counts. The strategies above are not theoretical. They are the minimum plumbing to keep a long-running agent on track.