Context Management for LLM Agents: From Chaos to Controllable Design
As LLM agents tackle longer task chains, their context windows quickly fill up, leading to overflow, lost constraints, noise accumulation, and rising costs. This article analyzes the root causes of uncontrolled context from an engineering perspective and outlines actionable strategies to manage it effectively. It covers establishing a context budget model, implementing hierarchical summarization to compress history without losing key details, and leveraging external memory and retrieval to keep irrelevant content out of the context window.
Background: The Context Window as the Agent’s Working Memory
Every time a Large Language Model (LLM) performs inference, it can only read a fixed length of input known as the context window, measured in tokens. In standard Q&A, the window typically contains system instructions, historical messages, and retrieved materials. The task chain for an agent is much longer; after each tool call, the tool’s return result is appended to the window, causing it to fill up rapidly.
Recently, the industry has seen frequent discussions regarding the release cadence of new foundational models, and some platforms have adjusted their third-party client access rules. These changes indicate two things: model capabilities are continuously improving, while the integration environment remains unstable. Even with expanded window capacities, long tasks still experience loss of control. This happens because without active context management, information piles up disorderly. This article outlines the root causes of the problem from an engineering perspective and provides actionable solutions.
I. Problem Definition: Why Context Gets Out of Control
Context loss of control typically manifests in four ways:
- Window Overflow: The input exceeds the model’s upper limit, causing an API error or forcing the platform to truncate the earliest content.
- Key Information Loss: Constraints provided by the user in the first round are truncated, leading the model to violate these constraints in subsequent outputs.
- Noise Accumulation: Large blocks of logs and repeated web content occupy the window, diluting truly useful information and distracting the model’s attention.
- Increased Cost and Latency: If the entire history is resubmitted every round, the cumulative input volume grows rapidly with the number of turns.
The scale of the fourth problem can be illustrated with a simple calculation. Assuming 1,000 new tokens are added per round, the input submitted in the nth round is approximately n×1,000 tokens. The cumulative input for ten rounds is about 55,000 tokens, and for twenty rounds, it reaches about 210,000 tokens. The cumulative input volume is roughly proportional to the square of the number of rounds, meaning the cost of long tasks grows much faster than the complexity of the task itself.
II. Establishing a Context Budget Model
To handle context issues, you must first treat the window as a budget and allocate quotas for each type of content. The table below shows a set of empirical engineering values; actual ratios should be adjusted according to the task type.
| Zone | Typical Content | Recommended Ratio |
|---|---|---|
| System Instructions | Role definition, output format, safety rules | 5%–10% |
| Task State | Current goal, completed steps, hard constraints | 10%–15% |
| Retrieved Materials | Document snippets relevant to the current query | 30%–40% |
| Recent Conversation | Raw text of the last few rounds | 25%–35% |
| Reserved Space | Model output length and safety margin | 15%–20% |
Budget allocation must be executed alongside priority rules. The example below loads content by priority; items that do not fit are skipped, while instructional content is always retained.
from dataclasses import dataclass@dataclassclass ContextItem:text: strtokens: intpriority: int # The smaller the value, the higher the prioritykind: str # "instruction" | "state" | "retrieved" | "history"def pack_context(items: list[ContextItem], budget: int) -> tuple[list[ContextItem], int]:mandatory = [i for i in items if i.kind == "instruction"]optional = sorted((i for i in items if i.kind != "instruction"),key=lambda x: x.priority,)used = sum(i.tokens for i in mandatory)if used > budget:raise ValueError("System instructions have exceeded the budget; need to streamline instructions")selected = list(mandatory)for item in optional:if used + item.tokens <= budget:selected.append(item)used += item.tokensreturn selected, used
There are two key points to this function. First, instructional content does not participate in eviction; if it exceeds the budget, an error is raised directly to prevent the model from running without rules. Second, other content is greedily packed by priority. This strategy is simple to implement, making it suitable for a first version, and can be replaced with more refined sorting methods later.
III. Hierarchical Summarization: Compressing History Instead of Deleting It
Directly truncating history is the crudest approach. Earlier conversations might contain user preferences, decisions already made, and unresolved issues. Deleting them will cause the model to repeat questions or overturn existing conclusions. A more robust approach is to compress older content into a summary while retaining the raw text of recent conversations.
The structure of the summary is more important than its length. It is recommended to use fixed fields rather than free-form prose. The four common fields are:
- Goal: What the user ultimately wants to achieve.
- Constraints: Conditions that cannot be violated (e.g., format, scope, deadline).
- Decisions: Determined choices and their rationale.
- Open Issues: Items that still need confirmation or remain unresolved.
Structured summaries are easy to validate later and easy to retrieve by field. The code below demonstrates the basic logic of rolling compression.
def compress_history(history: list[dict], summarize, keep_recent: int = 6) -> list[dict]:if len(history) <= keep_recent:return historyolder = history[:-keep_recent]recent = history[-keep_recent:]# summarize can be a model-calling function or a rule-based extraction functionsummary = summarize(older)summary_message = {"role": "system", "content": f"[History Summary]\n{summary}"}return [summary_message] + recent
The trigger timing must also be designed. A common practice is to initiate compression when used tokens exceed 70% of the budget, rather than waiting until the window approaches its limit. This leaves a margin to prevent the compression process itself from failing due to insufficient space.
Summaries lose detail, so they cannot serve as the sole source of information. Hard constraints explicitly provided by the user should be stored simultaneously in the task state (see Section V) and reinjected every round, without relying on the completeness of the summary.
IV. External Memory and Retrieval: Keeping Materials Outside the Window
Many long tasks involve large amounts of documents, historical records, or knowledge base content. Placing all of them into the window is impractical and introduces noise. The external memory approach stores the raw text in external storage, retrieving only a few relevant snippets based on the current query to inject into the window.
A typical retrieval pipeline includes the following steps:
- Chunking: Split long documents into shorter snippets based on semantic boundaries, commonly a few hundred tokens, while retaining metadata like titles and sources.
- Vectorization: Use an embedding model to convert each snippet into a vector and write it to a vector index.
- Query: Convert the user’s question into a vector to recall candidate snippets from the index.
- Filtering and Sorting: Remove snippets with similarity scores below a threshold, and rerank them by relevance and recency.
- Injection: Place the final selected snippets into the retrieved materials area and annotate their sources.
In engineering implementation, raw text is usually stored in object storage, vectors in a vector search service, and document titles, timestamps, and permissions in a relational database. Cloud platforms like Baidu AI Cloud offer object storage, vector search, and relational database services that can fulfill these responsibilities. The specific selection depends on data scale, latency requirements, and the team’s operational capabilities.
The core of the retrieval code is threshold control, as shown in the example below.
def retrieve(query: str, store, top_k: int = 5, min_score: float = 0.6) -> list[dict]:query_vector = embed(query)hits = store.search(query_vector, top_k=top_k)# Snippets below the threshold are better left unused than injecting irrelevant content into the windowreturn [{"text": h.text, "source": h.source, "score": h.score}for h in hits if h.score >= min_score]
