LLM API Integration and Conversation Migration After Free Quotas Run Out

    This article explains how to keep LLM chat workflows stable when free usage limits change. It covers API fundamentals and token-based billing, secure API key management, exporting and converting chat history, context-window trimming with sliding windows or summaries, sample Python code, and practices for cost control, reliability, compliance, and data protection.

    1. Background: Why Free Chat Quotas Tighten

    Online LLM chat services often use free quotas to attract users. Compute costs, concurrency load, and risk-control policies all affect quota settings, and providers may change the rules at any time. Common limits fall into three categories: the maximum length of a single conversation, the maximum input size per request, and the number of calls allowed per day or per time window.

    If conversation records from long-term projects are stored only in a web page or client, they become difficult to continue once the rules change. Therefore, understanding how to call APIs and keeping key data under your own control are the foundation for building stable applications.

    2. First, Understand the API: What It Is and How Billing Works

    An API (Application Programming Interface) is an agreed way for programs to call each other. A client sends a structured request, and the server returns a structured result. For LLM services, requests usually include the model name, a message list, and generation parameters, while the response contains the text generated by the model.

    Web or client login relies on an account and verification code, while API calls use an API key for identity verification. The key is an access credential. Once leaked, others can consume your quota, so it must be kept secure.

    Billing is usually based on tokens. A token is the smallest unit used by the model to split text. One Chinese character or one English word may correspond to one or several tokens. Costs are generally divided into input tokens and output tokens, and the output unit price is often higher. Actual unit prices depend on the official pricing page of the selected service; no numeric values are listed here.

    3. Preparation Before Integration

    1. Complete account registration and identity verification, and enable pay-as-you-go billing as required by the provider.
    2. Create a separate key for each application. This way, if one application behaves abnormally, you only need to disable the corresponding key without affecting other services.
    3. Set budget caps and usage alerts to avoid excess charges caused by abnormal calls.
    4. Store keys in environment variables or a secret management service. Plaintext keys should not appear in code repositories, logs, or frontend pages.

    4. Migrating Historical Conversations

    Migrating historical conversations to a new API requires three steps: export, cleaning, and conversion.

    • Export: Most chat products provide an export function, usually in JSON or Markdown format. Prefer JSON because it is more structured and easier for programs to process.
    • Cleaning: Remove noise such as duplicate messages, interface提示 text, and attachment placeholders, keeping only roles and body content.
    • Conversion: Organize the records into a messages list. Each message contains two fields: role (one of system, user, or assistant) and content.

    Long conversations often exceed the model’s context window and need to be trimmed. Two common strategies are:

    • Sliding window: Keep only the most recent N turns. This is simple to implement and predictable, but early information is lost.
    • Summary compression: Ask the model to compress early conversations into a summary and place it in a system message. This preserves continuity but adds the cost of an extra call.

    In real projects, the two approaches are often combined. The system prompt is kept separately, and historical messages are truncated from newest to oldest according to a character budget.

    5. Example Code

    The following code shows the basic flow of reading configuration from environment variables and sending a chat request. The service URL and model name need to be replaced with the actual values from the selected service documentation.

    1. import os
    2. import requests
    3. API_BASE = os.environ["LLM_API_BASE"] # Service base URL; refer to the provider's documentation
    4. API_KEY = os.environ["LLM_API_KEY"] # Read the key only from environment variables
    5. def chat(messages, model_name, timeout=60):
    6. headers = {
    7. "Authorization": f"Bearer {API_KEY}",
    8. "Content-Type": "application/json",
    9. }
    10. payload = {"model": model_name, "messages": messages}
    11. resp = requests.post(
    12. f"{API_BASE}/chat/completions",
    13. json=payload,
    14. headers=headers,
    15. timeout=timeout,
    16. )
    17. resp.raise_for_status()
    18. return resp.json()["choices"][0]["message"]["content"]

    The following code reads an exported history file and keeps the most recent messages according to a character budget.

    1. import json
    2. def load_history(path, max_chars=40000):
    3. with open(path, encoding="utf-8") as f:
    4. raw = json.load(f)
    5. # Filter messages with valid roles
    6. messages = [m for m in raw if m.get("role") in ("system", "user", "assistant")]
    7. # Accumulate from the newest message backward and stop when the budget is exceeded
    8. kept, total = [], 0
    9. for m in reversed(messages):
    10. total += len(m.get("content", ""))
    11. if total > max_chars:
    12. break
    13. kept.append(m)
    14. return list(reversed(kept))

    When calling, load the history first, append the new user input to the end of the list, and then pass it to the chat function. If the history contains a system prompt, ensure that it is at the beginning of the list and is not trimmed away.

    6. Cost and Stability

    • Cost estimation: Before launch, use real samples to calculate average input and output lengths, then multiply by the unit price to estimate daily cost. Compare the estimate with the bill regularly.
    • Retry mechanism: When encountering rate limits or temporary failures, use exponential backoff. For example, wait 1, 2, and 4 seconds before retrying, up to three times. Infinite retries amplify failures and costs.
    • Timeout settings: Set an explicit timeout for each request to avoid blocking threads for a long time.
    • Result caching: Cache identical inputs locally to reduce repeated calls and repeated billing.
    • Observability: Record the latency, token usage, and error code of each call to help troubleshoot. Logs must not contain keys or sensitive user information.

    7. Compliance and Data Security

    • Follow the provider’s terms of use. Do not share keys with others or embed them in frontend code; otherwise, the key will be exposed to all visitors.
    • Conversation content may contain personal information. Desensitize it before storage, and define retention periods and deletion mechanisms.
    • When enterprise or customer data is involved, confirm the data processing agreement first and clarify whether the provider may use the data for other purposes.

    8. Summary

    After free quotas change, a stable approach is to keep conversation data and calling capability under your own control. Key steps include understanding token billing and key authentication, standardizing key management and budget settings, handling long conversations with sliding windows or summary compression, and ensuring service quality through retries, timeouts, caching, and logs.