LLM API Integration in Practice: From Credential Management to Usage Control

    Integrating a large language model through its API lets you add model capabilities to your own applications. This guide explains how to prepare an account and API keys, understand token-based billing, quotas, and rate limits, protect credentials, and make your first API call with retry handling.

    Why Integrate LLMs Through APIs

    An Application Programming Interface (API) defines the rules that programs use to communicate with a service. Instead of operating a web interface manually, your application can send data to the service and receive results directly.

    For developers, the main value of an API is the ability to embed model capabilities into existing systems, such as document processing, intelligent customer support, code assistance, and data analysis.

    API access is often described as a dedicated key. A web interface may use a username and password, while programmatic access uses separately issued credentials. These two methods differ in authentication, billing, and permissions, so they should be managed separately.

    Before You Start: Three Preparations

    1. Set up a service account. Register an account, complete any required identity verification, and confirm that the model you need is available to your account.
    2. Create access credentials. Generate separate API keys for each application or runtime environment. If one key is leaked, you can revoke only that key without affecting other systems.
    3. Confirm the billing model. Understand whether the service is pay-as-you-go or prepaid, and check the unit price, account balance, and any free quota.

    Understanding Quotas and Billing Rules

    Calling a large model API is rarely unlimited. You need to understand the key constraints before going into production.

    • Free quota. Most providers give new accounts a limited amount of free usage. Once it is used up, you may need to add funds or wait for the quota to reset.
    • Tokens as the billing unit. Most services charge by token. Tokens are the text units used by the model. Chinese and English have different tokenization ratios, so the same text can consume different token counts in different languages.
    • Balance constraints. If a prepaid account runs out of balance, the service will reject new requests and return an error.
    • Rate limits. Even with sufficient balance, providers limit the number of requests per minute and the number of concurrent requests. Exceeding these limits returns a rate-limit error.

    So “no hard-coded request cap” does not mean “no cost or rate constraints.” In practice, you should:

    • Set budget limits and balance alerts for each project.
    • Split API keys by application to track usage separately.
    • Review usage details regularly to catch abnormal spikes.

    Securing and Rotating API Keys

    An API key has the same power as an account password. If it leaks, someone else can consume your quota. Follow these security principles:

    • Never commit API keys to source code, configuration files, or public repositories.
    • Inject keys into the runtime environment through environment variables or a secret management service.
    • Redact keys in logs and do not print full Authorization headers.
    • Grant only the permissions each project needs, following the principle of least privilege.
    • Establish a rotation mechanism and replace keys regularly. If you suspect a key has leaked, revoke it immediately in the console and generate a new one.

    Making Your First API Call

    A typical LLM API call has three parts:

    • Authentication information in the request headers.
    • The model identifier and conversation messages in the request body.
    • Generation parameters that control the output behavior.

    Two important generation parameters are:

    • temperature. Controls the randomness of the output. Lower values produce more stable results, which is useful for extraction, classification, and reporting tasks. Higher values produce more diverse output, which is better for creative tasks.
    • max_tokens. Limits the maximum length of a single response. It directly affects cost and response time, so set it according to the task.

    The following example shows a generic structure. The actual request path, field names, and response format should be checked against the official documentation of the service you are using.

    1. import json
    2. import os
    3. import random
    4. import time
    5. import urllib.error
    6. import urllib.request
    7. API_BASE_URL = os.environ["LLM_API_BASE_URL"]
    8. API_KEY = os.environ["LLM_API_KEY"]
    9. def chat(prompt: str, model: str, max_retries: int = 3) -> str:
    10. """Send one chat request with exponential backoff for rate limits and transient errors."""
    11. body = json.dumps({
    12. "model": model,
    13. "messages": [{"role": "user", "content": prompt}],
    14. "temperature": 0.3,
    15. "max_tokens": 1024,
    16. }).encode("utf-8")
    17. for attempt in range(max_retries):
    18. req = urllib.request.Request(
    19. url=f"{API_BASE_URL}/chat/completions", # Path depends on the API documentation
    20. data=body,
    21. method="POST",
    22. headers={
    23. "Authorization": f"Bearer {API_KEY}",
    24. "Content-Type": "application/json",
    25. },
    26. )
    27. try:
    28. with urllib.request.urlopen(req, timeout=60) as resp:
    29. data = json.loads(resp.read().decode("utf-8"))
    30. return data["choices"][0]["message"]["content"]
    31. except urllib.error.HTTPError as err:
    32. if err.code in (429, 500, 502, 503) and attempt < max_retries - 1:
    33. time.sleep(2 ** attempt + random.uniform(0, 1))
    34. continue
    35. raise
    36. except urllib.error.URLError:
    37. if attempt < max_retries - 1:
    38. time.sleep(2 ** attempt + random.uniform(0, 1))
    39. continue
    40. raise