Guide to Migrating Conversations and Building Self-Hosted Sessions Under LLM Usage Limits

    This guide explains how to migrate conversation history from large language model platforms to a self-hosted system when facing usage limits. It covers identifying limit types, ensuring compliance during data export, cleaning and standardizing exported data, and provides Python code for data normalization.

    1. Identifying Usage Limit Types and Compliance Boundaries

    Large language model platforms typically impose three types of usage limits. The first is time-based limits, where long conversations are frozen after a period of inactivity. The second is single-input length limits, making it difficult to submit long documents or code at once. The third is daily quota limits, where the service pauses until the quota refreshes once the daily call count is exhausted.

    For users who rely on long contexts, the biggest loss is often the disconnection of historical context. The platform may still allow viewing old chat records but cannot continue reasoning based on them. The goal of migration is to make historical data usable again in your own system.

    The prerequisite for migration is legal export. Before proceeding, confirm the following checklist item by item:

    • Read the terms of service regarding export, storage, and reuse. If the terms prohibit export, stop the operation and use the platform’s official data export feature or communicate with the platform for authorization.
    • Only export data you have the right to process. If the conversation contains others’ personal information, obtain their consent first, or retain only the minimum fields directly related to the task.
    • Record the authorization basis, including export time, data scope, purpose, and person in charge. This record is for post-audit purposes.
    • Store exported files on encrypted disks or access-controlled storage, and set a retention period. Delete them upon expiration and keep a deletion record. The deletion record should only include operation time, object identifier, and operator, without writing the conversation text.
    • Replace or delete names, phone numbers, addresses, customer data, and internal keys immediately after export.
    • Do not bulk import unauthorized third-party content into other services.

    Self-hosted systems must also fulfill personal information protection obligations. Comply with applicable data protection laws (such as GDPR, CCPA, or local equivalents). When services involve users across borders, verify the data transfer and privacy rules of the corresponding regions.

    2. Cleaning and Standardizing Exported Data

    The export formats differ significantly across platforms. JSON usually retains nested structures, CSV often flattens multi-turn conversations into a single row, and timestamp formats are not unified. You need to establish a field mapping table before importing.

    Original Field (Example) Standard Field Processing Rule
    conversation_id / session_id conversation_id If missing, record as unknown and write to the error log
    role / sender role Standardize to user, assistant; system prompts are filtered separately
    content / text content Remove leading and trailing whitespace; discard if empty
    create_time / timestamp created_at Standardize to UTC time, ISO 8601 format
    None token_count Calculated using the target model’s tokenizer during import
    None status Default to complete; mark interrupted streaming responses as partial

    There are three rules during cleaning. Empty messages and system prompts do not carry valid information and should be filtered out. Messages with unknown roles require manual confirmation of their meaning before deciding whether to keep them. Messages with missing timestamps are retained and flagged to avoid sorting errors.

    The following code only processes single-session JSON files and Unix second-level timestamps. It relies only on the Python standard library and is suitable for Python 3.9 and above. CSV, multi-session files, and ISO timestamps require separate parsing functions. Error messages only record line numbers, not the text, to prevent log leakage of content.

    1. import json
    2. from dataclasses import dataclass
    3. from datetime import datetime, timezone
    4. from typing import Optional
    5. ROLE_MAP = {"user": "user", "human": "user",
    6. "assistant": "assistant", "bot": "assistant", "ai": "assistant"}
    7. @dataclass
    8. class Message:
    9. conversation_id: str
    10. role: str
    11. content: str
    12. created_at: Optional[str]
    13. def to_iso_utc(ts) -> Optional[str]:
    14. # Only handles Unix second-level timestamps; other formats need additional parsing based on the export file
    15. if isinstance(ts, (int, float)):
    16. return datetime.fromtimestamp(ts, tz=timezone.utc).isoformat()
    17. return None
    18. def normalize_export(path: str) -> tuple[list[Message], list[str]]:
    19. with open(path, "r", encoding="utf-8") as f:
    20. data = json.load(f)
    21. conv_id = str(data.get("conversation_id", "unknown"))
    22. messages, errors = [], []
    23. for i, item in enumerate(data.get("messages", [])):
    24. role = ROLE_MAP.get(str(item.get("role", "")).strip().lower())
    25. content = str(item.get("content", "")).strip()
    26. if role is None:
    27. errors.append(f"Item {i} has an unknown role or is a system prompt, skipped")
    28. continue
    29. if not content:
    30. continue
    31. messages.append(Message(conv_id, role, content,
    32. to_iso_utc(item.get("timestamp"))))
    33. return messages, errors

    Overly long conversations need to be sliced. The slicing boundary can be set at points where the topic clearly changes, or sliced every certain number of turns, such as every 40 turns. Adjacent slices should retain 2 overlapping turns.