Migrating AI Chat Context Safely After Conversation Length Limits

    This article explains why AI platforms limit long conversations, including GPU memory growth from the KV cache and compute costs from recomputing history. It covers why exported chat histories often perform poorly in new sessions, provides a Python script to parse and clean the exports, and describes map-reduce summarization, compliance checks, context injection, and a long-term state management architecture built on API calls, persistent storage, and vector retrieval.

    1. Why Long Conversations Get Limited

    Platform limits usually come from two pressures. The first is GPU memory. During inference, a large language model keeps the context it has already processed as a KV cache in GPU memory. The memory used by the KV cache grows roughly linearly with sequence length, and the more concurrent sessions run on the same GPU, the tighter memory becomes. This conclusion assumes a standard attention architecture. Techniques such as grouped-query attention and cache quantization reduce the memory cost per token, but they do not change the growth trend. As a result, long sessions that stay idle for a long time may be reclaimed or frozen to free resources for other requests.

    The second pressure is compute and scheduling cost. If the server does not enable prefix caching or KV cache reuse, every request recomputes the historical tokens, so the more turns a conversation has, the more computation each request requires. With caching enabled, the repeated part can be skipped, but the cache itself still consumes storage and memory. Platform limits are also shaped by concurrency caps, user quotas, session storage costs, and scheduling policies. The “insufficient compute” message users see is usually the result of several constraints combined, so it is hard to attribute to a single metric.

    This distinction matters in practice. If limits mainly come from concurrency and quotas, switching to a different time of day or shortening each input may help. If limits come from storage and scheduling, exporting the history and rebuilding it elsewhere is the more reliable approach.

    2. Why an Exported History Cannot Simply Be Reused

    Many users exported their history as the platform suggested, then found that the new conversation performed much worse. There are three main reasons.

    First, context windows have hard limits. A long conversation may contain dozens of turns, including a lot of code, revision requests, and rejected approaches. Exported JSON files are large, while most new platforms and local models have limited effective windows and cannot accept everything at once. Pasting the full export causes earlier content to be truncated, and key constraints may be the first to be lost.

    Second, implicit constraints are spread across turns. Through repeated corrections, the user taught the model their writing style, code conventions, and things to avoid. This information is not stored in a structured form. It is scattered across different turns. After migration, the new model often cannot extract these constraints from the history, and output quality drops.

    Third, export formats differ. After unzipping, files are usually JSON or Markdown, and field names, timestamp formats, and role identifiers vary from platform to platform. Feeding them directly to a new model can cause parsing errors or role confusion. The table below lists common field mappings. Build a similar mapping table before migrating.

    Unified field Common source fields Handling notes
    role role, sender, author.role Normalize to user, assistant, or system. Mark unrecognized values as unknown.
    text content, text, parts May be a string or an array. Extract text item by item.
    timestamp create_time, created_at, ts Convert to ISO 8601 with a time zone. Treat values without a time zone as UTC.
    attachments files, attachments, images Record references to images and files separately. Do not treat them as text.

    When parsing fails, check the following: empty or malformed timestamps, missing role fields, content stored as arrays or nested structures, multiple JSON files in one ZIP package, files not encoded in UTF-8, and duplicate messages in the export. Each of these can cause misordered messages, lost content, or duplicate injection.

    3. Engineering Steps for Migration

    Step 1: Parse, Map, and Clean

    The first step is to convert the exported files into a unified intermediate format. The script should identify the different message container structures, extract roles and text using the field mapping table, handle both strings and multimodal arrays, deduplicate messages by ID, and sort them by time. The code below is a skeleton you can adapt. Before using it, adjust the field names based on real export samples.

    1. import json
    2. from datetime import datetime, timezone
    3. ROLE_MAP = {
    4. "user": "user", "human": "user",
    5. "assistant": "assistant", "ai": "assistant", "model": "assistant",
    6. "system": "system",
    7. }
    8. def normalize_content(content):
    9. """Handle strings, arrays, and multimodal structures. Keep only the text parts."""
    10. if content is None:
    11. return ""
    12. if isinstance(content, str):
    13. return content.strip()
    14. if isinstance(content, list):
    15. parts = []
    16. for part in content:
    17. if isinstance(part, str):
    18. parts.append(part)
    19. elif isinstance(part, dict):
    20. text = part.get("text") or part.get("content")
    21. if isinstance(text, str):
    22. parts.append(text)
    23. return "\n".join(p.strip() for p in parts if p.strip())
    24. return str(content).strip()
    25. def extract_messages(raw):
    26. if isinstance(raw, list):
    27. return raw
    28. if isinstance(raw, dict):
    29. if isinstance(raw.get("messages"), list):
    30. return raw["messages"]
    31. if isinstance(raw.get("mapping"), dict):
    32. return [n["message"] for n in raw["mapping"].values()
    33. if isinstance(n, dict) and n.get("message")]
    34. return []
    35. def parse_timestamp(value):
    36. if value in (None, ""):
    37. return None
    38. try:
    39. if isinstance(value, (int, float)):
    40. dt = datetime.fromtimestamp(value, tz=timezone.utc)
    41. else:
    42. dt = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
    43. except (ValueError, OSError, OverflowError):
    44. return None
    45. if dt.tzinfo is None:
    46. dt = dt.replace(tzinfo=timezone.utc)
    47. return dt
    48. def parse_exported_chat(json_file_path):
    49. with open(json_file_path, "r", encoding="utf-8") as f:
    50. raw = json.load(f)
    51. seen_ids, dialogues = set(), []
    52. for item in extract_messages(raw):
    53. if not isinstance(item, dict):
    54. continue
    55. msg_id = item.get("id")
    56. if msg_id is not None:
    57. if msg_id in seen_ids:
    58. continue
    59. seen_ids.add(msg_id)
    60. role_raw = str(item.get("role") or item.get("sender") or "unknown").lower()
    61. text = normalize_content(item.get("content") or item.get("text") or item.get("parts"))
    62. if not text:
    63. continue
    64. dialogues.append({
    65. "id": msg_id,
    66. "role": ROLE_MAP.get(role_raw, "unknown"),
    67. "text": text,
    68. "time": parse_timestamp(item.get("timestamp") or item.get("created_at")),
    69. })
    70. epoch = datetime.min.replace(tzinfo=timezone.utc)
    71. dialogues.sort(key=lambda d: (d["time"] is None, d["time"] or epoch))
    72. return dialogues

    All parsing runs locally. Keep the original ZIP and JSON files untouched, and save the cleaned output as a new file.

    Step 2: Chunked Compression (Map-Reduce)

    When the history exceeds the target model’s context window, compress it first. A common approach is to use another model with a longer context window, or to process the history in sliding windows.

    • Map: Split the conversation by topic, date, or fixed token count. Summarize each chunk separately, extracting key decisions, constraints, things to avoid, and code structure.
    • Reduce: Merge the chunk summaries, remove duplicates, resolve contradictions, and produce a global background description.

    You can base the prompt on the following example, and ask the model to label each conclusion with the turn it came from:

    Analyze the following multi-turn conversation records and extract and summarize: 1. the user’s core goal; 2. the finalized solution or code structure that has been decided; 3. approaches the user explicitly prohibits or rules out; 4. important business rules or constraints. Label each conclusion with its source turn number. Output the result as structured JSON to serve as the background context for the new conversation.

    This step has three costs to plan for. The first is cost. Each chunk requires a model call, so total token usage approaches the length of the original history plus the overhead of the summaries. The second is latency. More chunks mean longer runtime, so run the Map stage in parallel. The third is failure. If a chunk times out or returns malformed output, retry only that chunk and log its number instead of rerunning the whole job.

    Complete compliance checks before sending any content to a third-party model.

    • Redaction: Remove phone numbers, ID numbers, bank card numbers, access keys, and customer names before summarization.
    • Authorization: Confirm that the exported conversations belong to you or that you have permission to use them. Check the platform’s terms of service on data export and reprocessing.
    • Cross-border transfer: If you use an overseas model service, confirm whether personal information or important data leaves your country or region under the laws that apply to you. If needed, use a model hosted in your region or deployed locally.
    • Encryption and retention: Use TLS for transmission, encrypt stored data, set retention periods for intermediate files, and delete them automatically when they expire.

    Check the summary quality item by item.

    Check item Verification question
    Goal Does the summary accurately state what the user ultimately wants to accomplish?
    Constraints Are the business rules, performance requirements, and compatibility scope complete?
    Excl