LLM Usage Limits: Access Options and Cost Control

    This article explains why free LLM interfaces impose usage limits, compares free chat interfaces, subscription plans, and pay-as-you-go APIs, and describes token-based billing with a worked example. It also covers preparation steps before API integration, a controllable wrapper module with retries and usage logging, and practical cost-control measures for teams and developers.

    1. Why Usage Limits Exist

    Free interactive interfaces are usually designed for individual day-to-day question answering. To control compute costs and ensure fair use, providers commonly limit input length, set daily conversation counts, shorten how long conversation history is retained, and lower concurrency priority during peak periods. These are standard resource-governance measures, not necessarily signs of a service failure.

    For developers, the impact of these limits mainly appears in three areas:

    • Long-document processing fails midway and must be manually split and resubmitted.
    • Conversation history is cleared, so context must be rebuilt.
    • The number of calls a workflow depends on is unpredictable and difficult to fit into a schedule.

    Understanding these causes helps determine whether the problem should be solved by adjusting usage patterns or by changing the access channel.

    2. Comparison of Three Common Access Options

    Dimension Free interactive interface Subscription plan Pay-as-you-go API
    Cost structure No direct fee Fixed periodic fee Billed by actual usage
    Usage cap Set uniformly by the provider Limited within the plan Usually determined by account balance and rate limits
    Programmability None Product-dependent Supports programmatic calls
    Suitable scenarios Occasional Q&A, exploratory use Fixed-frequency personal use Batch processing, system integration, team collaboration

    Specific pricing, quotas, and rate rules are subject to each provider’s latest published terms. When choosing an option, base the decision on actual call volume rather than unit price alone.

    3. How Pay-as-You-Go Billing Works

    Most large-model services use tokens as the billing unit. A token is the basic unit by which a model splits text, and input and output are usually measured separately. The cost of a single call can be estimated with the following formula:

    • Cost = input tokens × input unit price + output tokens × output unit price

    Suppose a model’s input price is CNY 0.002 per 1,000 tokens and its output price is CNY 0.008 per 1,000 tokens. For a call with 3,000 input tokens and 800 output tokens, the cost is approximately 3 × 0.002 + 0.8 × 0.008 = CNY 0.0124. This price pair is only for demonstrating the calculation method; actual prices must follow the provider’s current price list.

    Keep the following points in mind:

    1. The same piece of Chinese text may tokenize differently across models. Use the usage data returned by the provider when estimating costs.
    2. Multi-turn conversations count prior content as input again, so longer sessions make each call more expensive.
    3. When output length is uncontrolled, cost variance increases significantly. Set an output limit.

    4. Preparation Before Integration

    Before making formal API calls, complete the following preparation:

    1. Account and authentication: Official API platforms often require account verification. Follow the platform’s rules rather than seeking workarounds.
    2. Key management: Store keys in environment variables or a dedicated secret-management service. Do not write them into source code, configuration repositories, or logs.
    3. Small-scale testing: Add a small amount of funds first, validate input and output lengths and costs with a set of typical requests, and then decide on the funding level.
    4. Budget alerts: Set usage thresholds at the account or project level and notify the responsible person when a threshold is exceeded.
    5. Runtime environment: Confirm that the local network can access the provider’s endpoint and that the system time is correct to avoid signature or authentication failures.

    5. Engineering Implementation: Wrapping a Controllable Call Layer

    Scattering call logic directly throughout business code makes usage difficult to track. It is better to encapsulate calls in an independent module that handles authentication, long-text splitting, retries, and usage logging in a unified way. The following example uses only the standard library. The endpoint path and response fields must be replaced with the definitions in the provider’s documentation:

    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. MODEL = os.environ.get("LLM_MODEL", "your-model-name")
    9. CHUNK_CHARS = int(os.environ.get("LLM_CHUNK_CHARS", "20000"))
    10. MAX_RETRIES = 3
    11. def post_json(path, payload, timeout=60):
    12. data = json.dumps(payload).encode("utf-8")
    13. req = urllib.request.Request(
    14. f"{API_BASE_URL}{path}",
    15. data=data,
    16. headers={
    17. "Authorization": f"Bearer {API_KEY}",
    18. "Content-Type": "application/json",
    19. },
    20. method="POST",
    21. )
    22. with urllib.request.urlopen(req, timeout=timeout) as resp:
    23. return json.loads(resp.read().decode("utf-8"))
    24. def call_with_retry(path, payload):
    25. for attempt in range(MAX_RETRIES):
    26. try:
    27. return post_json(path, payload)
    28. except urllib.error.HTTPError as e:
    29. retryable = e.code == 429 or e.code >= 500
    30. if not retryable or attempt == MAX_RETRIES - 1:
    31. raise
    32. except urllib.error.URLError:
    33. if attempt == MAX_RETRIES - 1:
    34. raise
    35. time.sleep(2 ** attempt)
    36. def split_text(text, size=CHUNK_CHARS):
    37. return [text[i:i + size] for i in range(0, len(text), size)]
    38. def summarize_long_text(text, instruction):
    39. outputs = []
    40. for chunk in split_text(text):
    41. payload = {
    42. "model": MODEL,
    43. "messages": [{"role": "user", "content": f"{instruction}\n\n{chunk}"}],
    44. "max_tokens": 512,
    45. }
    46. result = call_with_retry("/chat/completions", payload)
    47. record_usage(result)
    48. outputs.append(result["choices"][0]["message"]["content"])
    49. return "\n".join(outputs)
    50. def record_usage(result, ledger="usage.log"):
    51. usage = result.get("usage", {})
    52. line = (
    53. f"{time.strftime('%Y-%m-%d %H:%M:%S')}\t"
    54. f"input={usage.get('prompt_tokens', 0)}\t"
    55. f"output={usage.get('completion_tokens', 0)}\n"
    56. )
    57. with open(ledger, "a", encoding="utf-8") as f:
    58. f.write(line)

    This code reflects several design principles:

    • Externalized configuration: The endpoint, key, model name, and chunk size all come from environment variables. This makes it easier to switch between environments and prevents sensitive information from entering the codebase.
    • Retry only recoverable errors: 429 (rate limited) and 5xx server errors are suitable for backoff retries. Client errors such as 400 and 401 should be raised directly because retrying them is meaningless.
    • Exponential backoff: The wait time doubles after each attempt, reducing sustained pressure on the endpoint when the service is busy.
    • Unified accounting: Record input and output usage for every call so costs can be aggregated by day or by project.

    Note that prompt_tokens and completion_tokens are common field names, but providers may use different names. Follow their documentation.

    6. Cost-Control Strategies

    Under pay-as-you-go billing, cost depends mainly on how calls are made. The following strategies can usually reduce overhead significantly:

    1. Streamline prompts: Remove background descriptions unrelated to the task and keep fixed instructions in a stable position.
    2. Control conversation length: Summarize long conversations periodically and use the summary in place of the full history to avoid charging for large amounts of old content in every turn.
    3. Limit output length: Set a reasonable output limit based on the task. Classification and extraction tasks usually do not require long outputs.
    4. Cache results: Reuse outputs for repeated inputs where appropriate.