Continuing Long Chats via API After Free Quota Cuts: A Complete Migration Guide
Many LLM platforms have tightened their free tiers, breaking long-running projects with inactive-session cutoffs, shorter inputs, and daily usage caps. This guide explains how to move a long chat project to API access: how API billing actually works (including why max_tokens only limits output), how to export, clean, and store chat history locally in SQLite, how to control token usage with sliding windows and retrieval, and how to handle rate limiting and errors. Follow the checklist at the end to keep long-term projects running uninterrupted.
1. What Changes When Free Quotas Shrink
Recently, several LLM platforms have tightened their free policies. The App-side restrictions commonly fall into three categories, each of which disrupts long-term projects:
- Inactive conversations expire: Some platforms stop allowing replies in conversations that have been inactive beyond a certain period (for example, 7 days). If a story-writing project has accumulated hundreds of thousands of characters of context, the earlier content can no longer be used.
- Reduced single-input length: The amount of text you can enter at once is lowered. Long document parsing and large code reviews must be split manually, and relationships between segments are easily lost after splitting.
- Daily limits and “busy” errors: Once you hit the daily conversation cap, the system returns messages like “server busy,” and access usually doesn’t recover until the next day. Developers relying on scheduled tasks will find their pipelines stalled.
Exact numbers depend on each platform’s official announcements. Before making any changes, check at least three things: the free quota, rate limits, and the context window. A change in any of these will affect your parameter settings later.
2. How API Access Differs from the App
An API (Application Programming Interface) is a set of rules that lets different software call each other. When you use the App, the platform identifies you by account and grants free quota. With the API, you get an API Key and pay per token consumed.
| Dimension | App | API Access |
|---|---|---|
| Context storage | Stored by the platform, subject to activity rules | Stored locally; you decide how much to keep |
| Billing | Free quota plus subscription plans | Pay per token, only for what you use |
| Rate limiting | Daily counts, busy errors | Requests per minute, concurrency, daily quotas |
| Best suited for | Casual Q&A, lightweight creation | Long-term projects, scheduled tasks, personal automation |
The API offers three advantages. First, you control conversation context yourself, unaffected by App-side activity rules. Second, costs are predictable, which suits users with fluctuating usage. Third, API calls can be integrated into personal scripts, IDE plugins, or internal systems.
The API has its own limits, though. Platforms typically enforce rate, concurrency, and daily quotas, and exceeding them returns errors. Read the platform’s rate-limiting rules before you start.
3. How Costs Work: max_tokens Only Limits Output
A common misconception is that max_tokens controls total cost. In reality, max_tokens only limits the length of a single model reply. On every request, the entire history you send counts toward input tokens and is billed at the input rate. The longer the conversation, the larger the input per turn.
The cost of a single request can be estimated with this formula:
Cost per request ≈ Input tokens × input price + Output tokens × output price
This formula excludes add-ons like cache reads/writes and tool calls. Always rely on the platform’s billing statement and pricing documentation.
Example: assume an input price of $0.30 per million tokens and an output price of $1.20 per million tokens (for illustration only; check official pricing). If a request carries about 20,000 input tokens and the model replies with about 1,000 output tokens:
- Input cost: 20,000 ÷ 1,000,000 × 0.30 = $0.006
- Output cost: 1,000 ÷ 1,000,000 × 1.20 = $0.0012
- Total: roughly $0.0072
The takeaway: the longer your history, the more input dominates the cost. The key to cost control is limiting the input sent each turn — exactly what the sliding window in Section 6 addresses.
4. API Key and Privacy Security
An API Key is the key to your account; if it leaks, others can spend your quota directly. Follow these rules:
- Store keys in environment variables or a system secrets manager, e.g., reading an environment variable like LLM_API_KEY.
- Never hardcode keys into source code, config files, or commit them to a repository. Scan your repo with tooling before committing to confirm nothing was accidentally included.
- Never paste keys into chat windows or screenshots.
- If you suspect a leak, revoke the old key in the platform console immediately and generate a new one.
Chat history may also contain personal information: phone numbers, ID numbers, home addresses, internal company data. Handle it with these principles:
- Redact before importing — replace sensitive fields with placeholders.
- Encrypt local storage and keep it in a directory not synced to cloud drives.
- Retain the minimum — keep only what’s needed for continuing the chat, and delete the original export files once the project ends.
5. Migrating and Storing Chat History Locally
The goal of migration is to turn in-App conversation history into local data that is readable, searchable, and resumable. Steps:
Step 1 — Export. If the App offers an export feature, prefer the official export. Formats may be JSON, Markdown, or HTML. Before exporting, confirm you have the right to process this data and comply with the platform’s terms of service.
Step 2 — Validate with a small sample. Export and import 5–10 conversations first, checking message counts, roles, chronological order, and content integrity. Only migrate everything after verification. Export formats and permissions vary widely across platforms; this step prevents large-scale rework.
Step 3 — Clean. Normalize encoding to UTF-8, remove empty and duplicate messages, map speaker roles into the three types — system, user, assistant — strip ad text and binary attachments, and preserve timestamps.
Step 4 — Store locally. SQLite is recommended. A table schema could look like:
- conversation_id: conversation identifier
- turn_index: turn number
- role: role
- content: message text
- tokens: estimated token count
- created_at: creation time
- summary_id: ID of the parent summary, empty if none
Step 5 — Assemble the API message array. When sending requests, organize the data in order like this:
[{“role”: “system”, “content”: “Project settings and rules”}, {“role”: “user”, “content”: “…”}, {“role”: “assistant”, “content”: “…”}]
Step 6 — Rollback and validation. Back up the original export files before importing. Use transactions when writing to the database, and verify record counts and file hashes after import. If validation fails, roll the entire batch back to the backup — no partial overwrites.
6. Controlling Tokens with Sliding Windows and Retrieval
The core problem with long conversations is that input keeps growing. A sliding window plus retrieval keeps each turn’s input within a controllable range.
The sliding window approach: keep only the most recent N turns verbatim and compress older content into a rolling summary. Update the summary every K turns and cap its length so the summary itself doesn’t grow unbounded.
The retrieval approach: split historical content into chunks, generate a vector for each chunk, and store them in an index. On each question, fetch only the TopK most relevant chunks into the context.
The two can be combined. Assembly order: system settings, rolling summary, TopK retrieved chunks, most recent N turns verbatim, current question.
Example parameters (tune through testing):
| Parameter | Example Value | Purpose |
|---|---|---|
| N (retained turns) | 10 | Keeps recent conversation coherent |
| Summary cap | 800 tokens | Prevents unbounded summary growth |
| K (summary update interval) | Every 5 turns | Controls summary update frequency |
| TopK | 5 | Limits number of retrieved chunks |
| Similarity threshold | 0.75 | Filters out irrelevant chunks |
| Input budget | 12,000 tokens | Hard cap on input per turn |
| max_tokens | 2,000 | Reserves space for output |
The context window is the model’s total token limit, shared between input and output. When assembling context, first reserve max_tokens for output, then set the input budget, leaving about 10% safety margin since token counts vary by tokenizer. If input exceeds the budget, drop the oldest retrieved chunks first — never truncate the system settings.
7. Rate Limiting and Error Handling
Scheduled tasks suffer most when rate limiting interrupts them. On a 429 status code or concurrency-limit error, use exponential backoff:
- Wait about 1 second on the first retry, then roughly 2s, 4s, 8s, with random jitter to avoid multiple tasks retrying simultaneously.
- If the response includes a Retry-After header, follow its value.
- Retry at most 5 times; beyond that, push the task into a pending queue and log it — don’t wait forever.
400 and 401 errors indicate problems with the request format or the key. Retrying is pointless — fail immediately and stop for manual inspection.
8. Checklist for Continuing the Chat
Execute in the following order. After each step, verify against the checklist before moving on.
- Export. Check: original files backed up; record count matches the conversation count shown in the App.
- Clean. Check: encoding correct; no empty messages; sensitive data redacted.
- Summarize or chunk. Check: each chunk has a title and timestamp; summaries don’t exceed the cap.
- Build the index. Check: vector count equals chunk count; sampled retrieval results are actually relevant.
- Send requests. Check: test with a small sample first; verify input token counts against cost estimates.
- Save results. Check: each turn is written within a transaction, with this turn’s token usage logged.
- Backoff on rate limits. Check: 429 triggers retries; retry count is capped.
- Recover from failures. Check: resume from the last successfully written turn_index; never rewrite completed turns.
Once these steps are done, long-term projects can run continuously on your local setup, no longer interrupted by changes to free quotas.
