A Practical Guide to LLM Evaluation and Inference Cost Optimization

    As large language models move from demos into real production environments, evaluation must shift from judging by intuition to measuring with a structured system. This guide explains how to build a reusable evaluation and model-selection methodology around complex tasks. It covers moving from single interactions to systematic evaluation, four core dimensions—task quality, response speed and throughput, invocation cost, and output stability and controllability—and how to tier calls by scenario rather than searching for an all-around model. It then presents evaluation methods for math and open-ended reasoning, code and tool-calling tasks, engineering techniques such as batching, scheduling, caching, and elastic scaling to control inference cost, a composite scoring model for selection, common pitfalls to avoid, and a scenario-based tiering strategy that balances quality, speed, cost, and long-term stability.

    As large language models (LLMs) move from the demo stage into real production environments, evaluation has to shift from judging by intuition to measuring with a structured system. In the past, users often judged a model’s capability from a single short conversation, a one-off code generation, or a piece of polished text. But in enterprise applications, what truly determines success is usually not an isolated impressive result, but the model’s stability, response speed, invocation cost, cost of failure, and engineering maintainability on complex tasks. A model that excels at math reasoning, code repair, or long-form writing is not naturally suited to every scenario; conversely, a fast, low-cost, highly stable model may amplify business risk if it is forced to handle tasks beyond its capability boundary. As a result, building a reusable evaluation and selection methodology around complex tasks is becoming an important capability for technical teams.

    1. From Single Interactions to Systematic Evaluation

    The biggest problem with a single interaction is too few samples and too much noise. A successful answer may simply mean the model happened to match a familiar pattern, and a failure may be nothing more than unclear prompt wording. Drawing conclusions from just a few cases easily leads to one-sided judgments. A more reasonable approach is to break the evaluation target into a quantifiable set of tasks and establish a stable evaluation process.

    First, define the evaluation objective clearly. Different businesses have very different expectations for a model: customer service scenarios care about response speed and format stability; code assistance cares about executability and error localization; data analysis cares about numerical correctness and logical consistency; document generation cares about structural completeness; and math or research scenarios care more about whether the reasoning chain is reliable. Without a clear objective, all subsequent metrics lose their meaning.

    Second, build an evaluation set that covers real business. The ideal dataset is not a hand-picked handful of “hard problems,” but desensitized samples drawn from real tasks that cover high-frequency, typical, edge, and failure cases. This avoids evaluation results that only hold under ideal conditions yet cannot support actual production.

    Finally, evaluation should form a closed loop. Launching a model is not the finish line but the starting point of ongoing observation. Through log collection, user feedback, automated regression, and manual spot-checks, teams can identify degradation trends across different tasks and promptly adjust prompts, routing strategies, or model versions.

    2. Core Evaluation Dimensions: Quality, Speed, Cost, and Controllability

    A reasonably complete model evaluation framework should cover at least four dimensions: task completion quality, response speed and throughput, invocation cost, and output stability and controllability.

    2.1 Task Completion Quality

    Task quality cannot be judged only by whether it “looks right,” but by whether it is “correct,” “usable,” and “reusable.” The definition of quality differs across scenarios.

    For math and logic reasoning tasks, quality is usually reflected in answer accuracy, the soundness of derivation steps, coverage of boundary conditions, and the ability to identify counterexamples. For code tasks, quality depends not only on whether the generated code looks reasonable, but also on whether it compiles, passes unit tests and static checks, and is verified by actual execution. For text generation tasks, quality involves structural completeness, factual consistency, tone matching, and editability.

    Therefore, quality evaluation should use a combination of multiple metrics. For code generation, you can measure pass rate, first-pass rate, average repair rounds, and execution time; for math problems, you can measure accuracy, step completeness, and manual review scores; for long-form generation, you can measure structural coverage, factual accuracy, and revision cost.

    Example code:

    1. def evaluate_quality(cases, model_call):
    2. results = []
    3. for case in cases:
    4. output = model_call(case["prompt"])
    5. score = judge_quality(
    6. expected=case.get("expected"),
    7. output=output,
    8. criteria=case.get("criteria", {})
    9. )
    10. results.append({
    11. "id": case["id"],
    12. "score": score,
    13. "latency": case.get("latency"),
    14. "tokens": case.get("tokens")
    15. })
    16. return aggregate(results)

    Here, judge_quality can be rule validation, automated testing, another model acting as a judge, or manual sampling review. What matters is not the specific method itself, but whether the evaluation criteria align with real business goals.

    2.2 Response Speed and Throughput

    Speed is an extremely critical variable in production. For interactive products, a slow time-to-first-token noticeably harms the experience; for batch tasks, insufficient throughput directly causes task backlogs and low resource utilization.

    Speed evaluation cannot look at average latency alone; it must also account for tail latency. For example, most requests may complete quickly while a few complex requests take significantly longer, and this variance heavily impacts user experience and business SLAs. Therefore, it is recommended to measure average latency, percentile latency, timeout rate, concurrency capacity, and retry/failure rate together.

    At the same time, speed and quality are often in tension. Some models respond fast and cheaply on simple tasks but need more thinking time or higher resource consumption on complex reasoning tasks; some models reason more deeply but struggle to meet high-concurrency, low-latency requirements. Evaluation must distinguish scenarios rather than applying the same standard to every model.

    2.3 Invocation Cost

    Cost evaluation cannot look only at per-call price; it should focus on the total cost of completing one valid task. The formula can be expressed as:

    1. Cost per valid task = Total invocation cost / Number of successfully completed tasks

    This metric is closer to business reality than unit price alone. For example, a model with a low per-call cost may actually cost more if complex tasks frequently fail and require multiple retries or manual fixes. Conversely, a model with a slightly higher unit price but a higher first-attempt success rate may be better in end-to-end cost.

    Cost should also include infrastructure costs, storage costs, monitoring costs, manual review costs, and the potential business losses caused by erroneous outputs. For high-frequency simple tasks, a fast, low-cost model may be more suitable; for low-frequency but high-value tasks, a deep reasoning model may deliver more value.

    2.4 Output Stability and Controllability

    Real systems often require model output to conform to a fixed format, such as structured fields, parseable text, standard code snippets, or moderation results. If output frequently deviates from the format, even good content quality will increase system parsing cost.

    Stability also includes consistency on repeated requests, the ability to refuse ambiguous questions, boundary control over sensitive content, and fault tolerance when facing abnormal inputs. A model that occasionally performs brilliantly but has unstable output formats is still difficult to put into production.

    Therefore, evaluation should include format validation, abnormal-input testing, repeated-request testing, and manual review sampling. For critical businesses, fallback strategies should also be set up, such as failure retries, rule validation, manual review, or degraded responses.

    3. Speed and Quality Are Not Opposed; They Should Be Layered by Scenario

    A common mistake in practice is trying to find an “all-around model.” A more realistic approach is scenario tiering: assign simple tasks to fast models, complex tasks to deep reasoning models, key decisions to strongly validated models, and low-risk tasks to low-cost models.

    For tasks like FAQ answering, format conversion, summary extraction, and simple classification, response speed and cost often matter more than ultimate reasoning ability. For complex math derivations, tricky code repair, long-chain analysis, solution comparison, and open-ended problem exploration, the model needs stronger context understanding and multi-step reasoning.

    You can implement tiered calls through a routing mechanism:

    1. def route_prompt(prompt, complexity_score, budget):
    2. if complexity_score < 0.35 and budget == "low":
    3. return call_fast_model(prompt)
    4. elif complexity_score < 0.65:
    5. return call_balanced_model(prompt)
    6. else:
    7. return call_deep_reasoning_model(prompt)

    Here, complexity_score can come from rule-based judgment, task-type recognition, question length, whether it contains multi-step constraints, whether tool calls are needed, and so on. The goal of routing is not single-point optimization but achieving a balance among quality, speed, and cost across the whole system.

    4. Evaluating Math and Open-Ended Reasoning Tasks

    Open-ended math problems, complex logic reasoning, and proof-completion tasks are important scenarios for testing the capability boundary of LLMs. These tasks cannot rely on answer matching alone, because the same final answer does not mean a reliable reasoning process. Evaluation should focus more on whether the model has long-chain reasoning, symbolic transformation, counterexample identification, and self-correction abilities.

    First, build a tiered problem set. Basic problems show whether the model has mastered fundamental operations and concepts; intermediate problems show multi-step reasoning ability; open problems show whether the model can propose ideas, spot contradictions, and correct step by step. Problems should include clearly verifiable goals, such as final answers, proof paths, boundary conditions, or counterexamples.

    Second, focus on process quality, not just result correctness. For math proof tasks, you can set several checkpoints, such as whether correct premises are introduced, whether boundary cases are covered, whether there is jumpy reasoning, whether there is circular reasoning, and whether key counterexamples are missed. Evaluation can use a combination of “result scoring + process scoring + manual spot-checks.”

    Third, you can introduce a verifier approach. For tasks that can be formalized or verified programmatically, model output should ideally pass independent validation. For example, code can run tests, formulas can be checked symbolically, and structured conclusions can pass rule constraints. Even if some open problems are hard to fully verify automatically, cross-checking with multiple models, manual review, and iterative correction can reduce error rates.

    Finally, distinguish “generating correctly” from “explaining reliably.” Some models may give correct answers but have flaws in the explanation process; some models can propose complex ideas but are unstable in execution. Therefore, in high-end reasoning scenarios, the evaluation focus should shift from “can it do it” to “can it reliably reproduce the correct process.”

    5. Evaluation Focus for Code and Tool-Calling Tasks

    The advantage of code tasks is relatively clear feedback. Evaluation should not just compare text similarity, but judge quality through compilation, testing, static checks, and actual execution results.

    A complete code evaluation typically includes:

    1. Functional correctness: whether the code achieves the intended goal;
    2. Executability: whether it passes compilation or interpretation;
    3. Boundary coverage: whether it handles null values, abnormal inputs, and extreme cases;
    4. Maintainability: whether the structure is clear and the naming is reasonable;
    5. Security: whether there are obvious risks or improper dependencies;
    6. Repair ability: whether it can iterate effectively when given error messages.

    Example evaluation flow:

    1. def evaluate_code(cases, model_call):
    2. results = []
    3. for case in cases:
    4. generated_code = model_call(case["prompt"])
    5. test_result = run_tests(
    6. code=generated_code,
    7. test_cases=case["tests"]
    8. )
    9. results.append({
    10. "passed": test_result.passed,
    11. "failed_cases": test_result.failed,
    12. "repair_rounds": 0
    13. })
    14. return results

    Tool-calling scenarios should also be included in evaluation. A model must not only generate correct text, but also judge when to call which capability, how to organize inputs, how to explain results, and how to fall back on failure. For complex workflows, the stability of the tool-calling chain is often more critical than single-call generation quality.

    6. Engineering Optimization: Batching, Scheduling, Caching, and Elastic Scaling

    After evaluation, you also need engineering means to reduce cost and improve stability. Common optimization approaches include batching, request caching, asynchronous queues, elastic scaling, model tiering, and result reuse.

    For tasks that can be executed asynchronously, you can use a queue to smooth peaks: write requests into a message queue, then have the inference service consume them gradually. This improves system throughput and avoids instantaneous peaks overwhelming inference resources. For requests that repeat frequently with little variation, you can build a result cache to reduce unnecessary model calls. For tasks with similar content but different phrasing, you can combine semantic matching to decide whether partial results can be reused.

    At the deployment level, a container platform can host inference services, object storage can hold evaluation sets and logs, a logging service can trace request chains, and monitoring and alerting can observe latency, error rate, resource utilization, and task backlogs. For example, when building model evaluation and inference services on Baidu AI Cloud, you can also combine these common cloud capabilities to connect inference tasks, data management, task scheduling, and runtime monitoring into a complete pipeline.

    In addition, establish a canary release and rollback mechanism. Before a new model goes live, run it on partial traffic and compare it against the old model. By observing success rate, latency, user feedback, and business metrics, confirm the gains before gradually expanding scope. This reduces the uncertainty introduced by model upgrades.

    To make selection more intuitive, you can convert multiple metrics into a composite score. For example:

    1. Composite score = Quality score × Quality weight
    2. + Speed score × Speed weight
    3. + Cost score × Cost weight
    4. + Stability score × Stability weight

    Weights differ across scenarios. Real-time interactive scenarios can assign higher weights to speed and stability; complex analysis scenarios can assign higher weights to quality and reasoning depth; large-scale batch scenarios can assign higher weights to cost and throughput.

    Pseudocode:

    1. def composite_score(quality, speed, cost, stability):
    2. return (
    3. 0.50 * normalize(quality)
    4. + 0.20 * normalize(speed)
    5. + 0.20 * normalize(cost)
    6. + 0.10 * normalize(stability)
    7. )

    Note that weights should be determined by business goals, not simply copied from someone else’s template. The point of a composite score is to turn vague experience into comparable, trackable, and reviewable metrics.

    8. Common Pitfalls

    First, over-relying on a single interaction. Model performance is heavily influenced by prompts, context length, task complexity, and randomness, so a small number of samples cannot represent real capability.

    Second, looking only at average metrics while ignoring tail issues. Production systems are often dragged down by a few failed requests, so you must pay attention to timeout rate, format error rate, and high-cost requests.

    Third, simply opposing speed and intelligence. A fast model is not necessarily incapable of handling complex tasks, and a deeply capable model does not necessarily have to handle every request. The key lies in task tiering and routing design.

    Fourth, neglecting updates to the evaluation set. Changes in business, changes in user question distribution, and changes in system constraints all affect model applicability. If the evaluation set is not updated, evaluation conclusions will gradually become distorted.

    Fifth, ignoring failure-handling mechanisms. Real systems can never guarantee that a model is always correct; they must design retries, degradation, manual review, and fallback responses to prevent a single-point error from spreading into a business incident.

    9. Conclusion

    Evaluating an LLM cannot be about whether it is “smart” alone, but about whether it can stably achieve goals on specific tasks while balancing quality, speed, cost, and controllability. For complex tasks in particular, a systematic evaluation framework is needed: it should test both open-ended reasoning and code ability, and assess responsiveness under high concurrency; it should focus on both single-call success rate and end-to-end total cost; it should rely on both automated validation and retain manual spot-checks and business feedback.

    Ultimately, the reasonable path for model selection is not to pursue a single strongest model, but to build a scenario-based tiering strategy: use fast models to handle high-frequency simple tasks, use deep reasoning models to handle complex problems, use engineering means to optimize throughput and cost, and use monitoring and regression mechanisms to ensure long-term stability. Only by combining model capability, business goals, infrastructure, and operational processes can LLMs truly become trusted productivity rather than a one-time technical demo.