Your AI Agent Doesn't Need More Context. It Needs Better Context Management.
An AI agent works perfectly for the first few interactions. It searches documents, calls APIs, analyzes results, and responds with useful information. Then, after 20 or 30 tool calls, something changes. Responses become slower. Token usage increases. The agent starts repeating work or overlooking i

An AI agent works perfectly for the first few interactions.
It searches documents, calls APIs, analyzes results, and responds with useful information.
Then, after 20 or 30 tool calls, something changes.
Responses become slower. Token usage increases. The agent starts repeating work or overlooking important details from earlier in the conversation.
The usual reaction is to increase the context window or switch to a more powerful model.
But a larger context window doesn't necessarily solve the problem.
Sometimes the issue isn't how much information the model can process. It's how much irrelevant information we're forcing it to process.
I've worked on AI agents involving tool calling, prompt caching, and context management. One important engineering lesson is that giving an agent access to more information isn't the same as giving it better information.
Let's look at how to control context growth, reduce unnecessary token usage, and keep AI agents reliable during longer workflows.
A traditional LLM application might send a user question and some supporting documents to a model.
It repeatedly interacts with tools, receives results, makes decisions, and continues working.
Imagine an agent helping a developer investigate a slow API.
User: Why is our orders API slow? | v Search Logs | v Analyze Results | v Query Database | v Inspect Indexes | v Generate Report Enter fullscreen mode Exit fullscreen mode Each step can add information to the conversation:
If the application keeps passing the entire history into every subsequent model call, the context grows throughout the workflow.
Suppose each tool produces a hypothetical 3,000-token response.
After 15 tool calls, that's 45,000 tokens of raw tool output alone.
The agent may only need five database metrics, but it keeps receiving the original query results, logs, and intermediate explanations.
This creates two problems: increasing inference costs and a growing amount of irrelevant information competing for the model's attention.
Modern LLMs can support large context windows, but that capacity shouldn't be treated as free memory.
Every request has a cost in processing, latency, and sometimes accuracy.
System instructions Full conversation history All previous tool responses Complete application logs Database query results Retrieved documents Current question Enter fullscreen mode Exit fullscreen mode Approach B: Send what's relevant
System instructions Current objective Important confirmed findings Relevant recent messages Selected tool results Current question Enter fullscreen mode Exit fullscreen mode The second prompt is smaller and more focused.
However, blindly removing information is risky. An important detail might be buried in an earlier tool response.
The goal isn't simply to minimize tokens.
It's to preserve information that influences the next decision while removing redundant or irrelevant material.
This is often called context engineering.
The LangChain team describes several useful approaches: writing information outside the model context, selecting relevant information, compressing it, and isolating work.
Reference: Context Engineering for Agents.
One of the easiest improvements is filtering tool results before returning them to the model.
Imagine a database tool that retrieves 1,000 customer records.
The agent only needs to determine how many accounts are inactive.
A poor tool implementation returns the entire dataset:
def get_inactive_customers ( db ): return db. fetch_all ( "SELECT * FROM customers WHERE active = false" ) Enter fullscreen mode Exit fullscreen mode This creates unnecessary context and may expose personal data the model doesn't need.
A better tool returns the specific information required for the task:
def count_inactive_customers ( db ): row = db. fetch_one ( """ SELECT COUNT(*) AS total FROM customers WHERE active = false """ ) return { "inactive_customers": row [ "total" ] } Enter fullscreen mode Exit fullscreen mode This is simpler, cheaper, and easier for the model to interpret.
The underlying principle is familiar from backend development: avoid fetching more data than the consumer needs.
Of course, if the agent must inspect individual accounts, a count alone won't be enough.
In that case, use pagination, bounded results, and explicit fields.
Also enforce authorization and tenant filtering in the tool implementation itself. Context optimization should never weaken data access controls.
A common design mistake is treating the conversation history as the application's entire state.
But not every piece of application state needs to be visible to the LLM.
Consider this hypothetical investigation state:
from typing import TypedDict class InvestigationState ( TypedDict ): objective: str completed_steps: list [ str ] confirmed_findings: list [ str ] raw_logs_path: str | None next_action: str | None Enter fullscreen mode Exit fullscreen mode The application can persist this state separately.
Raw logs remain in controlled storage, while the model receives only the relevant findings and references needed for the current step.
def build_context ( state: InvestigationState ): return { "objective": state [ "objective" ], "confirmed_findings": state [ "confirmed_findings" ], "next_action": state [ "next_action" ], } Enter fullscreen mode Exit fullscreen mode This is a simplified illustration of context selection, not a complete LangGraph implementation.
The important distinction is between what the application remembers and what the model needs to see right now.
LangGraph supports stateful workflows and checkpointing, which can help separate persistent execution state from the messages included in model calls.
See the LangGraph persistence documentation.
For longer conversations, keeping every previous message becomes expensive.
Summarization is one way to reduce that overhead.
Imagine an agent that has already investigated several database queries.
Instead of sending the entire interaction history, we can preserve a compact summary:
Objective: Investigate slow orders API. Confirmed findings: - Endpoint performs three database queries. - One query lacks a useful composite index. - Database CPU is within normal range. Unresolved: - Verify the execution plan after index changes. Next action: Review EXPLAIN ANALYZE output. Enter fullscreen mode Exit fullscreen mode This retains the information needed to continue working.
But summarization introduces another failure mode: losing important details.
A summary might omit an error code, change a numerical value, or turn a hypothesis into a confirmed fact.
For technical workflows, I'd preserve certain information separately rather than relying entirely on generated summaries.
That includes exact error messages, identifiers, important measurements, user requirements, and unresolved decisions.
Summarize explanations, but preserve facts that must remain exact.
And don't summarize in the middle of an operation that depends on precise intermediate state.
Sometimes an agent needs to perform several independent investigations.
For example, a software engineering assistant might need to:
Passing every tool response from all three investigations into one conversation can create unnecessary complexity.
An alternative is delegating those investigations to separate agents with isolated context.
Main Agent | +----------+----------+ | | | v v v Logs Agent SQL Agent Deploy Agent | | | +----------+----------+ | v Compact Findings | v Main Agent Enter fullscreen mode Exit fullscreen mode Each subagent works with the context relevant to its task and returns a structured summary.
The main agent doesn't need every log line or intermediate database query.
This approach can make large workflows easier to manage.
However, subagents aren't automatically cheaper.
They can introduce additional model calls, coordination overhead, and latency. A poorly defined task may also lose important information when handed between agents.
I'd use them when isolation offers a clear benefit, not simply because multi-agent architectures sound more advanced.
The LangChain team's context management guidance discusses using external storage, compression, and isolated work to manage long-running agents.
Prompt caching is another useful optimization.
When a model provider supports caching repeated input prefixes, applications may reduce the cost of processing unchanged instructions and other stable context.
A practical prompt layout might look like this:
Stable system instructions Stable tool definitions Stable application rules -------------------------- Current task Relevant retrieved documents Recent conversation context Enter fullscreen mode Exit fullscreen mode Keeping reusable content stable can improve cache opportunities.
But caching doesn't solve every problem.
A cached prompt can still contain irrelevant information. Caching also doesn't guarantee improved answer quality, and the exact savings depend on the provider, model, request structure, and cache behavior.
I would measure actual cached input tokens and cost rather than assuming every repeated request benefits equally.
The broader principle is that caching improves the economics of repeated context, while context management determines whether that context is necessary in the first place.
Reducing context size is useful only if the agent still completes its task correctly.
Suppose a new summarization strategy reduces input tokens but causes the agent to miss important requirements.
I'd evaluate changes using several measurements:
Compare these metrics against the same representative tasks.
Include short workflows, long investigations, noisy tool outputs, and tasks requiring information from earlier steps.
Also test failure cases where a summary omits a critical constraint.
The objective is not the smallest possible prompt. It's the smallest reliable context for the work being performed.
For an existing AI agent, I wouldn't immediately introduce subagents or complex memory infrastructure.
First, inspect how much context each tool call adds.
Then make tool outputs more specific. Return relevant fields, counts, and summaries rather than entire responses.
Next, separate persistent application state from the model's working context.
For long-running tasks, introduce summarization or selective retrieval once conversation history becomes a measurable problem.
Finally, consider isolated subagents when tasks naturally split into independent work.
After each change, rerun evaluation tasks to verify that token savings haven't reduced reliability.
This incremental approach makes it easier to identify which optimization actually helps.
A large context window is useful, but it shouldn't become an excuse to send everything to the model.
Building reliable AI agents requires deciding what information should be stored, what should be retrieved, and what the model needs for its next decision.
The best AI agents don't necessarily have access to the most context.
They have access to the right context at the right time.