Migrating LLM Conversations: A Practical Guide to Exporting, Cleaning, and Resuming

    When LLM platforms impose limits on context length or interaction frequency, ongoing tasks can be interrupted. This guide provides a practical approach to migrating your existing conversation context to a new environment. Learn how to export your conversation history, clean the data to fit target API formats, and seamlessly resume your work without violating platform terms of service.

    Migrating LLM Conversations: A Practical Guide to Exporting, Cleaning, and Resuming

    1. Background and Boundaries

    To manage compute costs, LLM platforms often adjust conversation frequency, context length, or daily interaction limits on web and mobile clients. When developers or office users hit these limits during code generation, copywriting, or multi-step reasoning, their ongoing tasks get interrupted.

    Conversation migration aims to carry existing context into an available environment. The model itself does not save your conversation; it only sees what is sent in the request. Therefore, the essence of migration is: exporting the history, formatting it for the target interface, and passing the key context to the model in the first request of the new session.

    This guide helps you continue your legitimate work. It does not involve bypassing platform access controls or quota mechanisms. Only export conversations under your own account and comply with the platform’s Terms of Service.

    2. Pre-Export Preparation

    Before starting, complete three checks:

    1. Confirm Permissions: Only export sessions under your own account. For team-shared sessions, obtain consent from relevant members and administrators.
    2. Read Terms: Review the platform’s user agreement and data export instructions. If the platform explicitly prohibits scraping or automated export, use official features or manually copy the necessary content.
    3. Backup Original File: Keep a copy of the exported raw file. If data cleaning goes wrong later, you can reprocess from the original data.

    3. Web Export

    Most platforms provide a data export feature in the settings page, which can generate a compressed archive containing all conversations. Prioritize this method as the format is most stable.

    If the platform does not offer a single conversation export entry, you can use browser developer tools to inspect network requests:

    1. Open the target conversation page, press F12 to open Developer Tools, and switch to the Network panel.
    2. Filter by Fetch or XHR to only show API requests.
    3. Refresh the page and find the request returning the conversation content, usually containing “conversation”, “session”, or “history” in the path.
    4. View the JSON in the Response tab, confirm the content, right-click to copy the response, and save it as raw_conversation.json.

    Some platforms require auth tokens or return data in pages. In these cases, request each page and merge the messages. Deduplicate by message ID and sort chronologically.

    4. Mobile Export

    Mobile apps are sandboxed, making direct file downloads difficult. The recommended order is:

    1. Look for official export or share functions within the app. Some platforms support exporting conversations as text or Markdown, which is the simplest method.
    2. If only a share link can be generated, open it in a desktop browser and follow the web export method in Section 3.
    3. If capturing on mobile is necessary, Android devices can use Chrome’s remote debugging, and iOS devices can use Safari’s Web Inspector to route the mobile page’s network requests to a desktop.

    Note that many modern pages load content dynamically via XHR, Fetch, or WebSocket. The browser’s “View Page Source” typically only shows the page framework, not the conversation data. Therefore, extract data from network responses rather than relying on source code.

    5. Cleaning Conversation Data

    Exported JSON usually contains many fields unrelated to the conversation, such as device IDs, UI states, rendering parameters, timestamps, and usage statistics. These fields consume token space and may cause target interface errors. The cleaning goal is to produce a messages array containing only role and content.

    Different platforms have different structures. The table below lists common mapping relationships; actual field names depend on your exported file.

    Platform Structure Message List Location Content Field Processing Method
    Top-level contains messages array messages content as string Read directly
    Top-level contains chat_messages chat_messages text or content Map uniformly to content
    content is a block list Same as above Blocks with type as text Concatenate text blocks
    Contains multiple branch replies Restore by parent-child relationship Depends on platform Keep only the current branch

    The following script handles these scenarios. It skips illegal roles and empty content, and truncates from the most recent message backward based on a character budget to ensure the latest context is retained.

    1. import json
    2. import sys
    3. ALLOWED_ROLES = {"system", "user", "assistant"}
    4. # Adjust candidate field names according to actual exported file
    5. MESSAGE_KEYS = ["messages", "chat_messages", "history"]
    6. def find_messages(raw):
    7. if isinstance(raw, list):
    8. return raw
    9. if isinstance(raw, dict):
    10. for key in MESSAGE_KEYS:
    11. if isinstance(raw.get(key), list):
    12. return raw[key]
    13. raise ValueError("Message list not found, please adjust MESSAGE_KEYS according to the exported file")
    14. def normalize_content(content):
    15. if isinstance(content, str):
    16. return content.strip()
    17. if isinstance(content, list):
    18. parts = []
    19. for block in content:
    20. if isinstance(block, str):
    21. parts.append(block)
    22. elif isinstance(block, dict) and block.get("type") == "text":
    23. parts.append(str(block.get("text", "")))
    24. return "\n".join(p for p in parts if p).strip()
    25. return ""
    26. def clean(raw_path, out_path, max_chars=20000):
    27. try:
    28. with open(raw_path, "r", encoding="utf-8") as f:
    29. raw = json.load(f)
    30. except (OSError, json.JSONDecodeError) as e:
    31. sys.exit(f"Read failed: {e}")
    32. cleaned = []
    33. for msg in find_messages(raw):
    34. if not isinstance(msg, dict):
    35. continue
    36. role = msg.get("role")
    37. if role not in ALLOWED_ROLES:
    38. continue
    39. content = normalize_content(msg.get("content", msg.get("text")))
    40. if content:
    41. cleaned.append({"role": role, "content": content})
    42. # Take from the newest message backward until the character budget is reached
    43. kept, total = [], 0
    44. for msg in reversed(cleaned):
    45. size = len(msg["content"])
    46. if kept and total + size > max_chars:
    47. break
    48. kept.append(msg)
    49. total += size
    50. kept.reverse()
    51. with open(out_path, "w", encoding="utf-8") as f:
    52. json.dump(kept, f, ensure_ascii=False, indent=2)
    53. print(f"Cleaning completed: {len(cleaned)} original valid messages, {len(kept)} kept.")
    54. if __name__ == "__main__":
    55. clean("raw_conversation.json", "cleaned_context.json")

    The character budget is only a rough estimate. Chinese text typically corresponds to one or two tokens per character, while code and English have different ratios. Before formal use, count actual tokens using the target model’s tokenizer and reserve space for new prompts and model responses.

    6. Importing to Other Tools or Custom APIs

    1. Importing to other AI applications

    Many AI apps support file uploads or pasting long text. The processing methods are as follows:

    • If the app supports file upload, directly upload the cleaned JSON and state in the first message: “Here is the previous conversation history, please continue working based on this.”
    • If only text can be pasted, convert the JSON to readable Markdown, arrange by turns, and label roles.
    • If the record exceeds the target app’s context window, first have the original model or yourself write a summary listing project goals, completed items, key code snippets, and unresolved issues, then submit it along with the most recent rounds of original text.

    2. Resuming via custom API

    For scenarios requiring more control, use your own client to call the model API. Key points are as follows:

    • The client must construct the messages array itself and send historical messages in each request. The model will not automatically read the exported JSON file.
    • Whether the target model can process this content depends on its context window, the interface’s message format, and your quota. Different models may perform differently, so conduct comparison tests after migration.
    • Before using third-party API aggregation platforms, verify their terms of service, API key permission scope, data retention duration, and data cross-border transfer rules.
    • API keys should be placed in environment variables or a key management service, not hardcoded in scripts or committed to code repositories.
    • Check the aggregation platform’s call limits and billing rules. The purpose of migration is to continue work within legally authorized quotas, not to bypass the original platform’s limits.

    7. Verification and Rollback After Migration

    After migration, do not jump directly into formal tasks. Perform the following checks first:

    1. Verify Quantity: Compare the number of original valid messages with the cleaned messages to ensure nothing was accidentally lost.
    2. Spot-check Content: Randomly select a few key conversation rounds to check if code, numbers, and proper nouns are intact.
    3. Test Resumption: Ask a small question that relies only on historical context to see if the model answers correctly.
    4. Keep Rollback Path: If the new environment performs unstably, keep the original export file and summary, switch to another model, or manually continue.

    After a long conversation migration, new interactions will continue to grow the context. It is recommended to write a system prompt at the migration node explaining the current goal, established conventions, and next step tasks. This helps the model enter the state faster and facilitates manual verification.

    8. Checklist

    • The conversation belongs to your own account, or authorization has been obtained
    • Platform terms have been read, and official export functions are prioritized
    • Original files have been backed up
    • Only role and content are retained after cleaning, and illegal roles and empty content are filtered
    • Tokens have been counted according to the target model, and excess parts have been summarized or truncated
    • Sensitive information has been desensitized, and data retention and cross-border transfer rules of third-party services have been confirmed
    • API keys are not written in code, and permissions are configured following the principle of least privilege
    • Quantity verification, content spot-check, and resumption test have been completed after migration

    Conversation migration is not a one-click operation. The four stages—export, clean, import, and verify—all require verification, and each step should retain a rollback version. By following the steps in this guide, you can stably carry your existing context into a new working environment compliantly.