Evaluating and Optimizing Quality and Cost in LLM Applications

    This article explains how to evaluate quality and cost together for LLM applications. It covers building a task-specific benchmark, designing scoring rules, calculating cost per successful task, tracking joint metrics, and applying engineering techniques such as context reduction, difficulty-based reasoning, caching, output-length control, and batching. It also outlines a delivery strategy for multi-step tasks.

    I. Why Quality and Cost Should Be Evaluated Together

    After an LLM application goes live, teams often look only at the price per call or only at demo quality. Both views are incomplete. A call may be cheap, but if it takes three retries to get a usable result, the actual cost is higher. A call may produce good results, but if the unit price is too high, the budget may not scale.

    Evaluation should answer one question: for a completed business task, how much was spent in total, and how many usable results were obtained? This puts quality and cost under the same denominator and brings the conclusion closer to real business conditions.

    II. Establish a Unified Evaluation Baseline

    The same model can perform very differently across tasks, so evaluation must be based on the business’s own task set. Public leaderboard scores can serve as reference, but they rarely show directly how a model will perform in a specific scenario.

    2.1 Build a Task Set

    A task set should include three types of samples:

    • High-frequency routine tasks: the majority of online traffic; they determine the overall cost level.
    • High-value complex tasks: failures are costly, so output quality needs close attention.
    • Boundary and exception tasks: samples with incomplete input, abnormal format, or requiring refusal, used to test robustness.

    Each type should come from real logs and be de-identified. The task set should contain at least several hundred samples and be updated regularly to avoid overfitting prompts or model configurations to old samples.

    2.2 Design Scoring Rules

    Scoring consists of automatic and human judgment. Output format, field completeness, and whether code passes unit tests can be judged automatically. Subjective dimensions such as semantic accuracy and expression quality require detailed scoring criteria, independent scoring by two annotators, calculation of consistency metrics, and arbitration by a third annotator when disagreements are large.

    The following is a general evaluation skeleton for recording the result, latency, and usage of each call:

    1. import time
    2. from dataclasses import dataclass, field
    3. @dataclass
    4. class CallRecord:
    5. task_id: str
    6. model: str
    7. input_tokens: int
    8. output_tokens: int
    9. latency_s: float
    10. passed: bool
    11. reasoning_tokens: int = 0
    12. @dataclass
    13. class EvalRun:
    14. records: list = field(default_factory=list)
    15. def run_eval(tasks, call_model, judge, model_name):
    16. run = EvalRun()
    17. for task in tasks:
    18. start = time.perf_counter()
    19. resp = call_model(model_name, task["prompt"])
    20. latency = time.perf_counter() - start
    21. passed = judge(task, resp["text"])
    22. usage = resp["usage"]
    23. run.records.append(CallRecord(
    24. task_id=task["id"],
    25. model=model_name,
    26. input_tokens=usage["input"],
    27. output_tokens=usage["output"],
    28. latency_s=latency,
    29. passed=passed,
    30. reasoning_tokens=usage.get("reasoning", 0),
    31. ))
    32. return run

    III. Break Down Cost per Task

    Most services charge separately for input tokens and output tokens. Some models also charge separately for tokens generated during reasoning, and these should be included in the accounting.

    The cost of a single call can be expressed as:

    Single-call cost = input tokens × input unit price + (output tokens + reasoning tokens) × output unit price

    What really needs to be compared is the cost of each task that passes acceptance:

    Cost per successful task = total cost of all calls ÷ number of tasks that pass acceptance

    This metric includes waste from retries, failures, and manual rework. Two models with the same unit price can have very different cost per successful task if their pass rates differ.

    The following hypothetical numbers illustrate the calculation. They are for demonstration only and do not represent any actual product price:

    Assume a model charges USD 1 per million input tokens and USD 4 per million output tokens. A batch of 100 tasks consumes 2,000,000 input tokens and 1,000,000 output and reasoning tokens, and 80 tasks pass acceptance.

    • Total cost = 2 × 1 + 1 × 4 = USD 6
    • Cost per successful task = 6 ÷ 80 = USD 0.075

    The corresponding calculation function is as follows:

    1. def cost_per_success(records, in_price, out_price):
    2. total = 0.0
    3. passed = 0
    4. for r in records:
    5. total += r.input_tokens / 1e6 * in_price
    6. total += (r.output_tokens + r.reasoning_tokens) / 1e6 * out_price
    7. passed += r.passed
    8. return total / passed if passed else float("inf")

    IV. Establish Joint Metrics

    Cost per successful task alone is still not enough. It is advisable to track the following metrics at the same time:

    • First-pass rate: the proportion of tasks that pass directly without retry, reflecting the model’s direct handling capability.
    • Tail latency: response time at the 95th percentile, determining whether the interactive experience is acceptable.
    • Human intervention rate: the proportion of tasks requiring manual modification, reflecting hidden costs that are easily overlooked.
    • Quality distribution: which task types concentrate low-scoring samples, making it easier to locate problems.

    When selecting a model, first filter candidates with a quality threshold, then compare cost per successful task and latency among those that meet the threshold. This avoids choosing a cheap but unusable option.

    V. Engineering Approaches to Reduce Cost

    5.1 Trim Context

    Many requests carry large amounts of historical conversation, repeated system instructions, and overly long examples unrelated to the current task. This can be handled in three ways:

    1. Keep only historical turns relevant to the current task;
    2. Put fixed instructions in a stable prefix of the request to improve server-side cache hit rates;
    3. Retrieve or summarize long documents before passing them to the model.

    5.2 Tier Reasoning by Difficulty

    Not all tasks require the deepest reasoning. A rule or lightweight classifier can first determine task difficulty, then select the corresponding model and reasoning intensity. Simple tasks use a lower tier, while high-risk or very long tasks are escalated to a higher tier.

    1. def choose_profile(task):
    2. if task["type"] in {"format_convert", "extract_field"}:
    3. return {"model": "model_fast", "reasoning": "low"}
    4. if task.get("risk") == "high" or task["length"] > 8000:
    5. return {"model": "model_strong", "reasoning": "high"}
    6. return {"model": "model_balanced", "reasoning": "medium"}

    Before a tiering strategy goes live, validate it with the evaluation baseline: is the pass rate of the lower tier on simple tasks close to that of the higher tier? If the gap is significant, adjust the classification rules.

    5.3 Caching

    • Prefix caching: reuse computed results for fixed system instructions and templates.
    • Result caching: return historical results directly for identical inputs, with an expiration time.
    • Semantic caching: reuse answers for similar questions. False hits directly cause incorrect output, so a high similarity threshold should be set and periodic spot checks should be performed.

    5.4 Control Output Length

    Specify output format and length limits in the prompt, set a reasonable maximum output length, and require structured output where possible to reduce unnecessary text. Output tokens usually cost more than input tokens, so controlling output length often has the most obvious benefit.

    5.5 Batching and Asynchrony

    Offline tasks such as data cleaning and batch summarization can combine requests and use asynchronous channels to trade lower cost for higher throughput. Online interactive tasks should keep real-time channels and reduce per-call cost through caching and tiered processing.

    VI. Delivery Strategy for Multi-Step Tasks

    The main risk of multi-step agents is that earlier errors are amplified in later steps. Safer practices include:

    • Set checkpoints: output intermediate results and automatically validate them after each stage.
    • Deliver the smallest usable version first, then iterate based on feedback, rather than generating the complete solution in one pass.
    • Keep human confirmation at key nodes and allow users to adjust goals midway.
    • Record token consumption at each step to identify cost-concentrated stages.

    This approach makes cost more controllable. Errors can be cut off early, and there is no need to pay for the entire long chain.

    VII. Implementation