Large Language Model Evaluation Methodology and Token Cost Optimization Practices

    This article presents a practical engineering approach to evaluating large language models and controlling token costs in production. It explains why model quality depends on the target scenario, defines capability and engineering evaluation dimensions, and describes how to build a repeatable evaluation set with objective and subjective scoring methods. It also covers token-based billing, input and output cost differences, context-window growth, and cost optimization strategies such as model routing, context compression, caching, batching, streaming, and usage monitoring.

    Why systematic model evaluation is necessary

    Large language models continue to improve rapidly, but their performance varies significantly across tasks such as language understanding, reasoning, and code generation. When choosing a model, developers often rely on public leaderboards or personal experience. As a result, a model may perform well in general benchmarks but still fall short in real business scenarios. In some cases, high invocation costs, queuing, or rate limiting may make the model difficult to use sustainably.

    Model quality is not absolute; it depends on the scenario. A model that performs well on a general leaderboard may not fit a vertical business use case. Conversely, a smaller model with appropriate tuning may offer better cost-performance on a specific task. Systematic evaluation helps answer three key questions:

    • Does the model meet the minimum accuracy and quality requirements for the task?
    • If the quality level is acceptable, are latency, throughput, and cost acceptable?
    • Can a better model-tiering strategy achieve similar results at a lower cost?

    By quantifying these dimensions, evaluation moves from a subjective impression to data-driven decision-making.

    Core dimensions of LLM evaluation

    A complete evaluation system should cover both capability and engineering dimensions.

    Capability dimensions

    • Language understanding and generation: coherence in summarization, rewriting, question answering, and multi-turn dialogue.
    • Logical reasoning: completion of mathematical calculations, causal inference, and multi-step reasoning tasks.
    • Code capabilities: code completion, cross-file understanding, bug localization, and unit test generation.
    • Long-context processing: information recall and consistency when handling long documents or long conversations.
    • Instruction following: whether the model strictly follows required formats, constraints, and role settings.

    Engineering dimensions

    • Latency: time to first token (TTFT) and overall response time.
    • Throughput: the number of requests that can be processed per unit of time, which directly affects queuing and rate-limiting experience.
    • Stability: availability under high concurrency, timeout rate, and frequency of rate-limit triggers.
    • Observability: whether calls can be traced through monitoring, alerting, and logging systems.

    Engineering dimensions are often overlooked, but they are critical to whether a product can be launched successfully. Issues such as response queuing and rate-limit truncation can significantly affect the end-user experience and must be included in evaluation.

    Building your own evaluation method

    Public leaderboards can only serve as an initial filtering reference. Real decisions should be based on an evaluation set that closely matches your business.

    Define the evaluation set

    Extract typical samples from real business scenarios, covering both high-frequency cases and edge cases. For each task type, prepare 20 to 50 cases to form a repeatable “golden dataset.”

    Establish scoring criteria

    • Objective tasks such as classification, extraction, and code execution can be scored automatically using precision/recall or unit test pass rates.
    • Subjective tasks such as writing and summarization can use human scoring or pairwise comparison with a “model-as-judge” approach to reduce single-evaluation bias.

    Example of an automated evaluation framework

    The following simplified framework sends the same set of samples to multiple candidate models and aggregates the results:

    1. # Pseudocode: multi-model comparison evaluation framework
    2. from collections import defaultdict
    3. # 1. Prepare the business evaluation set. Each case includes input and expected output.
    4. eval_dataset = [
    5. {"input": "Summarize the key risk points in the following contract clause...", "expected": "..."},
    6. {"input": "Write a function that validates email formats", "expected": "..."},
    7. # ... more cases
    8. ]
    9. def evaluate(candidate_models, eval_dataset, judge_fn):
    10. scores = defaultdict(list)
    11. latency = defaultdict(list)
    12. for model in candidate_models:
    13. for case in eval_dataset:
    14. resp, cost_ms = model.invoke(case["input"]) # Invoke the model and measure latency
    15. latency[model.name].append(cost_ms)
    16. # judge_fn can be rule-based, human, or model-based scoring
    17. scores[model.name].append(judge_fn(resp, case["expected"]))
    18. report = {}
    19. for model in candidate_models:
    20. report[model.name] = {
    21. "quality": sum(scores[model.name]) / len(scores[model.name]),
    22. "avg_latency_ms": sum(latency[model.name]) / len(latency[model.name]),
    23. }
    24. return report

    Through unified evaluation, teams can compare models across a “quality-latency” curve and avoid being misled by a single metric.

    Understanding token consumption and cost structure

    To optimize cost, it is important to understand the basic billing unit: the token.

    What is a token

    A token is the basic unit used by the model to process text. A Chinese character may correspond to one or more tokens, and an English word may also be split into one or more tokens. Models are not billed by word count or character count; they are billed by token count.

    Different pricing for input and output

    Most mainstream LLM services price input tokens and output tokens separately, and output tokens are usually more expensive than input tokens. This means:

    • A lengthy system prompt continuously consumes input tokens.
    • Generating large amounts of irrelevant content can significantly increase output costs.

    Impact of the context window

    In each conversation turn, historical messages are assembled into the context and sent again. As the number of turns increases, input tokens accumulate. Without a trimming strategy, the cost of long conversations can rise nonlinearly.

    Queuing and rate limiting

    In addition to token fees, service-side queuing and rate limiting must be considered. When request volume exceeds a quota or during peak hours, requests may be queued or even rejected. From an engineering perspective, this means designing retry, fallback, and timeout strategies to protect the user experience.

    Cost optimization strategies

    Once the sources of cost are understood, they can be addressed systematically. The following strategies can be combined.

    Trim the context

    • Remove redundant conversation history and keep only content strongly related to the current task.
    • Summarize early conversation and replace the full message history with a concise conversation summary.

    Model-tiered routing

    This is one of the most cost-effective approaches. Tasks can be classified by complexity: simple tasks such as intent recognition or formatting can be routed to smaller or lighter models, while complex reasoning tasks should be sent to more capable large models.

    1. def route_and_invoke(task):
    2. # Select a model based on task complexity to balance quality and cost
    3. if task.complexity == "low":
    4. return small_model.invoke(task.prompt)
    5. elif task.complexity == "medium":
    6. return medium_model.invoke(task.prompt)
    7. return large_model.invoke(task.prompt) # Use the large model only for complex tasks

    Caching and result reuse

    For highly repetitive queries such as FAQs or fixed template generation, introduce a caching layer. When a request hits the cache, return the result directly instead of invoking the model again. Caching can be implemented in local memory or in a distributed cache shared across instances.

    Batching and streaming output

    • Batching: combine multiple independent small requests to improve throughput and amortize scheduling overhead.
    • Streaming output: return results incrementally to improve first-token latency. In long generation tasks, low-quality output can also be stopped early, saving output tokens.

    Build cost and invocation monitoring

    Connect invocation logs, token usage, and cost data to monitoring and alerting systems. Set budget thresholds and alert rules so that abnormal daily spending or per-request cost can be detected early, preventing accidental budget exhaustion.

    1. # Pseudocode: record token usage and cumulative cost for each invocation
    2. def tracked_invoke(model, prompt, usage_store):
    3. resp, usage = model.invoke(prompt) # usage includes input and output tokens
    4. usage_store.record(
    5. model=model.name,
    6. input_tokens=usage["input_tokens"],
    7. output_tokens=usage["output_tokens"],
    8. cost=usage["input_tokens"] * PRICE_IN
    9. + usage["output_tokens"] * PRICE_OUT,
    10. )
    11. if usage_store.daily_cost() > DAILY_BUDGET:
    12. trigger_alert("Daily token cost has exceeded the budget") # Send an alert
    13. return resp

    Engineering best practices

    Overall, a scientific approach to LLM application should follow these principles:

    • Evaluate before selecting: use your own evaluation set to drive decisions rather than relying only on leaderboards.
    • Use models in tiers: match model capability to task complexity and avoid using an overly powerful model for simple tasks.
    • Make cost observable: include token usage and cost in monitoring and alerting so spending remains visible.
    • Handle rate limiting flexibly: design retries and fallbacks for queuing and timeouts to maintain stability.
    • Continuously iterate the evaluation set: as the business evolves, keep adding representative samples so the evaluation system remains effective.

    Conclusion

    Evaluating large language models is a systems-engineering task. It requires considering capability, cost, and engineering stability. Instead of spending budget on low-value tasks, teams can build a sustainable and measurable application system through model-tiered routing, context trimming, cache reuse, and cost monitoring. For enterprise scenarios that require these capabilities, Baidu AI Cloud’s general cloud product categories, such as model services, monitoring and alerting, and logging services, can be considered as an implementation option, helping teams balance quality, performance, and cost.