The Research Report
Your AI Agent Does Not Need a Bigger Context Window
Most production agent failures are not model failures. They are context failures. The agent had enough intelligence to solve the problem. It had enough tokens in theory. But the wrong tokens were in the wrong place at the wrong time.
The standard response to context problems is to throw more context at them. Bigger windows. Longer prompts. More retrieval. But the real problem is not capacity. It is curation.
A new approach called phase-specific context compilation treats the context window as a budget that gets allocated differently depending on what the agent is doing at each moment. And an open-source library called contextweaver makes it practical.
The Problem: One Blob to Rule Them All
Most agent frameworks build one giant prompt for every LLM call. They concatenate the full conversation history, every tool schema, every tool result, and every piece of retrieved knowledge. Then they hand it all to the model and hope for the best.
This causes three problems.
Cost. A tool-using agent with 100 tools and 50 turns of conversation can easily consume 80,000 tokens per request. At GPT-4o pricing, that is $0.48 per request. Across 10,000 conversations per day, you are burning nearly $5 million a year on tokens the model did not need.
Latency. Processing 80,000 tokens means 3 to 5 seconds of time-to-first-token before the model even starts generating. That is the cost of attention computation across a massive input.
Quality. The model loses focus. Research from Databricks Mosaic shows that quality degradation begins after roughly 32,000 tokens. Chroma tested 18 frontier models in 2025 and found that every single one degraded by 30 percent or more on multi-document retrieval when relevant content sat in the middle of the window. More context makes the model worse, not better, at finding what matters.
The issue is not that context windows are too small. The issue is that different phases of agent execution need different context.
The Four-Phase Model
A tool-using agent moves through four distinct phases for every user request.
Route. The agent decides which tool to call. It needs a compact overview of available tools. It does not need full tool schemas, conversation history, or raw tool outputs from previous calls. It needs a menu, not the cookbook.
Call. The agent constructs the actual tool invocation. It needs the selected tool's schema, the current user request, and enough recent context to fill in the parameters. It does not need 99 other tool schemas or 45 turns of old conversation.
Interpret. The agent processes the tool result. It needs the result plus the call that produced it. It does not need the full conversation history or the entire tool catalog.
Answer. The agent responds to the user. It needs relevant conversation turns, the dependency chain connecting the user's question to the tool result, and any summarized outputs. It does not need raw payloads or unrelated tool schemas.
Shoving all context into every phase is like photocopying the entire encyclopedia when you need one paragraph. You waste paper, waste time, and make it harder to find the paragraph you actually wanted.
How Phase-Specific Compilation Works
contextweaver is an open-source Python library built by Diogo Santos that implements phase-specific, budget-aware context compilation. The core idea: given a specific phase, a specific query, and a fixed token budget, build the smallest context pack that preserves the information the model actually needs.
The library runs an eight-stage pipeline.
- Generate candidates. Pull phase-relevant events from the event log for the current request.
- Dependency closure. If a tool result is selected, its parent tool call is automatically included. This prevents the common failure where the model sees an output but not the action that produced it.
- Sensitivity filter. Drop or redact items at or above the configured sensitivity floor.
- Context firewall. Store large tool outputs out of band. Replace them with compact summaries. A single oversized API response no longer eats half the budget.
- Score candidates. Rank by recency, tag match, kind priority, and token cost.
- Deduplicate candidates. Remove near-duplicates using Jaccard similarity.
- Select and pack. Greedily pack the highest-scoring items into the phase token budget.
- Render context. Assemble the final prompt string with diagnostics showing what was kept, dropped, and why.
The result is deterministic. Same inputs always produce the same output. No randomness. No model-in-the-loop for the compilation itself.
The Numbers
The contextweaver repository includes a before/after example that illustrates the effect clearly.
Without contextweaver, a simple agent request uses 417 raw prompt tokens with no budget enforcement and large outputs included verbatim.
With contextweaver, the same request uses 126 tokens under a 1,500-token budget. That is a 70 percent token reduction. The budget is enforced by the builder, not treated as a soft suggestion.
In a more aggressive scenario described in the project's README, a tool-using agent with 100 tools and 50 turns of conversation would consume approximately 80,000 tokens without compilation. With phase-specific compilation, the route phase needs roughly 500 tokens (five tool cards, no full schemas), and the answer phase needs roughly 2,000 tokens (three relevant turns plus dependency closure). That is a drop from 80,000 to 2,500 for the answer phase.
Cost drops by roughly 70 percent. Latency drops to sub-second. Quality improves because the model sees only relevant context.
Dependency Closure: The Detail That Matters
One feature deserves special attention: dependency closure.
When you truncate conversation history manually, it is easy to keep a tool result while dropping the tool call that produced it. The model sees a number or a JSON blob with no explanation of where it came from. This causes hallucinations, repeated questions, and broken reasoning.
Dependency closure fixes this. Every context item has an optional parent_id. When the compilation pipeline selects a tool result, it automatically pulls in the parent tool call. When it selects a user turn that triggered a tool call, it includes the call. The dependency chain stays intact even as the overall context shrinks.
This is the kind of detail that separates a working agent from one that looks good in demos but breaks in production.
The Context Firewall
Large tool outputs are the enemy of budget control. A single database query can return 50,000 tokens. A web search result can be massive. An API response can be enormous.
The context firewall intercepts these outputs before they reach the prompt. It stores the raw data out of band and injects a compact summary. If the model needs the full output, it can request it explicitly. But by default, the firewall prevents one oversized payload from consuming the entire budget.
This is a structural fix, not a workaround. You do not need to manually truncate outputs or write custom summarization code. The firewall handles it as part of the compilation pipeline.
Integration With Emerging Protocols
contextweaver supports two emerging agentic protocols out of the box.
MCP (Model Context Protocol). Convert tool definitions and results into native contextweaver types. Compatible with any MCP server including Claude Desktop and VS Code extensions. The ingestmcpresult() method handles one-call result ingestion with automatic artifact persistence.
A2A (Agent-to-Agent). Multi-agent session management with unified context. Agent cards convert to SelectableItem for routing. Cross-agent session loading works via loada2asession_jsonl(). A2A results are stored in ResultEnvelope with facts and artifact handles.
This means contextweaver is not just a standalone library. It is positioned as a context management layer that works with any framework and any protocol.
How This Differs From Other Approaches
Bigger context windows give you more room but do not decide what is relevant. Manual truncation is simple but breaks dependency chains. Conversation-only memory handles turns but ignores tool schemas, tool calls, and tool results. RAG retrieves external knowledge but does not solve the internal context assembly problem for agent phases.
contextweaver treats context as a compilation problem, not a storage problem. The question is not "how much can I fit?" but "what is the minimum this step actually needs?"
This distinction matters. Anthropic's context engineering guide frames it as an "attention budget" where every new token depletes the model's ability to focus. Production teams at scale treat the context window the way a finance team treats cash: a finite pool allocated deliberately across competing claims.
Wire's benchmarks show that a customer service agent processing 10,000 conversations per day costs roughly $255,000 per year with unmanaged context. The same agent with 60 percent context reduction costs $102,000 per year. Same model. Same task. Same volume. The difference is whether you treat the context window as storage or as a budget.
Getting Started
Install contextweaver from PyPI:
pip install contextweaver
Basic usage:
from contextweaver.context.manager import ContextManager
from contextweaver.types import ContextItem, ItemKind, Phase
mgr = ContextManager()
mgr.ingest(ContextItem(id="u1", kind=ItemKind.user_turn, text="How many users?"))
mgr.ingest(ContextItem(id="tc1", kind=ItemKind.tool_call,
text="db_query('SELECT COUNT(*) FROM users')", parent_id="u1"))
mgr.ingest(ContextItem(id="tr1", kind=ItemKind.tool_result,
text="count: 1042", parent_id="tc1"))
pack = mgr.build_sync(phase=Phase.answer, query="user count")
print(pack.prompt) # budget-aware compiled context
print(pack.stats) # what was kept, dropped, deduplicated
For tool routing, the library includes a separate routing engine with a beam-search router that produces compact ChoiceCards instead of full schemas:
from contextweaver.routing.catalog import Catalog
from contextweaver.routing.tree import TreeBuilder
from contextweaver.routing.router import Router
catalog = Catalog()
for item in load_catalog_json("catalog.json"):
catalog.register(item)
graph = TreeBuilder(max_children=10).build(catalog.all())
router = Router(graph, items=catalog.all(), beam_width=3, top_k=5)
result = router.route("send a reminder email about unpaid invoices")
print(result.candidate_ids)
The repository includes a full agent loop example at examples/fullagentloop.py that demonstrates the route, call, interpret, and answer flow end to end.
When Phase-Specific Compilation Backfires
No technique is universal. Phase-specific context compilation adds orchestration overhead that is not always justified.
Flat workflows. A single-phase or two-step pipeline (prompt then response) gains nothing from phase decomposition. The assembly logic adds latency without benefit.
Emergent replanning. When agents need to revise their plan mid-execution frequently, strict phase isolation forces expensive context re-assemblies. A single unified context that the agent can reread on demand can be cheaper.
Cross-phase dependencies. If the reviewer needs implementation history to catch subtle regressions, stripping it per phase rules causes missed findings. Identify whether cross-phase context matters before excluding it.
Small token budgets. If the entire project fits comfortably within context, the cost of filtering exceeds the cost of inclusion. Apply phase-specific compilation when context exceeds what the model can usefully attend to.
The Bigger Picture
Phase-specific context compilation is part of a broader shift from prompt engineering to context engineering. The old question was "what words should I put in the prompt?" The new question is "what information does this step need, and what information is actively harmful?"
The tools are catching up to the insight. contextweaver handles compilation. Anthropic's progressive disclosure pattern handles loading. LangChain's Deep Agents handle autonomous compaction. Together, they form a stack where the context window is no longer a passive container but an actively managed resource.
The agents that work reliably in production are not the ones with the biggest context windows. They are the ones that curate what goes in. Phase-specific compilation is the most direct way to do that.
Suggested Title: Your AI Agent Does Not Need a Bigger Context Window
Word Count: 1,693
Citations:
- contextweaver GitHub repository: https://github.com/dgenio/contextweaver
- contextweaver PyPI: https://pypi.org/project/contextweaver/
- Diogo Santos, "Your AI agent does not need a bigger context window," dev.to, April 14, 2026: https://dev.to/dgenio/your-ai-agent-does-not-need-a-bigger-context-window-44ob
- AgentPatterns.ai, "Phase-Specific Context Assembly for AI Agent Development": https://agentpatterns.ai/context-engineering/phase-specific-context-assembly/
- Tian Pan, "Token Budget as Architecture Constraint: Designing Agents That Work Under Hard Ceilings," April 13, 2026: https://tianpan.co/blog/2026-04-13-token-budget-as-architecture-constraint
- Wire Blog, "Context budgets: how to allocate tokens for AI agents," Jitpal Kocher, April 13, 2026: https://usewire.io/blog/context-budgets-how-to-allocate-tokens-for-ai-agents/
- ContextBudget paper (arXiv:2604.01664): https://www.alphaxiv.org/overview/2604.01664v1
- Anthropic, "Effective Context Engineering for AI Agents": https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents
- Chroma context rot research, 2025: https://research.trychroma.com/context-rot
Fact-Check Notes:
- The 70% token reduction figure comes from contextweaver's before_after.py example in the repository. This is a small, controlled example, not a production benchmark. The README also cites a larger scenario (100 tools, 50 turns) going from 80K to 2.5K tokens, but this is illustrative, not benchmarked.
- The Databricks Mosaic finding about degradation after 32K tokens is widely cited but I was unable to locate the original paper. Verify before citing the specific number.
- The Chroma 18-model benchmark finding (30% degradation) is from 2025 and may be updated. The specific URL is https://research.trychroma.com/context-rot.
- The Wire cost comparison ($255K vs $102K) comes from their blog post citing Maxim AI. This is a specific benchmark scenario, not a universal claim.
- The TALE framework achieving 68% token reduction while maintaining accuracy within 5% is from the Tian Pan article citing academic research. I was unable to verify the original paper directly.
- contextweaver is at v0.1.7 on PyPI and labeled as Alpha status. It has 500+ tests, zero runtime dependencies, and mypy strict checking, but it is early-stage software.