Managing LLM API Costs and Long Conversations: Metered Billing and Context Window Practices

    This article explains how large language model (LLM) APIs enforce usage limits such as rate limiting, token quotas, and context windows. It covers the fundamentals of token-based billing, practical strategies for estimating costs, handling HTTP 429 errors with retry logic, and managing long multi-turn conversations through sliding windows, summarization, and selective retrieval. Code examples in Python illustrate token estimation, exponential backoff, and history trimming.

    1. Why Services Enforce Usage Limits

    When calling a large language model (LLM) API, providers typically impose several types of restrictions: free or basic quotas, requests per unit time (rate limits), input and output length per request (context window), and concurrent connection limits. These limits are standard practice for sharing computational resources among multiple users.

    The most common issues users encounter fall into three categories:

    • Conversations grow too long, and the accumulated history exceeds the context window, causing requests to be rejected or unable to continue.
    • A single input text is too large, exceeding the server’s maximum length.
    • Request frequency or cumulative usage exceeds the quota, resulting in rate-limiting or insufficient-credit errors.

    These three problems have different causes and require different solutions. Long conversations demand better context management, rate limiting requires retries and throttling, and quota exhaustion calls for adjusting usage or switching to a paid plan. Understanding where the limits come from is more valuable than trying to bypass them.

    2. API Fundamentals

    An API (Application Programming Interface) is a predefined interface for programs to communicate. Graphical applications also use APIs to talk to servers, but they hide the request behind buttons and input fields. When developers call an API directly, they need to handle three tasks: obtain credentials, construct requests, and parse responses.

    Credentials are typically an API Key. It identifies the caller and is linked to the account’s quota and billing. It is not the same as a username and password for a login account and should be treated as sensitive information.

    Requests are usually HTTP POST operations with a JSON body containing a list of messages. Each message has a role (e.g., system, user, assistant) and text content. The system message sets the overall behavior, while user and assistant messages form the conversation history.

    Responses are also JSON, containing the model’s generated content and typically a usage statistic, such as the number of input and output tokens. These fields are the basis for verifying bills and estimating costs.

    The exact field names and parameter ranges depend on the service provider’s API documentation, as they vary across vendors.

    3. Metered Billing: Tokens and Context Window

    A token is the fundamental unit of text processing for a model. It may be a whole word, a single character, or part of a word. Most services charge separately for input and output tokens, with unit prices often quoted per million tokens.

    The context window refers to the maximum number of tokens a model can process in a single request. It includes the system instruction, all history messages, and the generated content in the current call. Anything beyond that limit is rejected or truncated.

    Long conversations have a cost characteristic that is easy to overlook. Most chat APIs are stateless: each request resends the entire history. Suppose each turn adds about 200 tokens. Over 20 turns, the input size for the k-th turn is roughly 200k tokens, so the cumulative input for all 20 turns is approximately:

    200 × (1 + 2 + … + 20) = 200 × 210 = 42,000 tokens

    If the same 20 turns were sent only once, the input would be just 4,000 tokens. Cumulative input grows roughly quadratically with the number of turns, which is the main reason long conversations become expensive.

    The following functions help estimate costs before sending a request:

    1. def estimate_tokens(text: str) -> int:
    2. """Roughly estimate the token count for a text, for budget planning only.
    3. As a rule of thumb, Chinese text is about 1 token per character, English text about 1 token per 4 characters.
    4. The actual usage reported by the service is authoritative."""
    5. cjk = sum(1 for ch in text if "\u4e00" <= ch <= "\u9fff")
    6. other = len(text) - cjk
    7. return cjk + (other + 3) // 4
    8. def estimate_cost(input_tokens: int, output_tokens: int,
    9. price_in_per_m: float, price_out_per_m: float) -> float:
    10. """Prices are per million tokens, check the provider's pricing page for exact values."""
    11. return (input_tokens * price_in_per_m + output_tokens * price_out_per_m) / 1_000_000

    Be aware that different tokenizers can split the same text differently, so this rough estimate can be significantly off. It is suitable for budget alerts and capacity planning, not as an exact billing reference.

    4. Rate Limits and Error Handling

    HTTP 429 (Too Many Requests) indicates that the request frequency exceeds the limit. Common handling principles:

    • Retry on temporary errors like 429 and 5xx using exponential backoff (wait time doubles each attempt).
    • If the response header includes Retry-After, follow its timing first.
    • Add random jitter to the wait time to avoid synchronized retries from many clients causing new congestion.
    • Do not retry authentication errors (401, 403) or errors indicating exhausted quota; instead, notify the user and stop.

    Here is a request function with backoff that uses only the Python standard library:

    1. import json
    2. import os
    3. import random
    4. import time
    5. import urllib.error
    6. import urllib.request
    7. API_URL = os.environ.get("LLM_API_URL", "https://api.example.com/v1/chat/completions")
    8. API_KEY = os.environ["LLM_API_KEY"]
    9. RETRYABLE = {429, 500, 502, 503, 504}
    10. def post_with_retry(payload: dict, max_retries: int = 5) -> dict:
    11. data = json.dumps(payload).encode("utf-8")
    12. for attempt in range(max_retries):
    13. req = urllib.request.Request(
    14. API_URL,
    15. data=data,
    16. headers={
    17. "Content-Type": "application/json",
    18. "Authorization": f"Bearer {API_KEY}",
    19. },
    20. method="POST",
    21. )
    22. try:
    23. with urllib.request.urlopen(req, timeout=60) as resp:
    24. return json.loads(resp.read().decode("utf-8"))
    25. except urllib.error.HTTPError as e:
    26. if e.code in RETRYABLE and attempt < max_retries - 1:
    27. retry_after = e.headers.get("Retry-After", "")
    28. if retry_after.isdigit():
    29. wait = float(retry_after)
    30. else:
    31. wait = min(2 ** attempt, 30)
    32. time.sleep(wait + random.uniform(0, 1))
    33. continue
    34. raise
    35. raise RuntimeError("Max retries reached")

    The example only handles the numeric second format of Retry-After. The standard also allows an HTTP date format; production code may need to add that parsing.

    5. Strategies for Managing Long Conversations

    When a conversation exceeds the context window, three common approaches are available.

    1. Sliding window: Keep only the most recent several turns and discard older messages. It is simple to implement and keeps costs predictable, but early instructions and critical details may be lost.

    2. Summarization: Periodically ask the model to generate a summary of older history and replace the original messages with that summary. Important information is preserved, but this costs an extra API call, and the summary may miss details.

    3. Chunking and on-demand retrieval: Store the full history locally and only insert the segments relevant to the current question into the context. This suits scenarios with large amounts of material and wide-ranging questions, but adds a retrieval step.

    In practice, these methods are often combined. For example, keep the latest few turns verbatim, compress earlier turns into a summary, and save the complete record locally for later reference.

    The following function trims history according to a token budget, preserves system messages, and accumulates from the most recent messages backward:

    1. def trim_history(messages: list[dict], budget: int) -> list[dict]:
    2. """Keep system messages and include messages from newest to oldest until the token budget is reached."""
    3. system_msgs = [m for m in messages if m["role"] == "system"]
    4. others = [m for m in messages if m["role"] != "system"]
    5. used = sum(estimate_tokens(m["content"]) for m in system_msgs)
    6. kept = []
    7. # Implementation continues based on the budget...
    8. # For brevity, the original code is truncated in the source; complete logic would iterate and add messages while used < budget.