A Practical Guide to Pay-as-You-Go LLM API Access and Conversation Migration

    This guide explains how to move from limited free-tier LLM usage to pay-as-you-go API access. It covers common quota limits, API billing concepts, cost estimation, context management for long conversations, exporting and migrating chat history, and a standard-library client example with retry handling.

    1. Background: Typical Symptoms of Limited Free Quotas

    Hosted LLM services usually provide free quotas to individual users for evaluation and light use. When usage frequency rises, common limits include the following three types:

    1. Session length limits: After a conversation accumulates to a certain size, the server no longer allows additional content, or it cleans up sessions that have been inactive for a long time.
    2. Single-input limits: When submitted text exceeds a length limit, it must be split or compressed before sending.
    3. Call frequency limits: Daily or per-minute request counts and token usage are constrained. Once the limit is reached, the service returns a rate-limiting response.

    These limits are essentially resource quota management. Providers need to control compute costs and ensure fair resource allocation, while users need to organize requests reasonably within their quotas. For people who rely on models for writing, coding, or organizing materials over time, understanding these mechanisms is more valuable than looking for temporary workarounds.

    2. Basic Concepts of Pay-as-You-Go APIs

    An API (Application Programming Interface) is a standard way for programs to communicate with a service. Unlike web pages or client applications, an API exchanges data in requests and responses, making it easy to integrate into scripts, tools, or custom systems.

    Using a pay-as-you-go API usually involves three elements:

    • Access credential (API Key): Identifies the caller and acts as the key to calling permissions.
    • Billing unit (Token): Text processed by the model is split into tokens, with input and output metered separately.
    • Account balance or usage cap: Prepay or set a cap, and deduct usage after each call.

    Tokenization rules vary by model and tokenizer. For Chinese text, token count is related to character count, but the ratio is not fixed. Use the usage fields returned by the server as the source of truth.

    3. Cost Estimation

    The cost of a single call can be approximated with the following formula:

    Single-call cost = input tokens × input price + output tokens × output price

    Prices should follow the provider’s published price list. When exact counts are unavailable, you can make a rough estimate based on character count and record usage data from each response to calibrate the estimate over time.

    1. def estimate_cost(input_tokens, output_tokens, price_in, price_out):
    2. """The pricing unit must match the provider's price list."""
    3. return input_tokens * price_in + output_tokens * price_out

    One important point: models usually do not retain session state, so each request must carry the full message history. The longer the conversation, the larger the single input, and total cost grows cumulatively. Therefore, controlling the size of message history is the most direct way to reduce cost.

    4. Context Management for Long Conversations

    Because the client must resend historical messages with each request, three common management strategies are:

    1. Sliding window: Keep only the most recent turns. This is simple to implement, but early information is lost.
    2. Summary compression: Ask the model to summarize earlier conversation and keep the summary as system-level context.
    3. Retrieval recall: Write historical messages into a vector index or full-text index and retrieve only the fragments relevant to the current question each turn.

    Most scenarios benefit from a combination: recent messages are kept as-is, mid-term content is compressed into summaries, and older content is retrieved on demand. The following function implements a simple character-based sliding window; character count serves as a rough proxy for token count.

    1. def trim_history(messages, max_chars=20000):
    2. """Keep all system messages and retain recent messages backward until the character limit is reached."""
    3. system_msgs = [m for m in messages if m["role"] == "system"]
    4. other_msgs = [m for m in messages if m["role"] != "system"]
    5. kept, total = [], 0
    6. for msg in reversed(other_msgs):
    7. total += len(msg["content"])
    8. if total > max_chars:
    9. break
    10. kept.append(msg)
    11. return system_msgs + list(reversed(kept))

    There is a practical issue here: simple truncation may cut off key information such as persona settings or project conventions. System messages should therefore be kept separately, and configuration-like content is better placed in system messages or summaries rather than ordinary conversation turns.

    5. Exporting and Migrating Historical Conversations

    Before migration, export the conversation to a structured file. A JSON structure with three core fields—role, content, and timestamp—is recommended for reuse across systems.

    1. {
    2. "session_id": "novel-2026-001",
    3. "exported_at": "2026-11-24T23:10:09+00:00",
    4. "messages": [
    5. {"role": "system", "content": "You are an editor assisting with long-form novel writing."},
    6. {"role": "user", "content": "Please review the character setup in Chapter 1."},
    7. {"role": "assistant", "content": "The main characters in Chapter 1 include..."}
    8. ]
    9. }

    Before exporting, check whether the conversation contains personal privacy, account information, or business secrets, and redact it. Treat the exported file itself as sensitive data and do not upload it to public locations.

    6. Client Integration Example

    The following example uses only the standard library. It wraps a request function with backoff retry and demonstrates how to load a historical conversation before continuing it. The endpoint URL, model name, and response structure must follow the official documentation of the service you use.

    1. import json
    2. import os
    3. import time
    4. import urllib.error
    5. import urllib.request
    6. API_BASE_URL = os.environ["LLM_API_BASE_URL"]
    7. API_KEY = os.environ["LLM_API_KEY"]
    8. RETRYABLE_STATUS = {429, 500, 502, 503}
    9. def chat(messages, model, max_retries=3):
    10. payload = json.dumps({"model": model, "messages": messages}).encode("utf-8")
    11. for attempt in range(max_retries):
    12. req = urllib.request.Request(
    13. f"{API_BASE_URL}/chat/completions",
    14. data=payload,
    15. headers={
    16. "Authorization": f"Bearer {API_KEY}",
    17. "Content-Type": "application/json",
    18. },
    19. method="POST",
    20. )
    21. try:
    22. with urllib.request.urlopen(req, timeout=60) as resp:
    23. return json.loads(resp.read().decode("utf-8"))
    24. except urllib.error.HTTPError as e:
    25. if e.code in RETRYABLE_STATUS and attempt < max_retries - 1:
    26. time.sleep(2 ** attempt) # Exponential backoff
    27. continue
    28. raise
    29. raise RuntimeError("Retries exhausted")
    30. def load_session(path):
    31. with open(path, encoding="utf-8") as f:
    32. return json.load(f)["messages"]
    33. def main():
    34. history = trim_history(load_session("session.json"))