Context Migration for LLM Conversations: A Practical Guide
This guide explains why LLM providers limit long conversation histories and how to treat chat sessions as a governable data asset. It covers a layered context model (L0–L4), export and cleaning steps, compression strategies such as recursive summarization and rolling memory, a three-part prompt structure with token budget control, and regression testing with memory probes to verify that a migrated session can continue reliably. Code examples for normalization, masking, and budget checks are included.
1. The Phenomenon and the Reality: Limits Reclaim Compute, They Do Not Delete Data
After a major LLM service opened up a fairly complete set of capability APIs, it began applying activity limits to very long conversation histories on both web and mobile clients. The typical behavior: historical sessions still open and remain readable, but no new messages can be appended. The notice usually cites one of two thresholds — inactivity measured in hours, or inactivity measured in days — and adds a suggestion to export the history for use in another application. Feedback about single-input length caps and daily quota exhaustion causing pauses has appeared around the same time.
The key point is that these limits are a resource scheduling strategy, not data deletion. Long conversations are expensive for three reasons:
- Linear cost of the context window: every request re-encodes the entire prior conversation. Tokens grow roughly linearly with the number of turns, and attention computation grows faster still.
- Cold data occupying hot resources: a session from months ago still has to be loaded in full when reactivated — a classic case of cold data sitting in hot memory.
- Long-tail requests amplifying peaks: a small number of very long sessions triggering during peak hours can noticeably raise overall latency and failure rates.
So the right response is neither to complain nor to wait for the limits to be lifted, but to treat a “session” as a data asset that needs governance: exportable, structured, compressible, migratable, and verifiable.
2. Before Migrating: Layer the Context
Dumping raw records into a new model all at once almost always fails — the length limit is exceeded, key information gets diluted, and instructions conflict. The more reliable engineering approach is to layer first:
- L0 Raw layer: the complete conversation transcript, archived only, never used for inference.
- L1 Fact layer: materials, data, and constraints the user provided (immutable facts).
- L2 Decision layer: finalized approaches, options already ruled out, expressions explicitly banned.
- L3 Task layer: the current goal, pending items, acceptance criteria.
- L4 Style layer: tone, format, length, glossary.
During migration, only L1–L4 go into the new session; L0 stays on the archive side for reference. This controls length and prevents old requirements from being reopened for discussion.
A minimal viable archive structure (illustrative, not tied to any specific product API):
{"session_id": "s-2025-01-0007","exported_at": "2025-01-01T00:00:00Z","facts": ["The product serves enterprise internal knowledge retrieval", "Data must not leave the country"],"decisions": ["Use retrieval augmentation rather than full fine-tuning", "Do not use first-person marketing tone"],"rejected": ["Pure keyword search approach"],"todo": ["Draft the API contract"],"style": {"length": "under 800 words", "format": "subheadings + lists"}}
3. Export and Cleanup: Turning “Chat History” into Computable Text
An export usually arrives as an archive or a structured file and needs four cleanup steps:
- Decode and split: normalize everything to UTF-8, split into independent records per session, drop empty and duplicate messages.
- Role normalization: map role identifiers from different sources to the four categories
system / user / assistant / tool. - Denoise: remove pleasantries, repeated confirmations, and redundant fragments left by failed retries.
- Redact: replace phone numbers, ID numbers, keys, and internal addresses with placeholders, keeping a reversible mapping table locally.
Sample code:
import re, jsondef normalize(records):out = []for r in records:role = {"me": "user", "bot": "assistant"}.get(r["role"], r["role"])text = re.sub(r"\s+", " ", r["text"]).strip()if not text or text in out[-1:]:continueout.append({"role": role, "text": text})return outdef mask(text):text = re.sub(r"1\d{10}", "<PHONE>", text)text = re.sub(r"sk-[A-Za-z0-9]+", "<KEY>", text)return text
4. Compression Strategy: Layered Summarization and Rolling Memory
The most common cause of migration failure is trying to fit too much in at once. Two composable compression methods are recommended:
(1) Segmented recursive summarization: split the long conversation into fixed-size windows, generate a summary of at most N words for each chunk, then summarize the set of summaries a second time, forming a tree structure. Information retention is usually better than a single long-document summary.
(2) Rolling memory: maintain a continuously updated state file, updating only the delta after each turn instead of re-summarizing the entire history.
[Confirmed facts] The database is relational; peak concurrency is about 2k QPS[Finalized] Read/write splitting with a cache in front[Ruled out] Direct single-database connection[Next step] Produce the capacity assessment table
The essential requirement: summaries must be traceable to the original fragments (keep message IDs or timestamps). Otherwise later verification is impossible and the model starts fabricating history.
5. Migrating into a New Session: Three-Part Prompts and Budget Control
When entering a new session, use a three-part structure — background, constraints, task — and state the budget explicitly:
Background: below is the compressed memory from the previous session (1200 words total).Constraints: do not reopen ruled-out options; keep the existing glossary.Task: based on the background above, draft the API contract in under 800 words.If information is missing, list the gaps first and do not speculate.
Also enforce a length budget: system prompt + memory + current input should stay within 60%–70% of the target model’s context limit, leaving room for additional turns. A simple approximate check works in practice:
def budget_ok(parts, limit=8000, ratio=0.65):total = sum(len(p) for p in parts)return total <= limit * ratio, total
6. Verification and Regression: Confirming the Conversation Really Continues
Whether a migration succeeded cannot be judged by feel; it needs regression cases. Prepare 5–10 “memory probe” questions covering the four categories — facts, decisions, ruled-out options, style — and compare each answer for consistency. If deviations appear, go back to the L1/L2 layers and fix the summaries rather than appending more explanation.
It also helps to establish a routine: export archives on a schedule, put key session summaries under version control, and proactively split overly long sessions. If you use cloud capabilities, object storage can handle cold archiving, a message queue can handle asynchronous export, and logs plus monitoring alerts can track failure rates — turning the external variable of platform limits into a session governance system you control.
