How to Migrate AI Chat History and Resume Long Conversations in a New Context Window

    Learn why AI chat sessions hit read-only or truncation limits, why exported chat files cannot restore a conversation's context state, and how to migrate conversation history using a structured state file plus recent messages, with step-by-step instructions and Python code.

    Why Conversations Break During Migration

    Large language models read all preceding text every time they generate a reply. The longer a conversation grows, the more text the model must process. Providers typically impose limits on single-input length, per-session length, and daily usage. When these limits are triggered, three behaviors are common:

    • The old session becomes read-only: you can browse it but cannot send new messages.
    • New messages are rejected with a quota or capacity error.
    • Once a session exceeds its length limit, earlier content is silently truncated.

    All three cases share a common trait: the history is still stored, but the session’s usable state has changed. What you see is “the chat log is still there,” yet the only thing you can actually do is read it.

    Exported Files Are Not Restored Conversations

    An export file preserves text; resuming a conversation requires context state. The gap shows up in three ways:

    Length. A complete export can far exceed the single-input limit. Pasting everything into a new session either gets truncated or fills the context window, leaving little room for new questions.

    Structure. The original log is arranged chronologically, with questions, revisions, and retractions mixed together. The model must figure out on its own which instructions still apply—and when it guesses wrong, it repeats solutions that were already ruled out.

    Implicit constraints. Users often state mid-conversation things like “don’t use this phrasing” or “the second section is finalized.” These requirements are scattered across dozens of turns, and relying on memory to recall them leads to omissions.

    Comparing Three Migration Approaches

    There are three common approaches:

    1. Full paste. The simplest to implement, but constrained by length limits, it consumes a large amount of input quota, and old content dilutes the weight of new questions. Suitable for shorter histories.
    2. Chunked summaries stitched together. Split the history into segments, summarize each, then merge. High compression, but summaries can drop specific constraints and require manual review.
    3. Structured state plus recent raw turns. Split the conversation into four categories—background, constraints, finalized content, and open questions—then inject only the state and the most recent turns. Highest information density and easiest to maintain.

    This article recommends the third approach. It separates “what needs to be remembered” from “what needs to be asked now,” so the very first message in a new session can carry the complete working state.

    Implementation Steps

    Step 1: Backup and verification. After exporting, save the original file and compute its SHA-256 digest so you can later confirm the file has not been altered.

    Step 2: Parsing and chunking. Preserve each message’s role, timestamp, and body, and split the content into chunks by character count. Place chunk boundaries at turn boundaries so a question-answer pair isn’t split apart. Character count is only an approximation—different models use different tokenizers, so calibrate the chunking threshold against the target model’s tokenization rules.

    Step 3: Chunk summarization. For each chunk, extract background facts, constraints, finalized content, and open questions. The prompt should require the model to tag each item with the corresponding original turn number for traceability.

    Step 4: Merge into a state file. Combine and deduplicate results from all chunks. If two requirements contradict each other, prefer the later turn, but keep the older record and note its timestamp.

    Step 5: Inject into a new session. Place the state content at the start of the new session, followed by the raw text of the last three to five turns, so the model has both the full working picture and the current context.

    Here is sample code. summarize_chunk should be implemented with your own model and return a dictionary matching the state structure.

    1. import hashlib
    2. import json
    3. from pathlib import Path
    4. def file_sha256(path: Path) -> str:
    5. digest = hashlib.sha256()
    6. with path.open("rb") as f:
    7. for block in iter(lambda: f.read(65536), b""):
    8. digest.update(block)
    9. return digest.hexdigest()
    10. def load_messages(path: Path) -> list[dict]:
    11. with path.open("r", encoding="utf-8") as f:
    12. raw = json.load(f)
    13. return [
    14. {
    15. "role": item.get("role", "unknown"),
    16. "content": item.get("content", ""),
    17. "time": item.get("time"),
    18. }
    19. for item in raw
    20. ]
    21. def chunk_by_turns(messages: list[dict], max_chars: int = 6000) -> list[list[dict]]:
    22. chunks, current, size = [], [], 0
    23. for msg in messages:
    24. length = len(msg["content"])
    25. if current and size + length > max_chars:
    26. chunks.append(current)
    27. current, size = [], 0
    28. current.append(msg)
    29. size += length
    30. if current:
    31. chunks.append(current)
    32. return chunks
    33. def empty_state() -> dict:
    34. return {
    35. "background": [],
    36. "constraints": [],
    37. "finalized_sections": [],
    38. "open_questions": [],
    39. }
    40. def merge_state(base: dict, update: dict) -> dict:
    41. for key in base:
    42. for item in update.get(key, []):
    43. if item not in base[key]:
    44. base[key].append(item)
    45. return base
    46. def build_opening_prompt(state: dict, recent: list[dict]) -> str:
    47. titles = [
    48. ("background", "Background"),
    49. ("constraints", "Constraints"),
    50. ("finalized_sections", "Finalized content"),
    51. ("open_questions", "Open questions"),
    52. ]
    53. lines = ["Here is the state of previous work. Please continue collaborating based on it."]
    54. for key, title in titles:
    55. if state[key]:
    56. lines.append(f"## {title}")
    57. lines.extend(f"- {item}" for item in state[key])
    58. lines.append("## Recent conversation")
    59. lines.extend(f"[{m['role']}] {m['content']}" for m in recent)
    60. return "\n".join(lines)
    61. def migrate(export_path: Path, summarize_chunk) -> str:
    62. print("Source file checksum:", file_sha256(export_path))
    63. messages = load_messages(export_path)
    64. state = empty_state()
    65. for chunk in chunk_by_turns(messages):
    66. state = merge_state(state, summarize_chunk(chunk))
    67. return build_opening_prompt(state, messages[-5:])

    Quality Checks and Risks

    Summary distortion is the most common problem. Every constraint should carry the original turn number, and items should be sampled and checked against the source text. Numbers, proper names, and quoted content in summaries deserve priority verification.

    Privacy risk also needs attention. Export files may contain personal information, internal material, or trade secrets. Before sending anything to any external service, sanitize the data first and confirm that service’s data usage terms.

    Archiving habits determine migration cost. Never leave the only copy of your work in an online service. Periodically save both the state file and the original export to storage you control, so that when provider limits change, you can resume work quickly using the same workflow.