LLM Evaluation, Selection, and Token Cost Optimization: A Practical Guide
Many developers and teams run into two problems that look contradictory but share the same root cause: subscription quotas or credits are about to expire and get wasted for lack of a suitable use case, while on the tasks that actually matter, token consumption far outpaces expectations, costs spiral out of control, and queuing delays pile up. Both symptoms trace back to the same gaps—insufficient model evaluation, no quantitative management of token consumption, and weak engineering resilience in the calling path. Rather than reviewing any single product, this article takes a general engineering perspective and addresses three areas systematically: how to evaluate and select large language models scientifically, how to quantify and optimize token consumption, and how to cope with the stability challenges brought by rate limiting and queuing.
The Four Core Dimensions for Evaluating Large Language Models
Judging whether a model is “good enough and pleasant to use” should not rely on the subjective feel of a single conversation. Instead, you need a structured evaluation framework. Common industry practice weighs a model across the following four dimensions.
1. Quality
This is the most fundamental dimension. It covers instruction following, context window length, coherence across multiple turns, the accuracy of structured output (such as JSON), and performance in specific domains (code, math, legal, customer support, and so on). Evaluate against a test set closely aligned with your own workload rather than a generic leaderboard—a model that leads a general benchmark does not necessarily translate that lead into gains for your scenario.
2. Performance
For online services, latency and throughput matter just as much. Track time to first token (TTFT), tokens per second (TPS), and behavior under high concurrency. A slightly weaker model that responds very quickly may be a better fit for real-time interaction than a “slow but strong” model.
3. Cost
Cost is not just unit price—it is the actual consumption required to complete a task. For the same summarization task, a long-context model may consume several times more tokens simply by repeatedly carrying historical content. Measure cost as the “total cost per completed unit of work,” not just the quoted price per thousand tokens.
4. Engineering fit
This includes stability, availability SLAs, rate-limiting policies (QPS/TPM ceilings), and support for streaming output and function calling. These capabilities determine whether a model can be integrated into a production system smoothly.
Understanding Tokens: The First Step Toward Cost Control
Large language models are metered and billed almost entirely in tokens. A single Chinese character roughly corresponds to one or two tokens, while an English word is often split into multiple subwords. Understanding what tokens are made of is the prerequisite for cost optimization:
- Input tokens: system prompts, conversation history, user input, and any attached context documents.
- Output tokens: the content the model generates, usually priced higher than input.
A common mistake is passing an ever-growing conversation history through untouched on every call. As the number of turns increases, input tokens swell linearly or even accelerate—this is the direct reason “a handful of tasks can burn through an entire quota.”
The pseudocode below illustrates how to estimate and record consumption:
# Pseudocode: wrap the call and log token usagedef call_model(messages, model, temperature=0.3):resp = client.chat.completions.create(model=model,messages=messages,temperature=temperature,)usage = resp.usage # includes prompt_tokens and completion_tokenslog_metrics({"model": model,"prompt_tokens": usage.prompt_tokens,"completion_tokens": usage.completion_tokens,"total_tokens": usage.total_tokens,})return resp
The key is instrumentation and collection: only by quantifying and logging the input and output tokens of every call can you pinpoint exactly where cost is being wasted.
Four Practical Paths to Optimize Token Consumption
1. Trim prompts and context
Remove redundant system prompts and avoid repeated instructions. Summarize and compress conversation history instead of passing it through in full. For example, collapse multiple turns into a one-line background overview:
# Before: pass the full history throughmessages = system_prompt + full_history + new_query # grows with each turn# After: history summary + retrieved key snippetsmessages = [{"role": "system", "content": concise_system_prompt},{"role": "system", "content": "History recap: the user is configuring an order export task and has confirmed the field format."},{"role": "user", "content": new_query},]
2. Cache and reuse results
For identical or highly similar requests (such as fixed-template summaries or common questions), build a result cache. A cache hit lets you skip the model call entirely—one of the most cost-effective ways to reduce spend.
3. Tiered model routing
Not every task needs the strongest model. Adopt a routing strategy where lightweight models handle the bulk of requests and the strong model serves as a fallback: simple classification and format conversion go to the lightweight model, while complex reasoning is escalated to the large model.
def route(task):if task["complexity"] == "low":return "light_model" # use a lightweight model for simple tasksreturn "strong_model" # use a strong model for complex tasks
4. Batching and streaming output
Offline batch jobs can merge requests to improve throughput. For online interactions, streaming output lets users see the first token sooner, improving the experience while making it easy to terminate unnecessary generation midway on demand.
Handling Rate Limiting and Queuing: A More Resilient System
An exhausted quota is only a cost problem, but rate limiting and queuing directly threaten availability. Production systems should be designed with mature resilience:
- Exponential backoff retries: when you hit rate limits (such as 429 responses), retry at increasing intervals to avoid a cascade.
- Jitter and concurrency control: add randomized jitter to concurrent requests to prevent a retry storm from hitting the backend all at once.
- Graceful degradation and fallback: when the strong model is unavailable, automatically switch to the lightweight model or cached results so the main workflow is not interrupted.
- Monitoring and alerting: build real-time dashboards for token consumption rate, error rate, and latency, with alerts triggered at thresholds, so you catch quota burn at the source instead of wondering where it went.
Supporting the Practice with General Cloud Capabilities
Putting these practices into production usually relies on the standardized infrastructure of a cloud platform—for example, using a log service to aggregate token usage and latency for each call; using monitoring and alerting to set thresholds on the cost curve and error rate; using a container platform to scale elastically against concurrency swings; and using a message queue to smooth out peaks and level the load from offline batch processing. Baidu AI Cloud offers this kind of integratable infrastructure across its ERNIE model family and related general-purpose cloud products, helping teams embed model capabilities into their production pipelines reliably.
Summary
“Quota going unused” and “money running out” are two sides of the same coin, and the answer to both points to fine-grained operational management: build a four-dimensional framework of quality, performance, cost, and engineering fit when evaluating; quantify token usage with instrumentation, cut consumption with trimmed prompts and caching, match tasks to models through tiered routing, and safeguard stability with backoff and graceful degradation. Master this methodology and you can avoid both letting your quota expire unused and letting costs quietly spiral out of control.
