A Guide to Migrating Long Conversation History: Export, Segmentation, and Context Reconstruction
When migrating long LLM conversation histories, simply exporting files does not restore the session due to context window limitations. This guide outlines a structured approach to parsing, segmenting, summarizing, and reconstructing context. It addresses key constraints like capacity, data structure, and semantic conflicts, ensuring that the new conversation retains continuity and accuracy while fitting within token limits.
I. The Core Problem: Readable Records ≠ Resumable Conversations
When a service imposes limits on long conversations, a common symptom is that old sessions can still be opened and history can be reviewed, but new messages cannot be sent. This is usually caused by operational strategies such as quota limits, session timeout durations, single input length restrictions, or resource allocations. These restrictions are access controls and do not mean historical data is lost.
Exporting the file itself does not restore the conversation either. Language models do not maintain long-term “memory” on the server side; each request relies entirely on the context submitted with it. The context window is a limited token budget, and a history of tens of thousands of words often exceeds the acceptable range for a single request. Therefore, the core task of migration is to compress history into a form that fits the window while retaining key semantics.
II. Three Constraints to Clarify Before Migration
1. Capacity Constraints. The new platform’s context window has an upper limit, and space must be reserved for system instructions, the current query, and model output. Typically, historical context should be controlled to a certain proportion of the window—e.g., no more than a quarter—to ensure sufficient room for subsequent conversation.
2. Structural Constraints. The export package might be a compressed archive containing multiple files, where field names, time formats, and role identifiers differ across files. Before migration, the data model must be unified; otherwise, subsequent segmentation and summarization will be built on incorrect boundaries.
3. Semantic Constraints. In long conversations, early conclusions may be modified later. For example, an initial plan might be overturned, or parameters adjusted. If all history is treated equally during migration, the model will read outdated information and generate contradictory answers.
III. Candidate Solutions and Selection
| Solution | Pros | Cons |
|---|---|---|
| Paste full history | Simple to implement, lossless information | Easily exceeds window, high cost |
| Turn-by-turn replay | Faithfully restores conversation process | High number of requests, time-consuming, still limited by window |
| Hierarchical summary reconstruction | Small footprint, highly controllable | Information loss occurs, requires template design |
| Retrieval Augmented Generation (RAG) | Retrieves relevant turns on demand, highly scalable | Requires additional components like vector retrieval or keyword indexing |
In practice, a more robust approach is a hybrid solution: use hierarchical summaries to preserve the overall narrative, use retrieval to supplement specific details, and append the verbatim text of recent turns. This controls the size while retaining traceable original phrasing.
The complete workflow is: Export, Parse & Normalize, Segment, Chunk Compress, Key Information Extract, Context Assemble, Quality Assurance, Deploy. The steps are detailed below.
IV. Step 1: Parsing and Normalization
First, map fields from different sources to a unified structure. The recommended internal model is as follows:
{"conversation_id": "conv_0001","title": "Interface Performance Optimization Discussion","created_at": "2026-03-02T09:15:00+08:00","turns": [{"role": "user", "content": "Our query interface P99 latency is high, how to troubleshoot?", "timestamp": "2026-03-02T09:15:00+08:00"},{"role": "assistant", "content": "You can start with slow query logs and connection pool wait times.", "timestamp": "2026-03-02T09:15:20+08:00"}]}
Parsing code example (field names need to be adjusted based on actual export structure):
import jsonimport zipfilefrom datetime import datetimeROLE_MAP = {"user": "user", "human": "user", "assistant": "assistant", "ai": "assistant"}def load_raw_conversations(archive_path: str) -> list[dict]:"""Read all JSON files from the archive and return a unified list of conversations."""conversations = []with zipfile.ZipFile(archive_path) as zf:for name in zf.namelist():if not name.endswith(".json"):continuewith zf.open(name) as f:data = json.load(f)if isinstance(data, list):conversations.extend(data)else:conversations.append(data)return conversationsdef normalize(raw: dict) -> dict:"""Map raw conversation to unified structure and sort messages by time."""turns = []for msg in raw.get("messages", []):role = ROLE_MAP.get(str(msg.get("role", "")).lower())if role is None:continue # Skip system messages or unknown roles to avoid polluting contextturns.append({"role": role,"content": msg.get("content", "").strip(),"timestamp": msg.get("timestamp"),})turns.sort(key=lambda t: t["timestamp"] or "")return {"conversation_id": raw.get("id", ""),"title": raw.get("title", ""),"turns": turns,}
After normalization, count the number of turns, characters, and empty messages for each conversation. Anomalies (such as empty content or missing roles) should be logged separately to prevent silent discards.
V. Step 2: Segmentation by Semantic Boundaries
The basic unit for segmentation is a “single Q&A turn”, not a fixed character count. Cutting in the middle of a sentence breaks semantics and may separate a question from its answer into different chunks.
def chunk_turns(turns: list[dict], max_tokens: int, count_tokens) -> list[list[dict]]:"""Accumulate by turn, start a new chunk when exceeding budget. count_tokens provided by caller."""chunks, current, used = [], [], 0for turn in turns:cost = count_tokens(turn["content"])if current and used + cost > max_tokens:chunks.append(current)current, used = [], 0current.append(turn)used += costif current:chunks.append(current)return chunks
If a single message itself exceeds the budget, it should form its own chunk and be truncated during the summarization phase, while marking it as “overlong original text” in the metadata.
VI. Step 3: Chunk Compression and Hierarchical Summarization
Use a fixed template to generate summaries for each chunk. The benefit of a fixed template is stable output structure, facilitating subsequent merging and validation. Recommended template fields are as follows:
- Goal: The problem this segment aims to solve.
- Confirmed Conclusions: Discussed and adopted decisions.
- Constraints: Hard requirements such as version, environment, performance metrics, deadlines.
- Unfinished Items: Issues still pending resolution or explicitly marked as pending.
- Key Entities: Function names, config keys, numbers, paths, names, etc., should be preserved verbatim.
After generating summaries for each chunk, merge them pairwise in chronological order to form higher-level summaries until the total volume drops to the target size. This hierarchical structure, similar to a merge process, ensures that early content also has corresponding compressed results.
def hierarchical_summary(chunk_summaries: list[str], summarize, max_chars: int) -> str:"""Repeatedly merge adjacent summaries until total length does not exceed limit. summarize is an external function."""level = chunk_summarieswhile sum(len(s) for s in level) > max_chars and len(level) > 1:merged = []for i in range(0, len(level), 2):pair = level[i:i + 2]merged.append(summarize("\n\n".join(pair)))level = mergedreturn "\n\n".join(level)
Note that details may be lost at each level during merging. Therefore, key entities and numbers should be retained separately in the template and not subjected to free-form summarization.
VII. Step 4: Key Information Extraction and Conflict Resolution
Beyond summaries, structured information should be extracted separately to form a “Current Valid Facts” table. Each record includes content, source turn, and status. Statuses are typically divided into three categories: Valid, Superseded, and To Be Confirmed.
Rules for handling conflicts are as follows:
- Process in chronological order; explicit later decisions override previous ones, and the old decision is marked as “Superseded”.
- Proposals that only exist in discussions and have not been confirmed are marked as “To Be Confirmed” and must not be used as conclusions.
- Code snippets, commands, configuration values, and numbers must be preserved verbatim without paraphrasing.
This step may seem tedious, but it is crucial to prevent the new conversation from producing self-contradictory answers.
VIII. Step 5: Context Reconstruction
The beginning of the new conversation should include a clear explanation telling the model that this content is migrated historical material, distinguishing between summaries and verbatim text. The recommended assembly structure is as follows:
[System Instruction]The following content is migrated material from a previous conversation. Please refer to "Current Valid Facts" as authoritative.If a summary conflicts with the original text, the original text prevails, and prompt the user to confirm.[Current Valid Facts]- Goal: Optimize query interface P99 latency- Confirmed: Connection pool limit adjusted to 64 (Source: Turn 12)- Superseded: Early plan "Add caching layer" rejected (Source: Turn 5)- To Be Confirmed: Whether to enable read-write separation (Source: Turn 30)[Hierarchical Summary]...[Recent Verbatim Conversation]The last 6 to 10 turns are fully preserved to maintain tone and detail.[Current Question]The user's new question
Retaining the verbatim text of recent turns is critical. It allows the model to continue the context of the last discussion, reducing semantic breaks caused by summary compression.
IX. Step 6: Quality Assurance
After migration, the following checks should be performed; don’t just check “can a message be sent”.
Entity Coverage Check. Extract key entities from the original text and check if each appears in the summary or facts table. Missing entities need to be supplemented.
import redef missing_entities(source_text: str, summary_text: str) -> set[str]:"""Find identifiers present in original text but missing in summary, simple check for omissions."""pattern = re.compile(r"[A-Za-z_][A-Za-z0-9_\.]{3,}|\d+(?:\.\d+)?")src = set(pattern.findall(source_text))dst = set(pattern.findall(summary_text))return src - dst
Sample Replay. Select about ten typical questions from the history, let the new conversation answer them, and compare with the original conclusions. Focus on checking whether numbers, conclusions, and constraints are consistent.
Verbatim Comparison. Perform string-level comparisons on code and configuration items to avoid spelling deviations introduced by summaries.
X. Privacy and Compliance
Exported history records may contain personal information, internal data, or even keys and access tokens. The processing workflow should follow these principles:
- Before migration, use regex and rules to scan for sensitive fields, such as phone numbers, emails, identifiers, and credential formats, replacing them uniformly with placeholders.
- Intermediate products (decompressed directories, segmented files, summary caches) should only be saved in local controlled locations and deleted promptly after use.
- Before handing data over to any external processing service, confirm the other party’s data retention policy and obtain authorization from the data owner.
- Follow the principle of least privilege; only submit the content necessary for context reconstruction, do not upload the entire package.
XI. Cost and Maintainability
Hierarchical summarization incurs multiple model calls, and costs increase with history length. The following measures can be taken to reduce overhead:
- Use the hash of the chunk content as a cache key to directly reuse existing summaries during repeated processing.
- Record the template version, generation time, and source chunk range for each generated summary to facilitate tracing and re-running.
- Make the entire workflow idempotent. Executing the same input multiple times should yield the same result or be identified as already completed.
XII. Common Pitfalls
- Stuffing exported files directly into context. Content exceeding the window will be truncated, often at uncontrollable positions, potentially cutting off the most critical constraints.
- Keeping only summaries, discarding original text. Summaries are good for conveying the narrative but cannot replace precise numbers and code.
- Ignoring chronological order. Later decisions override earlier ones; out-of-order processing will reactivate old plans.
- Not recording summary sources. Without the ability to trace which turn a conclusion came from, it is difficult to verify during disputes.
The goal of migration is to give the new conversation working conditions equivalent to the original within a limited window. Executing in the order of parsing, segmentation, compression, extraction, reconstruction, and validation, while retaining traceable records, allows historical conversations to continue functioning in the new environment.
