Usage-Based LLM API Billing: Funding API Keys and Migrating Conversations
Learn how usage-based billing works for large language model APIs, how to fund and secure API keys, send your first request, migrate conversation history, manage context and costs, handle rate limits, and continue working without exceeding budget or context limits.
Understanding Usage-Based Billing
An API is a standardized set of rules for making requests. After you create an API key on a platform, each request includes that key, allowing the platform to track usage and deduct charges from your balance. API billing and a client subscription are separate systems. A client’s quota may be exhausted while its API access continues to work, but the balances, limits, and usage histories are not shared.
Usage-based billing means you pay for what you use. Costs are primarily determined by the number of input and output tokens, while rates vary by model and platform. This does not mean the API is unlimited. Usage is also constrained by your prepaid balance, platform rate limits, and the model’s context window.
Check the Billing Rules Before Adding Funds
Before getting started, review the platform’s billing and limits documentation. Confirm these four points:
- Whether you must add funds before creating an API key. Some platforms allow you to create a key first, while others require account verification or an initial payment.
- The separate prices for input and output tokens.
- The limits for requests per minute and tokens per minute.
- The context window size for each model.
Then estimate your expected usage. You can start with a rough calculation based on one week of usage: multiply the average number of conversation turns per day by the average number of characters per turn, then convert the result to tokens. In Chinese, one character typically corresponds to approximately one or two tokens, but use the platform’s tokenizer or counting tool for a more accurate estimate.
This estimate can guide your first deposit. A practical approach is to add enough funds for about one week of usage, monitor your spending for two or three days, and adjust the amount afterward.
Create and Store an API Key
Open the platform’s API key management page and create a new key. Many platforms display the full key only once, so copy it immediately and store it in a password manager or environment variable.
Apply the principle of least privilege when configuring the key. If you only need conversational access, enable only the relevant chat or completion permissions. Do not grant management or billing permissions unnecessarily.
Give the key a descriptive name, such as long-form-writing or research-notes, so you can identify and disable it independently later.
Send Your First Request
Many platforms support a similar request structure. Always follow the platform’s documentation for the endpoint, model name, and authentication method. A common request includes:
- Request header:
Authorization: Bearer YOUR_API_KEY. Read the key from an environment variable instead of hard-coding it. - Request body: Fields such as
model,messages,max_tokens,temperature, andstream.
messages is an array in which each message contains a role and content. The role can be system, user, or assistant.
systemdefines the model’s role or constraints.usercontains the current request.assistantstores previous model responses so the conversation can continue.
A minimal example:
{"model": "platform-provided-model-name","messages": [{"role": "system","content": "You are an editor specializing in long-form fiction."},{"role": "user","content": "Continue the opening of Chapter 3 in approximately 300 words."}],"max_tokens": 800,"temperature": 0.9,"stream": false}
The response’s usage field usually lists the number of input and output tokens consumed. Record these values to track usage over time.
Migrate Existing Conversations
Conversation exports from client applications are commonly provided as JSON or plain text. They may contain turn-by-turn roles and content, but field names and structures vary between applications. Open the export first and confirm which fields represent the role and message content.
A long conversation generally cannot be inserted into a single request in its entirety. Use this three-step process:
- Remove personal information such as phone numbers, addresses, and identity document numbers. Replace them with placeholders.
- Ask the model—or create the summary yourself—to compress the earlier conversation into a concise summary. Save this summary as a
systemmessage containing character settings, plot direction, and unresolved questions. - Keep the most recent conversation turns in their original form and place them in the
messagesarray together with the summary.
This preserves continuity without exceeding the context window. For very long novels or research reports, store older chapters in an external document. Retrieve and inject only the sections relevant to the current request.
Control Request Parameters
Parameter settings affect both cost and output quality:
max_tokens: Limits the length of a single response. Fact-based queries can often use 200 to 500 tokens, while long-form continuation may require 1,000 or more.temperature: Creative writing commonly uses a value between 0.8 and 1.0. Factual organization and summarization generally work better around 0.2 to 0.5.stream: When set totrue, the response is delivered incrementally, which is useful for interactive interfaces. Streaming does not change billing, but it lets you see the result earlier and stop the request when necessary.
Remember that each request resends the conversation history. As the conversation grows, the number of input tokens and the cost of each request also increase. This is the main reason long-running conversations become more expensive.
Handle Rate Limits and Errors
Common error codes and recommended responses include:
- 400: The request format is invalid. Check parameter names and the JSON structure. Do not retry automatically.
- 401: The key is invalid or has been disabled. Check that it was copied correctly. Do not retry automatically.
- 402 or insufficient-balance errors: Add funds before trying again. Do not retry automatically.
- 429: A rate limit was triggered. Wait and retry with backoff.
- 500–503: The service is temporarily unavailable. Retry with backoff.
Use exponential backoff for retries. Wait approximately one second initially, double the delay after each failure, cap an individual wait at 30 seconds, and retry no more than five times. Add a small random delay to each wait so that multiple requests do not retry simultaneously.
After the retry limit is reached, record the error and tell the user to try again later.
Control Costs
You can estimate the cost of a request with this formula:
Request cost = input tokens × input price + output tokens × output price
Maintain a simple usage sheet with the date, model, task type, token counts, and cost for each request. This helps identify which types of work consume the most budget.
Common cost-saving practices include:
- Cache answers to repetitive questions instead of calling the API again.
- Use a less expensive lightweight model for simple tasks such as initial screening and classification.
- Replace full-document injection with summaries when working with long context.
- Configure a low-balance alert. A threshold equal to roughly half of your expected weekly usage can help prevent service interruptions.
Billing pages often provide downloadable usage details. Individual users can review them monthly, while businesses can use them for reconciliation. Because platform and model prices may change, use the rates shown on the most recent bill when recording costs.
Protect API Keys and Data
Never place an API key directly in source code, frontend pages, or public repositories. Recommended practices include:
- Store the key in an environment variable or a secrets management service.
- Rotate keys every 90 days, and rotate them immediately if suspicious activity is detected.
- If the platform supports IP allowlists, permit access only from your own devices or servers.
- Redact keys and sensitive conversation content from request logs.
- Periodically delete conversation history that is no longer needed, especially sessions containing personal information.
If a key is exposed, disable it immediately in the platform dashboard and create a replacement.
If You Do Not Want to Write Code
Users without a programming background can choose a third-party client with API configuration options or use a low-code orchestration tool. When evaluating these tools, focus on three points:
- Whether they support custom API endpoints and model names.
- Whether API keys are stored securely and encrypted.
- Whether conversations can be exported.
These tools do not eliminate the need for proper key protection. Do not share your key with others or enter it on untrusted websites.
Summary
First confirm the billing rules, pricing, and usage limits. Then create a least-privilege API key and store it securely. When migrating conversation history, remove sensitive data, summarize older content, and retain only the most recent turns. Use appropriate request parameters, retry 429 and 5xx errors with exponential backoff, and monitor usage records and balance alerts. This makes it possible to continue long conversations while keeping API costs under control.
