LLM API Usage Guide: Quota Management and Conversation Migration
This guide explores the transition from platform-assigned chat applications to on-demand LLM API access. It covers key concepts like API Keys and tokens, outlines the integration workflow, and provides practical Python examples for making API calls, migrating conversation history, and truncating context. Furthermore, it offers actionable strategies for cost control, security, and compliance to help developers manage API usage effectively.
I. Fundamental Differences Between Two Usage Methods
Chat applications for end-users and API interfaces for developers access the same underlying model services. The primary differences lie in authentication and metering.
- Application Side: Authenticates via account login, with quotas allocated by the service provider. Users typically cannot manually adjust quotas and must wait for resets upon hitting limits.
- API Side: Authenticates using an API Key, with quotas tied to the account balance. Each request is billed based on the actual input and output tokens consumed. Users can continue making calls by topping up their balance.
Therefore, the core of the API approach is shifting the metering model from “platform-assigned quotas” to “balance plus usage.” Users must manage their credentials, control request volumes, and take responsibility for costs.
II. Key Concepts
- API (Application Programming Interface): A predefined request format between programs. The caller sends an HTTP request with specified fields, and the server returns a structured result, typically in JSON format.
- API Key: A string identifying the caller’s identity, serving as an access credential. If leaked, others can directly consume your account balance, so it must be protected like a password.
- Token: The basic metering unit for model text processing, roughly corresponding to word or character fragments. Input and output are counted separately; long contexts significantly increase the input token count.
- Balance and Usage: Topping up forms the account balance, which is deducted based on token count after each successful call. The usage page typically displays call counts and consumption details.
III. Integration Workflow
Step 1: Log in to the service platform and complete account verification. Specific requirements follow the platform’s instructions.
Step 2: Navigate to the billing page and top up as needed. It is recommended to start with a small amount for testing to confirm the billing unit, deduction timing, and whether failed requests incur charges before committing to a larger top-up.
Step 3: Create an API Key in the key management page. It is advisable to create a separate key for each project. This way, if an anomaly occurs in one project, you only need to revoke the corresponding key without affecting other services.
Step 4: Verify call counts, token consumption, and balance changes on the usage page to ensure consistency with local records.
IV. Minimal Call Example
The following example uses only the Python standard library. Credentials and the model name are read from environment variables to avoid hardcoding them.
import jsonimport osimport urllib.requestAPI_URL = os.environ["LLM_API_URL"] # API endpoint, provided by the platform documentationAPI_KEY = os.environ["LLM_API_KEY"] # Access credential, do not hardcodeMODEL_NAME = os.environ["LLM_MODEL_NAME"] # Model name, refer to the platform listdef chat(messages, temperature=0.7, timeout=60):body = json.dumps({"model": MODEL_NAME,"messages": messages,"temperature": temperature,}).encode("utf-8")req = urllib.request.Request(API_URL,data=body,method="POST",headers={"Authorization": f"Bearer {API_KEY}","Content-Type": "application/json",},)with urllib.request.urlopen(req, timeout=timeout) as resp:return json.loads(resp.read().decode("utf-8"))if __name__ == "__main__":history = [{"role": "user", "content": "Please summarize the main idea of this text in three sentences."}]print(chat(history))
The field structure of the response body varies by platform; refer to the official documentation before parsing. The message format in the example uses the industry-standard structure of role plus content, where each message contains both a role and a content field.
V. Conversation History Migration and Truncation
Chat histories from application interfaces usually cannot be directly imported into the API and require manual structuring. This process involves three steps:
- Export: Prioritize using the platform’s data export feature. If unavailable, manually copy key content and save it as text or JSON files.
- Structuring: Organize each message into a dictionary containing
roleandcontent, maintaining the original chronological order. System instructions should be placed at the very beginning. - Truncation and Summarization: The model’s context window is limited; excessively long histories increase costs and may exceed length limits. A common practice is to retain the most recent dialogue turns and compress earlier content into a summary placed after the system instructions.
The following function truncates history by turns, assuming each turn consists of one user message and one assistant reply.
def trim_history(messages, max_turns=20):system_msgs = [m for m in messages if m["role"] == "system"]dialogue = [m for m in messages if m["role"] != "system"]return system_msgs + dialogue[-max_turns * 2:]
If the length of individual messages varies significantly, truncating by token or character count is more accurate. After truncation, check for semantic coherence, especially to avoid cutting off a complete storyline or code block.
VI. Usage Monitoring and Cost Control
The biggest risk of pay-as-you-go billing is runaway costs. The following measures can mitigate this risk:
- Budget Alerts: Set a monthly budget threshold on the platform or locally, triggering an alert when approached.
- Local Metering: Record input/output token counts, timestamps, and purposes after each call for easy reconciliation with bills.
- Streamlined Input: Remove irrelevant history for the current task. Split and retrieve long documents before processing them with the model.
- Result Caching: Return existing results directly for identical input requests to avoid redundant consumption.
- Limited Retries: Use exponential backoff for temporary errors like network timeouts, with a maximum retry limit.
import timeimport urllib.errordef call_with_retry(fn, retries=3):for attempt in range(retries):try:return fn()except (urllib.error.URLError, TimeoutError):if attempt == retries - 1:raisetime.sleep(2 ** attempt)
Retries are only suitable for temporary failures. For authentication or parameter errors, fail directly. Repeated requests will not succeed and may incur unnecessary costs.
VII. Security and Compliance
- Credential Management: Store API Keys in environment variables or dedicated secret management services. Do not hardcode them in repositories, configuration templates, or logs.
- Least Privilege: Assign keys per project and rotate them regularly. Immediately revoke and regenerate keys if anomalous calls are detected.
- Data Boundaries: Avoid sending others’ privacy information or unauthorized trade secrets to external services. When processing personal data, comply with applicable regional data protection regulations.
- Terms Verification: Before batch calling, automation tasks, or secondary distribution services, confirm whether the service agreement permits such usage.
VIII. Conclusion
On-demand API access returns quota management control to the user, but also transfers the responsibility for credential security, conversation state management, and cost accounting. Implementation should follow this sequence: start with a small top-up and a single script to verify the call workflow, then integrate history truncation and local metering, and finally establish budget alerts and key rotation mechanisms. This approach meets high-frequency usage demands while keeping costs and risks under control.
