Context Compression and Archiving for Long LLM Conversations: A Practical Guide
This guide explains why long LLM conversations lose context as the window fills up, and how to fix it by moving memory outside the context window. It covers a three-layer design (rolling summaries, structured archives, retrieval-based injection), a JSON archive schema that preserves rejected options and style settings, layered compression from turn-level to session-level, and how to re-inject state into a new session. It also lists common failure modes such as summary drift and broken references, plus engineering practices for storage, async summarization, monitoring, and data masking.
1. The Problem: Why Deeper Conversations Get Forgotten Completely
LLM inference depends on a finite context window. Once that window fills up, early content is truncated or down-weighted, and the model starts to “black out”: character relationships, constraints, and previously rejected options from earlier turns all stop applying. Users are forced to start a new session, only to find it knows nothing about the history. They have to re-explain the background, and interaction costs spike.
This is not a flaw in one particular product but a shared constraint of current mainstream architectures. In engineering terms, it splits into two problems: a capacity problem (the window cannot hold everything) and a fidelity problem (compression is lossy). The second one is what really determines the experience.
2. Core Idea: Move “Memory” Out of the Context Window
There is only one viable path: externalize conversation state into reusable structured assets, then inject it on demand. This breaks down into three layers.
- Rolling summary layer: Generate an incremental summary every N turns, keeping only decisions, conclusions, and open items.
- Structured archive layer: Persist summaries as data structures with fields, not as prose.
- Retrieval and injection layer: When a new session starts, select relevant fragments by task relevance and inject those, rather than dumping everything in.
Example Structure for a Structured Archive
{"session_id": "s-001","goal": "Design an order state machine","decisions": [{"topic": "state enumeration", "result": "adopt an 8-state model", "round": 12}],"constraints": ["must support idempotency", "latency target P99 < 200ms"],"rejected": [{"option": "polling approach", "reason": "cost too high"}],"open_questions": ["how to choose the compensation transaction approach"],"style": {"tone": "concise", "language": "Chinese"}}
The key is to preserve rejected options and style settings. Most summaries do not fail because they miss conclusions; they fail because they miss “what we are not doing,” which causes a new session to re-propose old approaches.
3. Compression Strategy: Layered Summaries and Key-Point Extraction
Compressing 50,000 words down to 3,000 in one pass looks efficient, but it concentrates risk: the model freely decides what counts as the “essence,” and results vary widely across runs. A more stable approach is to layer the process.
- Layer 1 (turn level): Extract one sentence per turn capturing “intent + conclusion,” with almost no loss.
- Layer 2 (stage level): Merge roughly every 20 turns, deduplicating and resolving references.
- Layer 3 (session level): Keep only four field types: goal, constraints, decisions, and open items.
for chunk in turn_sequence:summary = LLM("Extract intent and conclusion; do not speculate", chunk)stage_memory.append(summary)if len(stage_memory) % 20 == 0:session_state = LLM("Merge and deduplicate by JSON fields", stage_memory)
The prompt needs explicit constraints: “Rely only on the given text; do not add information that does not appear; leave fields blank when you cannot determine them.” This single sentence significantly suppresses hallucinated completion.
4. Re-Injection: How a New Session Picks Up Where It Left Off
Do not paste a long document at the start of a new session. Instead, provide three things in order: the task goal, hard constraints, and the three most recent decisions. Order affects weighting; later items are more likely to be followed, so put the most non-negotiable constraints at the end.
You are a senior engineer. Here is the historical archive:[Goal] ...[Hard constraints] Must be idempotent; do not introduce new external dependencies[Recent decisions] ...First restate your understanding of the constraints, then begin answering.
“Restate the constraints first” is a low-cost verification step that can expose misunderstandings early.
5. Common Failure Modes and Countermeasures
- Summary drift: Meaning shifts after multiple rounds of compression. Countermeasure: keep the original archive immutable and treat summaries as derived artifacts only.
- Broken references: “It” or “this approach” loses its referent. Countermeasure: force explicit subject completion during the merge stage.
- Style loss: Humor, irony, and wordplay are almost inevitably degraded by compression. Countermeasure: keep style in a separate field and archive original text fragments.
- Overconfidence: The model forcibly summarizes ambiguous content. Countermeasure: allow the output “insufficient information.”
6. Engineering Implementation Recommendations
Write archives to object storage or a database, keyed by session ID; use a message queue to trigger summary tasks asynchronously so interactions are not blocked; monitor and alert on summary quality, tracking key-point coverage before and after compression; mask sensitive fields before persisting to disk. If you use relevant general-purpose capabilities from Baidu AI Cloud, you can combine object storage, message queues, log services, and monitoring alerts to close the loop without building the entire infrastructure stack yourself.
7. Conclusion
Continuity in long conversations does not depend on how large the window is, but on whether state management is engineered. Turn memory into a structured, versionable, retrievable asset, and switching sessions changes from “starting over” to “resuming from a checkpoint.”
