跪拜 Guibai
← All articles
Backend · Interview · Artificial Intelligence

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

By AAA爱学习的刘哥 ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

Agent builders pay for every token in the context window, and aggressive summarization can erase the exact evidence the next decision depends on. This approach makes compression a risk-management problem, with structured state and retrieval standing in for the details that summaries lose.

Summary

Agent context splits into four layers. Stable rules and tool definitions form a cached prefix; task state is a structured record of goals, confirmed facts, and pending checks; history and documents stay outside the window and get pulled in by retrieval; recent turns remain verbatim to resolve references. Compression follows a fixed order: delete useless content, filter tool output to task-relevant fields, extract key original sentences, and generate summaries last.

The strategy separates what the user said from what the system has confirmed. User statements can be summarized; confirmed facts belong in structured state, like a JSON refund record that keeps conflicting evidence and open questions visible. Token budgets are allocated by decision risk, with high-risk operations re-reading authoritative data and validating before execution. If key fields are missing or evidence conflicts, the system expands context through retrieval or raw records. Whole-task cost matters more than per-call tokens: saving 30% of tokens is a loss if it doubles calls or raises the error rate.

Takeaways
— A four-layer context assembly separates stable rules, structured task state, on-demand retrieval, and recent verbatim dialogue.
— User statements can be summarized; system-confirmed facts belong in structured state, not in a prose summary.
— A refund task can be represented as JSON with goal, order_id, facts with sources, and pending items.
— Prompt caching can reduce processing cost for a stable prefix, but cached tokens still occupy the context window and benefits depend on the provider.
— Repeatedly summarizing previous summaries accumulates omissions and semantic drift.
— Retrieval must verify same order or contract, latest version, negations, exceptions, preconditions, and evidence conflicts.
— Compression order is delete useless content, filter tool fields, extract key original sentences, then generate summaries.
— High-sensitivity domains should keep original sentences, exact numbers, and sources.
— Token budgets should scale with decision risk; irreversible operations re-read authoritative data and validate before execution.
— Model self-reported confidence is not a valid approval gate for high-risk actions; rules and evidence validation decide.
— Cost optimization covers summarization, retrieval, lookup, and rework; saving 30% of tokens is negative optimization if calls double or errors rise.
Conclusions

Context compression becomes a data-governance problem: structured state preserves what the system can act on, and summaries only handle what is safe to lose.

The whole-task cost view is the sharpest point; a token cut that doubles calls or raises error rate is a net loss, so per-request optimization is the wrong target.

Requiring evidence validation instead of model confidence for high-risk actions treats the model as untrustworthy for safety-critical judgment, a deliberate and debatable design choice.

The four-layer assembly makes the context window behave like a cache, with stable rules warm, state incrementally updated, history fetched on demand, and recent turns kept verbatim for reference resolution.

Concepts & terms
Prompt caching
A model service feature that caches a stable prefix of tokens so repeated calls cost less to process. Cached tokens still count toward the context window, and the actual savings depend on the provider.
Structured task state
A machine-readable record of the current task's goal, confirmed facts, constraints, completed actions, and open items. It is updated incrementally instead of being rewritten as a summary.
Semantic drift
The gradual loss or alteration of facts that happens when summaries are repeatedly summarized, because each compression step introduces omissions and rewording.
On-demand retrieval
Keeping raw conversation, documents, and tool outputs outside the context window and pulling in only the evidence relevant to the current problem and task state, with sources attached.
From the discussion
Featured comments
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?

See top comments, translated →
Source: juejin.cn ↗ Google Translate ↗ Backup ↗