LLM API Token Pricing: A Practical Guide to Model Selection and Cost Optimization
LLM API costs depend on more than the price per token. This guide explains input and output pricing, model selection, off-peak scheduling, and engineering techniques such as context trimming, semantic caching, and request routing. It also includes a Python API example and guidance on monitoring token usage to keep production spending under control.
Cloud infrastructure purchasing used to revolve around compute instances, storage capacity, and network bandwidth. As large language models become part of everyday software development, another unit increasingly shapes infrastructure decisions: the token.
Tokens—the units models use to process and generate text—have become a central measure of LLM API consumption. Comparing services side by side makes pricing differences much easier to see, but choosing the lowest listed rate is not necessarily the best way to reduce costs.
This guide examines how token billing works, how developers can evaluate substantial price differences, and which engineering practices help turn cost awareness into reliable production savings.
1. Understanding LLM API Token Pricing
Early LLM API adoption often focused on comprehension and generation quality, with less attention paid to the underlying cost structure. As open-source models and cloud-hosted services have expanded, pricing has become easier to compare.
Input and Output Tokens Have Different Prices
Most providers charge separately for input and output tokens.
This distinction reflects how Transformer-based models perform inference. Input processing largely occurs during the prefill phase, when the model can process prompt tokens in parallel. Output generation is autoregressive: the model generates tokens sequentially while maintaining a KV cache.
Sequential decoding has different compute and memory-access characteristics from prefill, which helps explain why output tokens typically cost substantially more than input tokens. The exact resource balance depends on the workload; input processing is not uniformly cheaper in every technical sense.
Price Differences Can Be Substantial
The source pricing examples illustrate the potential range: one service might charge RMB 26 per million input tokens and RMB 136 per million output tokens during standard service hours, while another might offer off-peak rates of RMB 1 and RMB 4.5, respectively.
These figures are illustrative comparisons, not a current price list. Actual rates depend on the provider, model, and applicable pricing terms.
For a comparable text-processing workload, the choice of model or execution window can therefore change token charges by tens of times. This makes direct comparison useful—but only when it accounts for the work each model actually completes.
2. Choosing Models Based on the Workload
A low token price is only one part of an API selection decision. Developers also need to consider latency requirements, output quality, and the total consumption required to finish a task successfully.
Schedule Flexible Work During Off-Peak Hours
Where a provider offers off-peak pricing, asynchronous workloads are natural candidates for delayed execution. Examples include:
- Cleaning large volumes of historical logs
- Generating summaries for a document collection
- Extracting entities from offline datasets
A task queue can hold these requests until the lower-priced window without affecting an interactive user experience.
Latency-sensitive applications, such as live customer support or real-time code completion, have different requirements. They need services that can meet their concurrency and response-time targets rather than relying solely on the cheapest execution window.
Compare Quality-Adjusted Cost, Not Just Token Rates
A cheap model can become expensive if it frequently hallucinates, produces irrelevant text, or requires repeated attempts and manual review.
Conversely, a more capable model may interpret a complex prompt correctly and deliver a usable answer with fewer tokens or retries, offsetting some of its higher unit price.
The meaningful metric is therefore cost per successfully completed task, supported by measurements of total token consumption. Evaluate candidate models on a representative test set and account for:
- Input and output tokens across all attempts
- Unnecessary or unusable output
- Retries required to obtain an acceptable result
- Human intervention needed to resolve failures
This provides a more useful comparison than a price-per-million-tokens table alone.
3. Engineering Practices for Lower Token Costs
After narrowing the model choices, application architecture determines how efficiently those models are used.
Prompt Design and Context Trimming
Long context is an easy source of unnoticed spending. In a multi-turn conversation, sending the entire history on every request causes the input size to grow as the conversation continues.
A common approach combines a sliding context window with conversation summaries:
- Keep the most recent turns in their original form.
- Summarize older turns into a shorter representation.
- Send the summary alongside the recent messages.
This can reduce thousands of historical tokens to a few hundred while preserving the context needed for subsequent responses. The goal is to retain useful information rather than repeatedly transmitting the full transcript.
Semantic Caching
Many workloads contain highly similar requests, including FAQ responses and standardized support-ticket classification.
An application-level semantic cache uses vector similarity search to compare a new request with previous requests. When the similarity exceeds a defined threshold, the application can return a cached result instead of calling the model again.
For suitable requests, this reduces token consumption and can bring response times from seconds down to milliseconds. The benefit depends on whether a cached answer is appropriate for the new request—not merely whether the wording is similar.
Intelligent Request Routing
Applications often need more than one model tier. A routing gateway between the backend and model APIs can direct requests according to their complexity:
- Simple conversation or information queries go to a lower-cost, lightweight model.
- Complex reasoning and code generation go to a more capable model.
API gateway and serverless infrastructure can support this routing layer. The original architecture can be implemented using such capabilities on cloud platforms, including Baidu AI Cloud where the relevant services are available.
This tiered approach balances capability and cost instead of paying premium-model rates for every request.
4. API Integration and Token Observability
Ease of integration matters when evaluating a service. Many providers expose REST APIs, and some offer compatible request formats that allow developers to reuse an SDK or integration by changing credentials and endpoints.
Compatibility should still be checked against the relevant API documentation; changing an API key and endpoint is not sufficient for every provider.
The following Python example demonstrates a common chat-completions request format and basic token-usage reporting. The endpoint, API key, and model name are placeholders.
import requestsimport jsondef call_llm_api(prompt, max_tokens=500):# Generic API endpoint; replace with the actual service endpointurl = "https://api.your-cloud-provider.com/v1/chat/completions"headers = {"Content-Type": "application/json","Authorization": "Bearer YOUR_API_KEY"}payload = {"model": "your-model-name","messages": [{"role": "user", "content": prompt}],"max_tokens": max_tokens}response = requests.post(url, headers=headers, data=json.dumps(payload))result = response.json()# Parse token usage and connect it to monitoring and alertingif "usage" in result:prompt_tokens = result["usage"]["prompt_tokens"]completion_tokens = result["usage"]["completion_tokens"]total_tokens = result["usage"]["total_tokens"]print(f"Token usage -> Input: {prompt_tokens}, "f"Output: {completion_tokens}, Total: {total_tokens}")# Send token usage to a logging or monitoring system# report_to_monitor(total_tokens)return result["choices"][0]["message"]["content"]
In production, the monitoring step represented by report_to_monitor is essential. Token consumption from each API call should feed into centralized logging, monitoring, and alerting.
Build usage and budget dashboards that show consumption:
- By day
- By business unit or application
- By user
Keep input and output consumption distinguishable because their prices often differ. A total-token count is useful for tracking volume, but it does not by itself represent the bill.
Alerts should flag unexpected usage increases quickly. This helps teams detect problems such as application loops or abusive calls before they produce uncontrolled spending.
Conclusion
Token-based billing makes model selection an architectural decision as well as a purchasing decision.
Large differences in listed prices create opportunities for savings, but the lowest rate is not always the lowest-cost option. Effective optimization combines workload-aware scheduling, quality-adjusted evaluation, context management, semantic caching, and model routing.
With token-level observability in place, developers can move from reacting to API bills to actively managing them—while preserving the response quality and latency their applications require.
