跪拜 Guibai
← Back to the summary

Agent Context Compression: A Four-Layer Strategy to Cut Tokens Without Losing the Evidence

Agent Interview Question: How Does Context Compression Balance Token Cost and Decision Quality?

Interviewer asks In real business, how do you do context compression? How do you balance token cost with the model's decision quality?

My answer Based on my experience building agents, my principle for context compression is to use fewer tokens, keep enough information to support the next decision, and allow looking back when information is insufficient. So I typically use layered memory, on-demand retrieval, structured state, and raw-record lookup, combined with history summaries.

What information must be kept, and what can be compressed?

System rules, permissions, and disallowed operations should keep an authoritative version, separate from ordinary summaries. Current task state, such as the user's goal, confirmed conditions, and next steps, should be stored in a structured way. Key evidence for decisions, such as amounts, times, and terms, should be preserved precisely and linked to sources.

Explanatory processes and chitchat in historical interactions can be summarized. Large external documents should be retrieved and filtered first, then relevant content put into context.

There is a key distinction. What the user said can be summarized; what the system has currently confirmed should be stored as state. For example, for a customer-service refund, maintain a JSON with goal, order_id, and facts.

{
  "goal": "Verify whether this order can be refunded",
  "order_id": "A1042",
  "facts": [
    {"source": "User", "detail": "Says goods were not received"},
    {"source": "Logistics system", "detail": "Shows delivered"}
  ],
  "pending": ["Check delivery proof", "Confirm applicable refund terms"]
}

If this order is directly compressed into "the user didn't receive the goods, so it should be refunded", the conflicting evidence and pending items are both compressed away. What the next round needs to know is what still needs to be verified for this refund.

How would you assemble the context for each round?

My approach is to divide it into four layers.

Agent's four-layer context and lookup conditions

The first layer is stable rules. Put system rules, tool definitions, and business boundaries here. Duplicate and redundant wording can be removed, and relevant rules and tools loaded according to the task. The stable prefix can use prompt caching supported by the model service. Content that hits the cache still occupies the context window; the exact benefit depends on the provider.

The second layer is structured work state. Keep the goal of the current task, confirmed facts and constraints, actions already taken and their results, plus unresolved issues and evidence conflicts. This state is updated incrementally each round. In my development practice, repeatedly summarizing the previous summary tends to accumulate omissions and semantic drift. So keep timestamps and sources, and rebuild the state from raw records when necessary.

The third layer is on-demand retrieval of history and knowledge. Raw conversations, documents, and tool-call results are stored externally. Use the current problem plus task state to retrieve evidence, then rerank, deduplicate, select snippets, and attach sources. When retrieving, check whether it is the same order or contract, whether it is the latest version, whether there are negations, exceptions, and preconditions, and whether evidence conflicts. For example, when checking what circumstances support a refund, also pay attention to what circumstances do not support a refund.

The fourth layer is recent verbatim dialogue. It mainly serves to resolve references like "it" and "which one just now", and also keeps temporary modifications the user made, information not yet written into state, and necessary tone. The length varies greatly per round; a round can be a few words or contain tens of thousands of tokens of tool output. I truncate according to token budget and semantic completeness.

When you actually need to compress, what do you touch first?

Generally my order is to do low-risk processing first, then lossy summarization.

  1. First delete clearly useless content, such as duplicate logs, HTML navigation, and duplicate retrieval snippets. Whether something is useless has to be judged against the task.
  2. Filter tool output to task-relevant fields. If an API returns more than two hundred fields and the task only needs a few, put only those fields into context. When other fields are needed, allow a re-query of the full return.
  3. Extract key original sentences. In high-sensitivity scenarios such as contracts, finance, and medical, prioritize keeping key sentences, exact numbers, and sources. Extracting original sentences makes it easier to preserve wording and applicability conditions.
  4. Generate summaries last. A template keeps goals, facts and sources, hard constraints, completed actions and results, unfinished items, conflicts and uncertainties, and the original positions to look up. These information items determine how long the summary should be; forcing a length tends to squeeze out conditions.

So how do you balance token cost and decision quality?

Allocate budget dynamically by decision risk. Chitchat can be compressed more; knowledge Q&A should keep relevant evidence and necessary history. For operations like refunds and permission changes, re-read key facts from authoritative systems when possible, and validate before execution. The more irreversible the task, the more verifiable evidence should be kept.

Allow expansion when information is insufficient. When key fields are missing, evidence conflicts, no applicable rule is found, citations cannot support the conclusion, or a high-risk operation is about to be executed, first supplement retrieval, and restore raw records if necessary. Trigger conditions are determined by rules and evidence validation; the model's self-reported confidence is not used as a basis for approval.

Optimize the cost of the whole task. Set thresholds, compress only after reaching them, update state incrementally in normal operation, and reuse cache for stable content. You also have to count summarization, retrieval, lookup, and rework. If saving 30% of tokens doubles the number of calls or increases the error rate, that is negative optimization.

Comments

Top 1 from juejin.cn, machine-translated. The original thread is authoritative.

badhope 1 likes

I basically agree with this layered memory approach, but I'd add one more thing: the compressed state must be able to point back to the original evidence. For example, in a refund scenario, every fact needs a source and timestamp; when the model says "the package has been signed for," it should be able to link back to the tracking number. Otherwise, if the summary gets something wrong, every subsequent turn reasons from the wrong premise. We also enforce a hard constraint in production: amounts, times, and order numbers are excluded from summarization and are only read from structured fields. How would you handle conflicts between the summary and the original records?