A Practical Guide to Exporting LLM Conversation History and Migrating Context

    Learn how to export complete LLM conversation history, strip non-semantic fields, control context length, and restore context in a new session. This guide covers data cleaning with Python, summarization strategies, API integration, and security best practices for context migration.

    1. Background and Migration Goals

    Multi-turn conversation is the most common way users interact with large language model (LLM) applications. As the number of turns grows, the context keeps expanding, and platforms often impose limits on session length, request frequency, or call counts. Once a limit is hit, users must re-describe the task background in a new session, which wastes time and risks losing constraints and intermediate conclusions that were already confirmed.

    Context migration addresses three problems:

    1. Obtaining the complete history of an existing conversation from a reliable source.
    2. Removing task-irrelevant UI state, caches, and statistical fields while keeping only semantic content.
    3. Restoring the context in a reasonable structure in a new environment so the model can continue previous work.

    The goal of migration is not to copy the raw file wholesale, but to extract the information that the model can understand and that contributes to the task. This principle guides every decision in the steps that follow.

    2. Understanding the Structure of Conversation Data

    Most conversational products export session files in JSON format. These files typically contain three kinds of content:

    • Metadata: session identifier, creation and update timestamps, model name or version, client identifier, and so on.
    • Runtime state: UI layout, draft content, loading flags, token counts, retry records, etc.
    • Message sequence: each message’s role (user, assistant, or system), text content, timestamp, and possible attachment references.

    For migration, what usually matters is the role and text of each message in the sequence, along with their order. Timestamps in the metadata can be used to verify completeness but generally do not need to be carried into the new session.

    Below is a simplified structural example; actual field names depend on the exported file:

    1. {
    2. "session_id": "abc123",
    3. "created_at": "2026-01-01T10:00:00Z",
    4. "stats": {"total_tokens": 48213},
    5. "messages": [
    6. {"role": "user", "content": "Please help me document the fields in this dataset.", "ts": 1767261600},
    7. {"role": "assistant", "content": "Sure, please provide a data sample.", "ts": 1767261612}
    8. ]
    9. }

    After obtaining the file, it is a good idea to use an editor or a simple script to count the frequency of each field and confirm where the message array actually lives in the hierarchy. Export formats vary across products: messages may be nested inside a child object, or branched conversations may be stored as a tree. With a tree structure, you first need to trace back along the currently active branch to produce a linear path before further processing.

    3. Preparation Before Migration

    Three things should be completed before touching the data.

    Confirm data ownership and authorization scope. Conversation records may contain personal information, business data, or internal material. Only process data you own or are authorized to use, and be clear about its purpose.

    Preserve the original file. Perform all processing on a copy and leave the original export untouched. If a cleaning rule turns out to be wrong, you can always roll back and start over.

    Build a redaction checklist. Common items to handle include phone numbers, email addresses, ID numbers, internal service addresses, keys, and tokens. Scanning the file with regular expressions or a dedicated detection tool before migration prevents sensitive information from leaking into the new environment.

    4. Field Reduction Strategy

    The principle of reduction is “keep the semantics, drop the state.” Use the following table as a guide:

    Category Action Example
    Message role and text Keep role, content
    Message order Keep array index order
    Timestamps Optionally keep, for sort verification ts
    UI and layout state Delete collapse state, scroll position
    Statistics and billing info Delete token counts, elapsed time
    Drafts and unsent content Delete unsubmitted input text
    Empty or duplicate messages Delete empty content or identical to the previous message

    The following Python example shows basic cleaning logic:

    1. import json
    2. from pathlib import Path
    3. KEEP_ROLES = {"system", "user", "assistant"}
    4. def load_turns(path: str) -> list[dict]:
    5. data = json.loads(Path(path).read_text(encoding="utf-8"))
    6. turns = []
    7. prev = None
    8. for item in data.get("messages", []):
    9. role = item.get("role")
    10. content = item.get("content")
    11. if role not in KEEP_ROLES or not isinstance(content, str):
    12. continue
    13. content = content.strip()
    14. if not content:
    15. continue
    16. turn = {"role": role, "content": content}
    17. if turn == prev: # drop messages identical to the previous one
    18. continue
    19. turns.append(turn)
    20. prev = turn
    21. return turns

    This code processes only text and roles, ignoring all other fields. Always read files as UTF-8 to avoid encoding issues with non-ASCII content.

    5. Controlling Context Length

    Even after cleaning, the text may still exceed the target model’s context window. Three common control methods are:

    1. Sliding window: keep only the most recent N turns. Simple to implement, but early constraints may be lost.
    2. Segmented summarization: have the model summarize earlier conversation, keeping conclusions, constraints, and to-do items, then concatenate the summary with the most recent turns in original form.
    3. Key information extraction: manually or with rules, tag items that must be preserved, such as requirement descriptions, interface definitions, and confirmed decisions.

    In most cases, a combination of the second and third methods works best: compress early content into a summary, list key decisions separately, and keep recent dialogue verbatim.

    The following code enforces a budget by character count. Character count is only an approximation—in practice, use the tokenizer of the target model to count tokens:

    1. def trim_to_budget(turns: list[dict], max_chars: int = 12000) -> list[dict]:
    2. kept, total = [], 0
    3. for turn in reversed(turns): # take from the newest messages first to prioritize recent content
    4. size = len(turn["content"])
    5. if total + size > max_chars:
    6. break
    7. kept.append(turn)
    8. total += size
    9. return list(reversed(kept))

    The budget should be determined by the target model’s context window, the length of the system prompt, and the expected length of new input, while reserving enough room for the output.

    6. Restoring Context in a New Session

    The key to restoring context is structured organization, not pasting the entire JSON to the model. The recommended structure is:

    • One system message explaining the nature of the session, the source of the history summary, and the constraints the model should follow.
    • Several history messages with their original roles, in chronological order.
    • A final user message: the question you want to continue working on.
    1. def build_messages(turns: list[dict], summary: str | None = None) -> list[dict]:
    2. header = (
    3. "The following is a condensed record of a previous conversation. "
    4. "Continue honoring the constraints and conclusions already confirmed in it."
    5. )
    6. system_content = header
    7. if summary:
    8. system_content += f"\n\nHistory summary:\n{summary}"
    9. messages = [{"role": "system", "content": system_content}]
    10. messages.extend(turns)
    11. return messages

    Two points deserve attention. First, if assistant replies in the history contain conclusions that are no longer valid, mark them as “deprecated” in the summary to prevent the model from reusing incorrect information. Second, if the original conversation contains code or tables, preserve the original Markdown or code block formatting during cleaning; otherwise the model will struggle to recognize the structure.

    7. Connecting to a New Model Service

    Once the context is assembled, the message list needs to be sent to the target service. Interface details differ across providers, but most use HTTP-based JSON requests authenticated with a token. The example below makes a generic request using only the standard library, with the endpoint, model name, and key all injected via environment variables:

    1. import os
    2. import json
    3. import urllib.request
    4. def send_chat(messages: list[dict]) -> str:
    5. url = os.environ["CHAT_API_URL"]
    6. api_key = os.environ["CHAT_API_KEY"]
    7. payload = {
    8. "model": os.environ.get("CHAT_MODEL", "default"),
    9. "messages": messages,
    10. }
    11. req = urllib.request.Request(
    12. url,
    13. data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
    14. headers={
    15. "Content-Type": "application/json",
    16. "Authorization": f"Bearer {api_key}",
    17. },
    18. method="POST",
    19. )
    20. with urllib.request.urlopen(req, timeout=60) as resp:
    21. body = json.loads(resp.read().decode("utf-8"))
    22. return body["choices"][0]["message"]["content"]

    In practice, verify the field paths of the response structure against the service documentation. The choices field in the example corresponds to services compatible with the common chat API conventions, but not every service follows them.

    If you use a self-hosted or enterprise-private model service, you can deploy a gateway on your internal network that exposes the same request format externally. This way, the migration script does not need to change when the underlying service changes.

    8. Security and Compliance Essentials

    Context migration involves large amounts of text data, and security is easy to overlook. The following recommendations can be applied directly:

    • Keep secrets out of code: store API keys and access tokens in environment variables or a secrets management service—never in scripts or version control.
    • Keep message content out of logs: when debugging, log only message counts, character counts, and elapsed time, not message bodies.
    • Minimize transmission: send only the history required for the current task, not the entire session file, to external services.
    • Clean up intermediate files regularly: delete temporary files produced during cleaning after use, or keep them in a controlled directory.
    • Redact before assembly: complete sensitive-data replacement before building the messages, and keep the replacement rules auditable.

    9. Common Issues and Troubleshooting

    Garbled output. Check that file reads and writes consistently use UTF-8, and that ensure_ascii=False is set during JSON serialization.

    The new session drifts from the original task. This usually means the summary is missing or the system prompt is unclear. List key constraints at the beginning of the system message and reduce irrelevant history.

    Context exceeds the limit. Lower the character budget or add a summarization step. A summary should typically be one tenth to one fifth the length of the original text, and must retain decisions and to-do items.

    Roles appear out of order. Confirm whether the message array is a linear path. If the raw data contains branches, select a branch and linearize it first.

    The model re-answers already-solved questions. State in the system message which problems have been resolved, and include the corresponding conclusions in the summary.

    10. Pre-Launch Checklist

    Before running a formal migration, verify each of the following:

    1. Data ownership is clear, and a redaction scan has been completed.
    2. The original file is backed up, and cleaning is performed on a copy.
    3. Message roles, text, and order have been verified, and the count matches the original session.
    4. Context length fits within the target model’s window, with room reserved for output.
    5. The summary covers key decisions, constraints, and to-do items.
    6. Keys are injected via environment variables, and logs contain no message bodies.
    7. A trial run with a simple question confirms the new session can correctly reference the historical information.

    Following this workflow turns context migration from a one-off manual task into a reusable script. As conversation tools and model services evolve, you only need to adjust the export parsing and API call steps—the core logic for cleaning, compression, and restoration stays the same.