Pay-as-You-Go LLM API Usage and Migrating Conversation History: A Practical Guide

    This guide explains why free LLM tiers impose quotas, rate limits, and context length caps, and why pay-as-you-go API access is more reliable for sustained work. It covers API basics, token-based billing, a standard integration workflow, three ways to carry over past conversations, and a Python example with cost-control practices.

    1. Why Free Tiers Have Limits

    Running large language models consumes GPU compute, so providers usually place several constraints on free usage. There are three common types.

    First, total or daily quotas. Providers track calls per account or device. Once a threshold is reached, service pauses until the quota resets the next day.

    Second, concurrency and rate limits. The number of requests or token throughput within a time window is capped. Requests beyond the cap receive a rate-limit error, often shown as a message such as “service busy.”

    Third, context length limits. The model can process only a fixed number of input and output tokens in one request. The longer a conversation runs, the more history must be resubmitted each turn, until it eventually exceeds the context window.

    Free tier quotas change often, and providers revise their policies over time. Relying on free quotas for long-term work is therefore risky. For workloads that need stable access, a more reliable approach is to use a pay-as-you-go API and manage conversation state in your own program or tool.

    2. Basic API Concepts

    An API (Application Programming Interface) is an agreed-upon way for one program to call another. In the LLM context, a chat interface is only a front end. It calls the same API that developers use. Whatever a user types into a web page or app is packaged into an HTTP request and sent to the server. The server then returns the generated text.

    Working with an API generally involves four elements.

    1. Endpoint: the URL where requests are sent, as specified in the provider’s documentation.
    2. API key: a string that identifies the caller, similar to an access token. Unlike an account password, it can be created and revoked separately.
    3. Request body: contains the model name, the list of conversation messages, and generation parameters.
    4. Response body: contains the generated text and token usage statistics for the call.

    Store API keys in environment variables or a secrets manager. Never hard-code them in source code, and keep them out of screenshots, logs, and public repositories. If a key leaks, anyone can consume your quota, so rotate keys regularly.

    3. Core Logic of Pay-as-You-Go Billing

    Billing is based on tokens. A token is the smallest unit a model processes after splitting text. English words, Chinese characters, punctuation, and spaces may each map to one or more tokens. Tokenization rules differ between models, so the same text can produce different token counts. For accurate estimates, use the usage figures returned by the provider.

    Billing usually separates input from output.

    • Input tokens: system instructions, conversation history, and the current user message.
    • Output tokens: the model’s generated reply.

    As the number of turns grows, each request carries a longer history, so input tokens accumulate quickly. This is the main reason long conversations become more expensive.

    The general formula for estimating the cost of a call is:

    Cost per call = input tokens × input price + output tokens × output price

    Check the provider’s current price list for exact rates. Before you start, review the pricing in your console and set a budget cap or usage alerts. This protects you from unexpected charges caused by infinite loops or runaway retries.

    4. General Integration Process

    The integration steps are broadly the same regardless of provider.

    Step 1: Create credentials. Register on the provider’s developer platform, complete any identity verification it requires, and create an API key. Create a separate key for each project so that you can audit and revoke keys individually.

    Step 2: Fund the account and set a budget. Pay-as-you-go accounts usually require a prepaid balance. Set a monthly budget and balance alerts to keep risk within an acceptable range.

    Step 3: Verify connectivity. Send a minimal test request to confirm that the network, authentication, and model name are all correct before you connect production workloads.

    Step 4: Log usage. Write the usage fields from every response to your logs. This lets you track cost by day and by project, and spot unusual spikes.

    5. Three Methods for Migrating Conversation History

    Many users accumulate large amounts of conversation history in free interfaces and want to continue that work in a new environment. No common migration protocol exists between platforms, so migration generally depends on the user organizing the history manually. There are three common methods.

    1. Export the Raw Text and Continue Directly

    This is the most straightforward approach. Export the conversation from the original interface. The export is usually plain text or a structured format. Arrange the user and assistant messages in chronological order as a list, then use that list as the initial context for the new session.

    The drawback is high token consumption. If the history runs to hundreds of thousands of characters, every request must resend all of it. Cost and latency rise noticeably, and the history may exceed the model’s context window.

    2. Compress the History with Segmented Summaries

    Split the long history into segments by topic or time period. Have the model generate a summary for each segment. Each summary should preserve character settings, key events, unfinished tasks, and user preferences. Later requests then carry only the summaries plus the most recent few turns in full.

    Summary quality determines how well the conversation continues. Label facts, settings, and open tasks clearly in each summary so the model does not treat guesses as established facts.

    3. Store Structured Memory

    For projects that need ongoing maintenance, such as serialized fiction or continuing customer support, store key information in a database. Examples include a character attribute table, an event timeline, and a record of user preferences. Before each request, the program retrieves the records relevant to the current question and injects only what is needed.

    This method requires the most engineering effort. It also has the lowest token cost and is the easiest to audit and modify.

    6. Example Code

    The example below shows how to read credentials from environment variables and truncate the message history before sending a request. This keeps the input within budget. The actual endpoint, model name, and request fields depend on the provider’s documentation.

    1. import os
    2. import requests
    3. API_KEY = os.environ["LLM_API_KEY"] # Read from an environment variable, not hard-coded
    4. BASE_URL = os.environ["LLM_BASE_URL"] # Endpoint base URL from the provider's documentation
    5. MODEL = os.environ.get("LLM_MODEL", "your-model-name")
    6. MAX_HISTORY_CHARS = 20000 # Character limit for history, adjust to your budget
    7. def trim_history(messages, max_chars=MAX_HISTORY_CHARS):
    8. """Keep system instructions. Count backward from the newest message, and drop older messages once the limit is exceeded."""
    9. system_msgs = [m for m in messages if m["role"] == "system"]
    10. dialog = [m for m in messages if m["role"] != "system"]
    11. kept, total = [], 0
    12. for msg in reversed(dialog):
    13. total += len(msg["content"])
    14. if total > max_chars:
    15. break
    16. kept.append(msg)
    17. kept.reverse()
    18. return system_msgs + kept
    19. def chat(messages):
    20. payload = {
    21. "model": MODEL,
    22. "messages": trim_history(messages),
    23. }
    24. resp = requests.post(
    25. f"{BASE_URL}/chat/completions",
    26. headers={"Authorization": f"Bearer {API_KEY}"},
    27. json=payload,
    28. timeout=60,
    29. )
    30. resp.raise_for_status()
    31. data = resp.json()
    32. usage = data.get("usage", {})
    33. print("Input tokens:", usage.get("prompt_tokens"), "Output tokens:", usage.get("completion_tokens"))
    34. return data["choices"][0]["message"]["content"]

    This code has three points worth noting. First, the credentials and endpoint come from environment variables, so the code itself contains no sensitive information. Second, the history truncation is only a rough estimate based on character count. In production, count tokens with the tokenizer the provider supplies. Third, the usage figures are printed so they can be sent to a logging system later.

    7. Cost Control Practices

    1. Limit context length: keep only the recent content that relates to the current question, and replace the rest with summaries.
    2. Cap output length: use the maximum output token parameter to limit reply length and avoid unnecessarily long generations.
    3. Cache repeated results: for requests with identical inputs, cache the results locally to reduce duplicate calls.
    4. Set timeouts and retry limits: when network errors occur, retry with exponential backoff and cap the number of attempts to prevent runaway costs.
    5. Match the model to the task: use smaller, cheaper models for simple tasks, and switch to a more capable model only for complex reasoning.

    These measures share one goal: every call should have a clear purpose. Costs usually grow from ever-expanding history and wasteful retries, not from any single request.

    8. Frequently Asked Questions

    Q: Are API results exactly the same as the web interface?
    Not necessarily. The web interface may add system instructions, web search, or other features. By default, an API call uses only the content you submit. To get similar behavior, include the system instructions explicitly in your request.

    Q: Can the full conversation history be imported in one step?
    In most cases, no. Export the text first, then organize it using the methods in Section 5.

    Q: How do I know whether my budget is sufficient?
    Run a small test with one week of real workload. Record the average input and output tokens per request, then multiply by the expected number of calls to estimate the monthly cost.