LLM API Quota Limits: Call Planning and Cost Control

    This article explains how to plan LLM API usage and control costs after free or trial quotas become limited. It covers common limit types, token-based billing, API key security, a unified request function, structured chat-history migration, rolling summaries for context control, budget estimation, and retry strategies for rate limits.

    As LLM services generally move from free trials to quota management, many long-term users encounter similar problems: long conversations cannot be continued, a single input is truncated, and the daily request count reaches its cap. Behind these limits is the provider’s routine control over compute costs and resource allocation. Rather than passively waiting for quotas to recover, it is better to understand the calling mechanism and establish a usage approach that is budgetable, portable, and fault-tolerant. This article breaks down the process from a developer’s perspective.

    1. Understand the Types of Limits

    Free or trial services often apply several constraints at the same time. Common categories include:

    • Session retention policy: sessions that remain inactive for a long time may be archived or no longer support continuation.
    • Input length limit: the amount of text a single request can receive is limited; excess content must be truncated or split.
    • Request frequency quota: requests are counted by day or by minute; exceeding the limit returns a rate-limit error.
    • Context window: the total input and output length the model can process at once is limited; the longer the history, the heavier each request.

    The specific values depend on the provider’s official documentation and console. Determining which type of limit applies to your situation is the prerequisite for designing the follow-up solution.

    2. Understand the Basic Usage-Based Billing Model

    Most LLM services charge by token for usage-based billing. A token is the smallest unit the model uses to split text. A Chinese character often corresponds to roughly one to two tokens, and an English word also often corresponds to roughly one to two tokens, depending on tokenization.

    The cost of a request can be estimated with the following formula:

    Cost per request = input tokens × input unit price + output tokens × output unit price

    This formula has three key points. First, input usually includes historical conversation, so the longer the conversation, the higher the cost per turn. Second, output length can generally be limited by parameters; controlling the output cap can directly reduce costs. Third, some services set different tiers based on reasoning depth or model specification; higher tiers have higher unit costs. Choose the tier according to task difficulty rather than always using the highest tier.

    3. Credential Management: API Key Security Requirements

    When calling the service, most platforms use an API key as an identity credential. An API key serves a different purpose from an account password, but if leaked, others can still consume quota under your identity. Therefore, follow these principles:

    • Do not write keys into source code or commit them to code repositories.
    • Read keys through environment variables or a secret management service.
    • Create separate keys for different projects and environments so they can be revoked individually.
    • Rotate keys regularly, and disable them immediately if abnormal usage is detected.

    The example reads configuration through environment variables:

    1. import os
    2. API_KEY = os.environ["LLM_API_KEY"]
    3. BASE_URL = os.environ["LLM_BASE_URL"] # Refer to the selected service's API documentation
    4. MODEL_NAME = os.environ["LLM_MODEL"] # Fill in the model name provided by the service

    4. Wrap a Unified Request Function

    Centralize network requests, authentication, and error handling in one function so that changes are minimal when switching services or adding features later.

    1. import requests
    2. def chat_completion(messages, max_tokens=1024, timeout=60):
    3. url = f"{BASE_URL}/chat/completions"
    4. headers = {"Authorization": f"Bearer {API_KEY}"}
    5. payload = {
    6. "model": MODEL_NAME,
    7. "messages": messages,
    8. "max_tokens": max_tokens,
    9. }
    10. resp = requests.post(url, headers=headers, json=payload, timeout=timeout)
    11. resp.raise_for_status()
    12. data = resp.json()
    13. return data["choices"][0]["message"]["content"]

    Two parameters are set here: max_tokens and timeout. The former limits output length and prevents a single request from consuming too much quota; the latter prevents requests from waiting indefinitely and occupying local resources.

    5. Migrate Historical Conversations: Structured Storage

    Existing chat records usually exist as page text or exported files. Before migration, organize them into a unified structure. Each message contains two fields, role and content, which is consistent with the message format used by most chat APIs.

    An example data structure is as follows:

    1. [
    2. {"role": "system", "content": "You are a senior technical writing assistant."},
    3. {"role": "user", "content": "Help me clarify the boundaries of this requirement."},
    4. {"role": "assistant", "content": "Okay, I will first list the known conditions and items to confirm."}
    5. ]

    Three points require attention during migration. First, remove chitchat unrelated to the current task to reduce ineffective tokens. Second, before importing, mask sensitive information such as phone numbers, ID numbers, and internal addresses. Third, keep an original backup for later tracing and verification.

    6. Control Context Length: Rolling Summaries

    When the history exceeds the model’s context window, or when input costs rise noticeably, compress older conversations into a summary and keep only the most recent turns in original form. This approach is common in long-form writing and continuous project collaboration.

    1. def trim_history(messages, keep_recent=6):
    2. system = [m for m in messages if m["role"] == "system"]
    3. rest = [m for m in messages if m["role"] != "system"]
    4. if len(rest) <= keep_recent:
    5. return messages
    6. old, recent = rest[:-keep_recent], rest[-keep_recent:]
    7. old_text = "\n".join(f'{m["role"]}: {m["content"]}' for m in old)
    8. summary = chat_completion([
    9. {"role": "user",
    10. "content": "Please summarize the following conversation in concise English, including key information, decisions made, and unfinished items:\n" + old_text}
    11. ], max_tokens=512)
    12. return system + [{"role": "user", "content": f"[Conversation summary] {summary}"}] + recent

    Summaries lose details. For content that requires precise citation, such as code, numbers, and clauses, keep the original text or archive it separately.

    7. Estimate the Budget and Set Caps

    Before formal use, it is advisable to estimate monthly cost with a small sample:

    1. Count the average number of input and output tokens per request.
    2. Multiply by the expected average number of daily requests to obtain the daily cost.
    3. Multiply by 30 to obtain the monthly cost, and reserve a margin.
    4. Set alert thresholds in the service console or in custom counting logic.

    Record the token usage of each call to identify abnormally high-consumption scenarios in time, such as loop calls or unlimited history appending.

    8. Handle Rate Limits and Peak Hours

    During peak hours, the server may return rate-limit or service-busy status codes. A common approach is exponential backoff with random jitter: increase the wait time progressively and add a random amount. This avoids congestion caused by immediate retries and prevents many clients from retrying at the same time.

    1. import random
    2. import time
    3. def call_with_retry(messages, max_retries=5):
    4. for attempt in range(max_retries):
    5. try:
    6. return chat_completion(messages)
    7. except requests.HTTPError as e:
    8. status = e.response.status_code
    9. if status not in (429, 503) or attempt == max_retries - 1:
    10. raise
    11. time.sleep((2 ** attempt) + random.uniform(0, 1