How to Export AI Chat Logs, Clean Them into a Minimal Message List, and Continue the Conversation via an Authorized API
Learn how to export your own AI chat logs within authorized boundaries, redact sensitive data, clean the JSON into a minimal message list, manage context length with summarization, and resume the conversation through an official or authorized chat completions API.
1. Define the Boundaries First: What You Can and Cannot Do
Before migrating a conversation, you need to understand where the boundaries lie. You may export conversations from your own account for personal backup, knowledge organization, or to continue working in another tool. That is simply managing your own data.
Certain practices should be avoided. Scraping other people’s conversations, decrypting a third-party app’s encrypted traffic, or bypassing a platform’s rate limits or automation detection may violate terms of service and can expose other people’s privacy. This article only covers exporting your own conversations through official features and continuing them via official or authorized APIs.
There are three risks to keep in mind before migrating. First, a platform’s terms of service may prohibit exporting or restrict how the data can be used, so read the relevant terms first. Second, conversations may contain sensitive content such as account details, API keys, phone numbers, or internal file paths; exported files should be redacted before being stored or transferred. Third, the export may fail or return only partial data, so keep a copy of the original conversation to avoid losing content due to cleaning errors.
2. The Overall Approach: Export, Clean, Restore
Conversation migration can be broken down into three steps.
Step 1: Export. Use the platform’s built-in export feature, or inspect the response data of your own conversation in the browser’s developer tools, and save the complete chat log as a local file.
Step 2: Clean. The exported file is usually a large JSON object that contains, besides the conversation content, UI state, timestamps, cache identifiers, and other fields. These fields are useful for rendering the web page but useless for continuing the chat. The goal of cleaning is to extract the role and text content, producing an array that contains only the message sequence.
Step 3: Restore. Feed the cleaned message array into a new conversation environment in the format the target platform requires. If the platform supports file uploads, you can upload it directly; if you are using an API, place the message array in the messages field of the request body.
The following sections walk through each step.
3. Exporting the Conversation: Prefer Official Features
Scenario A: Desktop Web
On the web, most apps load conversation content through API requests. You can inspect the response data of your own conversation using the browser’s developer tools:
- Open the platform’s conversation list and locate the conversation you want to export.
- Press F12 to open developer tools, switch to the Network tab, and enable Preserve log so request records are not cleared when the page refreshes.
- Click into the target conversation. In the request list, look for requests whose names contain “message”, “conversation”, or “history”. Click one and inspect the returned JSON under Response or Preview.
- After confirming the returned content is indeed your own conversation, save the response as a local
.jsonfile. Perform the redaction described in the next section before saving.
Some apps push messages over WebSocket. This traffic does not appear among regular XHR requests; switch to the WS tab to inspect it.
Scenario B: Mobile
Mobile devices generally lack developer tools, so the most reliable approach is the app’s built-in export feature. Some apps offer an “Export chat history” or “Share” option in their settings menu. These exported files are usually well-organized with clean fields and should be your first choice.
If the app has no export feature, you can copy message text on your phone. However, this loses role identifiers and timestamps, making later cleaning and restoration much harder.
Once you have the file on your phone, it is best to do the cleaning on a computer. When transferring the file, use a method you control, such as a USB cable or an encrypted personal cloud drive. Do not share conversation files containing sensitive information via public links.
This article does not cover configuring proxies or installing packet-capture certificates to decrypt mobile app traffic. Such practices may touch on third-party apps’ security mechanisms and terms of service, and a misconfigured certificate introduces additional security risks.
4. Privacy Redaction Before Exporting
Chat logs often contain fairly sensitive information. You may have pasted code, configuration files, database connection strings, API keys, phone numbers, email addresses, or internal company paths into the conversation. All of this can be exposed during export and transfer.
Therefore, before using the file to continue a chat, uploading it to another platform, or sending it to a third-party API, you should redact it. Redaction can be done in two passes. The first is a manual review: scroll through the conversation and identify obviously sensitive content. The second is a scripted batch replacement. Here is a simple example:
import rePATTERNS = [(re.compile(r"sk-[A-Za-z0-9]{16,}"), "[API_KEY]"),(re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+"), "[EMAIL]"),(re.compile(r"1[3-9]\d{9}"), "[PHONE]"),(re.compile(r"(?i)(password|passwd|secret|token)\s*[:=]\s*\S+"), r"\1=[REDACTED]"),]def redact(text: str) -> str:for pattern, replacement in PATTERNS:text = pattern.sub(replacement, text)return text
This script only covers common formats. It cannot identify all sensitive content, so manual review remains essential. Save the redacted output as a new file, and keep the original in a locally encrypted location.
5. Cleaning the JSON: Extracting the Right Message Path
The structure of the exported JSON varies by platform. Below is a common structural example. Field names are for reference only; the actual names depend on your exported file.
{"version": "1.0","sessionMeta": { "...": "..." },"conversation": {"id": "conversation ID","title": "conversation title","messages": [{"role": "user","content": [{ "type": "text", "text": "actual conversation content" }],"createTime": 1720000000}]}}
The message array lives under conversation.messages. When cleaning, take this path rather than a top-level data.messages. Cleaning has three goals.
First, remove metadata. Conversation IDs, message IDs, and timestamps are not helpful for continuing the chat and can be deleted. If you later want timeline analysis, you may keep timestamps, but they are usually unnecessary for resuming a conversation.
Second, extract text content. The content field may be a string or an array containing multiple segments. You only need the parts whose type is text. If code exists as a separate type, add handling logic for it based on the actual field names.
Third, preserve the correct roles. The three roles system, user, and assistant must be distinguished clearly, or the model will misinterpret the conversation structure.
The following script cleans according to these rules, with file checks and exception handling included:
import jsonALLOWED_ROLES = {"system", "user", "assistant"}def clean_conversation(raw_path: str, out_path: str) -> list:with open(raw_path, "r", encoding="utf-8") as f:data = json.load(f)conversation = data.get("conversation") or {}raw_messages = conversation.get("messages") or []if not isinstance(raw_messages, list):raise ValueError("conversation.messages is not an array; check the export file structure")clean = []for msg in raw_messages:if not isinstance(msg, dict):continuerole = msg.get("role")if role not in ALLOWED_ROLES:continuecontent = msg.get("content")texts = []if isinstance(content, str):texts.append(content)elif isinstance(content, list):for item in content:if isinstance(item, dict) and item.get("type") == "text" and item.get("text"):texts.append(item["text"])if texts:clean.append({"role": role, "content": "\n".join(texts)})print(f"Extracted {len(clean)} valid messages")with open(out_path, "w", encoding="utf-8") as f:json.dump(clean, f, ensure_ascii=False, indent=2)return cleanif __name__ == "__main__":clean_conversation("raw_export.json", "clean_data.json")
If the script reports zero messages, first check the top-level structure of the exported file, confirm the real path of the message array, and then adjust the lookup statements in the script.
6. Controlling Context Length: Summarize Instead of Importing Everything
Every model has a maximum context window, which is the total number of tokens a single request can hold. A token is the basic unit of text the model processes; it may be a character, part of a word, or several letters. As a rough guide, one Chinese character corresponds to about one to two tokens, while English averages about one token per four characters. The exact numbers depend on the target model’s tokenizer, so use the provider’s counting tool when estimating.
If the original conversation is very long, importing it in full may exceed the window. The overflow is typically truncated, with the earliest messages dropped first. This is the main reason a new platform’s answers seem to “not remember” earlier context.
The recommended approach is to keep three kinds of content. First, the system prompt, which defines the assistant’s role and rules and should be preserved in full. Second, the most recent turns — usually the last ten to twenty messages — because they are most relevant to the current question. Third, a summary of the earlier history: consolidate the conclusions reached, decisions made, and key constraints into a paragraph placed at the beginning of the message list.
The summary can be generated by a model or written by hand. A handwritten summary is usually more reliable, because you can judge which conclusions are still valid. It should cover the goal, completed work, unresolved problems, and important constraints.
The function below implements a simple truncation strategy that keeps all system messages plus the most recent non-system messages:
def trim_history(messages: list, keep_last: int = 20) -> list:system_msgs = [m for m in messages if m["role"] == "system"]others = [m for m in messages if m["role"] != "system"]return system_msgs + others[-keep_last:]
This function has one limitation. After truncation, the first message in the list may be an assistant reply rather than a user question, which some models are sensitive to. If you run into this, add a sentence of background context to the summary, or adjust the truncation point so it lands on a user message.
7. Resuming the Chat: Restoring the Conversation via an Official or Authorized API
After cleaning and redaction, you can continue the conversation through an API. The API here should be one officially provided by the platform, or one from a provider you have signed up with and trust.
Before choosing a provider, verify a few things: whether the provider publishes a privacy policy and data retention period, whether your conversation content will be used for training, whether data deletion is supported, and whether pricing and quotas are clear. Third-party relay services handle your entire conversation content and carry higher risk than using an official API directly, so evaluate them carefully before use.
Many providers offer chat completions endpoints compatible with the OpenAI API format. The example below follows that format; you need to replace the base URL and model name with those of your own provider. The API key must be placed in an environment variable — never hardcoded or committed to a code repository.
import jsonimport osimport timeimport requestsAPI_BASE = os.environ["LLM_API_BASE"] # e.g. https://your-provider.example.com/v1API_KEY = os.environ["LLM_API_KEY"] # read from environment variable; never hardcodeMODEL = os.environ.get("LLM_MODEL", "your-model-name")TIMEOUT = 60MAX_RETRIES = 3def load_history(path: str) -> list:with open(path, "r", encoding="utf-8") as f:messages = json.load(f)if not isinstance(messages, list):raise ValueError("The cleaned file should be a message array")return messagesdef trim_history(messages: list, keep_last: int = 20) -> list:system_msgs = [m for m in messages if m["role"] == "system"]others = [m for m in messages if m["role"] != "system"]return system_msgs + others[-keep_last:]def ask(history: list, question: str) -> str:payload = {"model": MODEL,"messages": history + [{"role": "user", "content": question}],}headers = {"Authorization": f"Bearer {API_KEY}","Content-Type": "application/json",}url = f"{API_BASE}/chat/completions"for attempt in range(MAX_RETRIES):try:resp = requests.post(url, headers=headers, json=payload, timeout=TIMEOUT)except requests.RequestException:if attempt == MAX_RETRIES - 1:raisetime.sleep(2 ** attempt)continueif resp.status_code == 429:# Wait and retry when rate-limited; do not bypass limits with concurrent requeststime.sleep(2 ** attempt)continueif resp.status_code == 401:raise RuntimeError("Authentication failed; check whether LLM_API_KEY is correct")if resp.status_code == 400:raise RuntimeError(f"Bad request parameters, possibly context overflow: {resp.text[:300]}")resp.raise_for_status()data = resp.json()return data["choices"][0]["message"]["content"]raise RuntimeError("Still failing after multiple retries; please try again later")if __name__ == "__main__":history = trim_history(load_history("clean_data.json"), keep_last=20)answer = ask(history, "Based on the discussion above, summarize the next action plan as a list.")print(answer)
A few points in this code deserve attention. The request timeout is set to 60 seconds to prevent the program from waiting indefinitely. When rate-limited, the program retries with exponential backoff and does not send concurrent requests to bypass the limit. When a 400 status is returned, the program hints that the cause may be context overflow, in which case you should go back to the summarization step and reduce the number of history messages.
If your provider’s endpoint path or response structure differs from the example, adjust the code according to the relevant API documentation.
