How to Safely Export and Migrate Chat Conversation History

    Learn how to export conversation history from AI chat platforms on web and mobile, clean the raw export into OpenAI-compatible role/content messages with a Python script, count tokens, redact sensitive data, and verify the migration results. Includes troubleshooting tips for common export and parsing failures.

    1. Before Exporting: Know What the File Contains and the Risks

    When your session quota runs out, you may no longer be able to send new messages, but the export function usually remains available. This article only covers history records that the platform officially allows you to export; it does not cover bypassing quota limits. Whether a conversation can be continued after migration depends on the target platform’s rules, and this article makes no guarantees.

    The exported file is data designed for UI rendering and state restoration, not plain conversation text. It may contain account details, phone numbers, email addresses, API keys embedded in code, customer data, and work content. Before doing anything, take three precautions: back up the original file, process it in an isolated local environment, and redact sensitive content before uploading anything to a third-party platform.

    Open the file and inspect the top-level structure first. If the top level is an array, each element usually corresponds to one conversation. If it is an object, common fields include messages or mapping. Field names vary across platforms. This article uses a ChatGPT-style conversations.json as the example; for other platforms, adapt the script to the actual field names.

    2. Export Checklist for Web and Mobile

    2.1 Web (Desktop)

    Follow these steps in order; exact labels depend on the current UI:

    1. After logging in, click your avatar or account entry in the lower-left corner.
    2. Go to “Settings” and find “Data controls” or “Data management.”
    3. Click “Export data.” The platform typically emails a download link to your registered address.
    4. Download the archive and extract it to get conversations.json.
    5. Check the file size and modification time to confirm it is not empty or an old file.

    2.2 Mobile (iOS)

    1. Find the export entry in the app’s settings page. Tapping it generates a temporary link.
    2. Temporary links usually expire quickly, so open the link in Safari as soon as it is generated.
    3. After downloading, check the “Downloads” folder in the Files app. If the file cannot be saved, verify that the app has file access permission in system settings.
    4. Copy the file to your computer for further processing.

    2.3 Mobile (Android)

    1. Find the export entry in the app and generate a download link.
    2. Prefer opening the link in Chrome. System browsers sometimes block non-standard downloads, and switching to Chrome often resolves this.
    3. After downloading, locate the file in the “Downloads” folder of the file manager.
    4. Confirm the app has storage write permission; otherwise the file may fail to save.

    2.4 Common Errors and Retry Order

    When export fails, troubleshoot in the following order instead of repeatedly tapping the generate button:

    1. Confirm the file is not empty and not a previous export.
    2. If the link has expired, regenerate it.
    3. Try a different browser, especially on mobile.
    4. Switch to web export.
    5. If it still fails, contact the platform’s official support channels with your app version and device model.

    3. Field Mapping, Cleaning Script, and Output Structure

    3.1 Target Structure

    Mainstream OpenAI-compatible APIs accept an array of objects, each containing role and content. The goal of cleaning is to convert the platform’s raw structure into this format while removing metadata such as timestamps, rendering states, and retry markers.

    3.2 Field Mapping Table (ChatGPT-Style Export)

    Source field Meaning Target field Handling
    mapping Message tree keyed by node ID None Trace back from current_node along parent to the root
    message.author.role Role role Keep only user and assistant
    message.content.parts List of text fragments content Keep only string fragments, join and trim whitespace
    content.content_type Content type None Process only text; skip images, attachment placeholders, etc.
    Empty message or parts System placeholder node None Skip
    Consecutive duplicates with same role Duplicate submission or generation None Deduplicate
    create_time, etc. Timestamps None Delete

    If the export is a linear array (e.g., a messages list), the script automatically falls back to linear traversal with the same mapping rules.

    3.3 Complete Cleaning Script

    The script keeps only the branch containing current_node, so other branches discarded by regeneration are dropped. If you want to keep all branches, modify the traversal logic yourself.

    Save as clean_export.py:

    1. import json
    2. import sys
    3. from pathlib import Path
    4. ALLOWED_ROLES = {"user", "assistant"}
    5. MAX_DEPTH = 5000
    6. def extract_text(content):
    7. """Extract plain text from a content object; skip non-text types."""
    8. if not isinstance(content, dict):
    9. return ""
    10. if content.get("content_type", "text") != "text":
    11. return ""
    12. parts = content.get("parts") or []
    13. texts = [p.strip() for p in parts if isinstance(p, str) and p.strip()]
    14. return "\n".join(texts)
    15. def get_text(msg):
    16. content = msg.get("content")
    17. if isinstance(content, str):
    18. return content.strip()
    19. return extract_text(content)
    20. def get_role(msg):
    21. author = msg.get("author")
    22. if isinstance(author, dict):
    23. return author.get("role", "")
    24. return msg.get("role", "")
    25. def walk_branch(mapping, current_node):
    26. """Trace from current_node up to the root via parent, returning nodes in chronological order."""
    27. chain, seen = [], set()
    28. node_id = current_node
    29. while node_id:
    30. if node_id in seen:
    31. print(f"Warning: circular reference at node {node_id}; traceback interrupted", file=sys.stderr)
    32. break
    33. if len(chain) >= MAX_DEPTH:
    34. print("Warning: branch depth exceeds limit; traceback interrupted", file=sys.stderr)
    35. break
    36. node = mapping.get(node_id)
    37. if node is None:
    38. print(f"Warning: parent node {node_id} not found; traceback ended early", file=sys.stderr)
    39. break
    40. seen.add(node_id)
    41. chain.append(node)
    42. node_id = node.get("parent")
    43. return list(reversed(chain))
    44. def clean_conversation(conv):
    45. mapping = conv.get("mapping")
    46. current = conv.get("current_node")
    47. if isinstance(mapping, dict) and current:
    48. raw = [n.get("message") for n in walk_branch(mapping, current)]
    49. else:
    50. # Fallback: used when the export is a linear messages list
    51. raw = conv.get("messages") or []
    52. messages = []
    53. for msg in raw:
    54. if not isinstance(msg, dict):
    55. continue
    56. role = get_role(msg)
    57. if role not in ALLOWED_ROLES:
    58. continue
    59. text = get_text(msg)
    60. if not text:
    61. continue
    62. item = {"role": role, "content": text}
    63. if messages and messages[-1] == item:
    64. continue
    65. messages.append(item)
    66. return messages
    67. def normalize_top_level(data):
    68. """Support three top-level shapes: conversation array, object with conversations, single conversation object."""
    69. if isinstance(data, list):
    70. return data
    71. if isinstance(data, dict):
    72. if isinstance(data.get("conversations"), list):
    73. return data["conversations"]
    74. if "mapping" in data or "messages" in data:
    75. return [data]
    76. raise SystemExit("Unrecognized top-level structure: expected a conversation array, or an object containing mapping/messages.")
    77. def check_results(results):
    78. problems = []
    79. for conv in results:
    80. msgs = conv["messages"]
    81. for i, m in enumerate(msgs):
    82. if not m["content"]:
    83. problems.append(f"{conv['title']}: message {i} has empty content")
    84. for i in range(1, len(msgs)):
    85. if msgs[i]["role"] == msgs[i - 1]["role"]:
    86. problems.append(
    87. f"{conv['title']}: message {i} has the same role as the previous one ({msgs[i]['role']}); please review manually"
    88. )
    89. return problems
    90. def process_export(input_path, output_path):
    91. src, dst = Path(input_path), Path(output_path)
    92. try:
    93. with src.open("r", encoding="utf-8") as f:
    94. data = json.load(f)
    95. except FileNotFoundError:
    96. raise SystemExit(f"Input file not found: {src}")
    97. except json.JSONDecodeError as e:
    98. raise SystemExit(
    99. f"JSON parse failed (line {e.lineno}, column {e.colno}): {e.msg}. "
    100. "Make sure the file is complete and not truncated."
    101. )
    102. except OSError as e:
    103. raise SystemExit(f"Cannot read file: {e}")
    104. results = []
    105. for index, conv in enumerate(normalize_top_level(data), start=1):
    106. if not isinstance(conv, dict):
    107. continue
    108. messages = clean_conversation(conv)
    109. if messages:
    110. results.append({
    111. "title": conv.get("title") or f"Conversation {index}",
    112. "messages": messages,
    113. })
    114. if not results:
    115. raise SystemExit("No messages extracted. Check whether the field names match the mapping table.")
    116. for problem in check_results(results):
    117. print("Validation note: " + problem, file=sys.stderr)
    118. tmp = dst.with_name(dst.name + ".tmp")
    119. try:
    120. with tmp.open("w", encoding="utf-8") as f:
    121. json.dump(results, f, ensure_ascii=False, indent=2)
    122. tmp.replace(dst)
    123. except OSError as e:
    124. raise SystemExit(f"Write failed: {e}")
    125. total = sum(len(c["messages"]) for c in results)
    126. print(f"Done: {len(results)} conversations, {total} messages in total, written to {dst}")
    127. if __name__ == "__main__":
    128. if len(sys.argv) != 3:
    129. raise SystemExit("Usage: python clean_export.py input.json output.json")
    130. process_export(sys.argv[1], sys.argv[2])

    Example usage:

    1. python clean_export.py conversations.json cleaned.json

    The script writes results via a temporary file followed by a rename. If writing fails midway, the original output file is not corrupted.

    3.4 Cleaned Output Structure

    The output is an array where each element represents one conversation. In the example below, a duplicated user message has already been deduplicated:

    1. [
    2. {
    3. "title": "Weekly report drafting",
    4. "messages": [
    5. {"role": "user", "content": "Help me draft a weekly report template."},
    6. {"role": "assistant", "content": "Sure, here is the template:\n1. Completed this week\n2. Risks and blockers\n3. Plan for next week"}
    7. ]
    8. }
    9. ]

    When migrating to another API, simply extract the messages array of the desired conversation.

    4. Backup, Token Counting, Redaction, and Migration Verification

    4.1 Back Up Before Migrating

    Before cleaning, keep the original file and record its checksum. This way you can return to the raw data if cleaning goes wrong.

    Linux or macOS:

    1. cp conversations.json conversations.backup.json
    2. shasum -a 256 conversations.json > conversations.sha256

    Windows PowerShell:

    1. Copy-Item conversations.json conversations.backup.json
    2. Get-FileHash conversations.json -Algorithm SHA256 | Out-File conversations.sha256

    The backup file contains the same sensitive content, so store it on an encrypted disk or in a controlled directory—not in a public folder of a shared cloud drive.

    4.2 Token Counting

    Token counts determine whether the migrated content fits within the target model’s context window. The following function uses tiktoken when available; otherwise it falls back to a rough character-based estimate for scale assessment only:

    1. import json
    2. import sys
    3. def estimate_tokens(text):
    4. try:
    5. import tiktoken
    6. except ImportError:
    7. return max(1, len(text) // 2) # Rough estimate, used when tiktoken is not installed
    8. enc = tiktoken.get_encoding("o200k_base")
    9. return len(enc.encode(text))
    10. def count_tokens(path):
    11. with open(path, "r", encoding="utf-8") as f:
    12. data = json.load(f)
    13. for conv in data:
    14. total = sum(estimate_tokens(m["content"]) for m in conv["messages"])
    15. print(f"{conv['title']}: ~{total} tokens, {len(conv['messages'])} messages")
    16. if __name__ == "__main__":
    17. count_tokens(sys.argv[1])

    Estimates are only for judging scale. Before the actual migration, verify with the target platform’s tokenizer or the usage data returned by its API.

    4.3 Redaction

    The cleaned file may still contain sensitive information. The following rules handle common formats but cannot cover names, addresses, or internal company codenames:

    1. import json
    2. import re
    3. import sys
    4. REDACT_RULES = [
    5. (re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"), "[EMAIL]"),
    6. (re.compile(r"(?<!\d)1[3-9]\d{9}(?!\d)"), "[PHONE]"),
    7. (re.compile(r"(?<!\d)\d{17}[\dXx](?!\d)"), "[ID NUMBER]"),
    8. (re.compile(r"\b(?:sk|pk|ak)-[A-Za-z0-9_-]{16,}\b"), "[API KEY]"),
    9. ]
    10. def redact(text):
    11. for pattern, label in REDACT_RULES:
    12. text = pattern.sub(label, text)
    13. return text
    14. def redact_file(src, dst):
    15. with open(src, "r", encoding="utf-8") as f:
    16. data = json.load(f)
    17. for conv in data:
    18. for m in conv["messages"]:
    19. m["content"] = redact(m["content"])
    20. with open(dst, "w", encoding="utf-8") as f:
    21. json.dump(data, f, ensure_ascii=False, indent=2)
    22. if __name__ == "__main__":
    23. redact_file(sys.argv[1], sys.argv[2])

    Usage:

    1. python redact.py cleaned.json cleaned_redacted.json

    The redaction script is only a first-pass filter. Before uploading, still perform manual spot checks, focusing on names, company names, customer names, addresses, and internal links.

    4.4 Spot Checks Before Migration

    1. Randomly sample three to five conversations and verify each message against the original export for completeness.
    2. Check that the role sequence is normal. The script flags consecutive identical roles; if there are many such warnings, investigate branch handling or field mapping.
    3. Compare total message counts with the effective messages in the original file. Large discrepancies may indicate dropped branches.
    4. Confirm there is no empty content or garbled text. Garbled characters usually mean the original file is not UTF-8 encoded.
    5. Confirm the redacted file contains no residual accounts, keys, or personal information.

    5. Troubleshooting Checklist

    Symptom Possible cause Resolution
    Exported file is empty or abnormally sized Export incomplete or download interrupted Re-export; verify file size and timestamp
    File is an old export A file with the same name already exists in Downloads Confirm the old file is backed up before deleting, then re-download
    Temporary link returns an error Link expired Regenerate the link and open it promptly
    Browser does not start downloading System browser blocks non-standard downloads Retry with Chrome or Safari
    iOS file cannot be saved App lacks file access permission Check permissions in system settings, then re-download
    Android download fails Missing storage write permission Grant the permission and retry
    JSON parse failure reported File truncated or corrupted Re-export; do not manually edit the original file
    No messages extracted Top-level structure or field names differ from the mapping table Open the file, inspect field names, and adjust the script accordingly
    Message count is significantly low current_node points to a short branch, or branches were dropped Confirm the current branch is the one you need; switch to full-branch traversal if necessary
    Non-ASCII text appears garbled File encoding is not UTF-8 Open with a UTF-8-capable editor or use an encoding conversion tool
    Sensitive data remains after redaction Regex rules do not cover that format Add rules and perform manual spot checks

    If you cannot resolve an issue, keep the original backup and error output, then work through the table item by item. Never modify or overwrite the original export file without a backup.

    After migration, delete local temporary files and intermediate results, keeping only the final redacted version. Store the original backup according to your own data retention requirements, and delete it yourself when it is no longer needed.