How to Evaluate Large Language Models: Token Cost and Hallucination Control

    Selecting a large language model for production is no longer just a benchmark-score contest. This article explains a practical and reproducible evaluation approach focused on two critical factors: cost per effective task and hallucination control. It covers token billing details, a reusable cost model with sample code, methods for measuring factual and faithfulness hallucinations, ways to combine hallucination rate with coverage, guidance for building business-aligned evaluation datasets, and a pipeline for embedding evaluation into model selection and regression testing. It also provides a multidimensional scoring framework for comparing models across business impact, cost, latency, functionality, and compliance.

    1. Introduction: Evaluation Is Shifting from “Who Is Stronger?” to “Who Is a Better Fit?”

    Once large language models enter the stage of large-scale deployment, the core question for enterprises is no longer simply “Which model has the highest overall score?” Instead, it becomes: “Which model can we afford, answer accurately with, and operate reliably in our business scenarios?”

    Many public benchmark leaderboards provide only a single overall score. That makes it difficult to answer these three practical questions:

    • Can we afford to run the model at our expected volume?
    • Does it answer accurately enough for our use cases?
    • Can it operate reliably under our latency, stability, and compliance requirements?

    For this reason, evaluation should shift toward a multidimensional, quantifiable, reproducible, and business-aligned process.

    This article focuses on four core questions:

    • How should token cost be calculated?
    • How can hallucination be quantified?
    • How should a trustworthy evaluation dataset be built?
    • How can evaluation become a sustainable part of the model selection process?

    2. Token Cost Accounting: Measure Cost per Effective Task

    The difficulty in cost accounting is that call volume, token usage, and delivered business value are not equivalent.

    Enterprises should not focus only on unit price or total call count. The more useful metric is the comprehensive cost of completing one effective task.

    2.1 Billing Structure: Details Behind the Unit Price

    Most model services bill according to token usage, but the billing granularity can vary significantly. Before comparing costs, at least four points should be considered.

    • Input and output are priced separately.
      For most model services, output tokens cost more than input tokens. Tasks involving long reasoning chains or long generated responses often have output tokens as the main cost driver.

    • Cache hit discounts.
      Context caching can provide discounts on repeated prefix tokens. The more stable the content is, the greater the benefit. Examples include system prompts and long documents that remain unchanged across requests.

    • Long-context costs can grow non-linearly.
      Multi-turn conversation history and reference documents concatenated by retrieval-augmented generation (RAG) can cause input tokens to accumulate over time. A single turn may look cheap, but the cost of an entire session can grow rapidly.

    • Failed requests may still be billed.
      Input tokens are usually not refunded when a call fails. Costs caused by timeout retries, rate-limiting queues, and other failed attempts should still be included in the total cost.

    2.2 A Reusable Cost Model

    Let:

    • I = number of input tokens for one call
    • O = number of output tokens
    • C = number of cached input tokens
    • p_in = input token price
    • p_out = output token price
    • p_cache = cached input token price, usually lower than p_in
    • f = failure rate

    If every failed call is retried once, the expected cost per call is:

    1. E[cost] = (1 + f) × [(I − C) × p_in + O × p_out + C × p_cache]

    If we also introduce task acceptance rate a, meaning the proportion of tasks that are not rejected by the business due to hallucinations, format errors, or other issues, then the comprehensive cost per effective task becomes:

    1. Cost_per_task = E[cost] / a

    This formula reveals a fact that is often overlooked: a model with a higher unit price but an acceptance rate close to 100% may have a lower effective-task cost than a cheaper model that requires frequent retries and manual correction.

    The following example shows how this calculation can be implemented:

    1. import math
    2. class CostModel:
    3. def __init__(self, p_in, p_out, p_cache=0.0):
    4. self.p_in = p_in
    5. self.p_out = p_out
    6. self.p_cache = p_cache
    7. def expected_cost(self, tokens_in, tokens_out, cached=0, fail_rate=0.0):
    8. # Cached input tokens are not charged again.
    9. # If a call fails, it is assumed to be retried once.
    10. return (1 + fail_rate) * (
    11. (tokens_in - cached) * self.p_in
    12. + tokens_out * self.p_out
    13. + cached * self.p_cache
    14. )
    15. def cost_per_task(self, tokens_in, tokens_out, accept_rate, fail_rate=0.0, cached=0):
    16. if accept_rate <= 0:
    17. return math.inf
    18. return self.expected_cost(tokens_in, tokens_out, cached, fail_rate) / accept_rate

    After deploying the cost model, teams should continuously monitor the distribution of input and output tokens and configure alert thresholds.

    If the average value shifts significantly, it often means that:

    • the prompt has been modified,
    • the context assembly logic is broken,
    • or upstream requests have become abnormal.

    2.3 Common Strategies for Cost Governance

    The goal is to reduce the cost per effective task while maintaining similar quality. The following strategies can be tried in order:

    • Tiered routing.
      Use lightweight models or rules for simple, high-frequency requests, and route complex or high-risk requests to more capable models. The routing accuracy should be validated with a business evaluation set.

    • Retrieval result reranking.
      In a RAG pipeline, filter by relevance before sending content to the model. Only truly relevant fragments should be included, avoiding the practice of concatenating entire documents into the prompt.

    • Prefix caching.
      Place stable content such as system prompts and knowledge descriptions at the beginning of the context and keep it unchanged. This helps caching mechanisms work effectively.

    • Output constraints.
      Use prompts and structured output requirements to reduce unnecessary redundant content and lower output token usage.

    • Batch processing.
      For offline batch scenarios, use model services that support asynchronous batch invocation. This can often significantly reduce unit cost.

    3. Hallucination Control: From “Looks Good” to “Can Be Verified”

    Hallucination refers to content generated by a model that appears plausible but does not match facts or the given materials. Typical examples include fabricated facts, invented citations or data, and adding information that does not exist in summarization or extraction tasks.

    Hallucinations can be divided into two categories:

    • Factual hallucinations, where the output conflicts with objective facts.
    • Faithfulness hallucinations, where the output conflicts with the given materials or instructions. For example, a summary may deviate from the source document, or extracted fields may contradict the original text.

    In scenarios such as RAG, customer-service knowledge Q&A, and financial compliance review, faithfulness hallucinations can be especially harmful. The model may present “errors with sources” with the same confidence as correct answers.

    3.1 Four Evaluation Paths for Hallucination Control

    1. Factual Q&A with Reference Answers

    Construct a question set where each question has a clear correct answer. Then measure standard metrics such as accuracy, precision, and recall.

    This approach is suitable for evaluating a model’s basic factual capability.

    2. Factual Verification without Reference Answers

    Break the model’s output into independently verifiable factual claims. Then check each claim one by one using a knowledge base or online retrieval.

    This produces an assertion-level factual consistency rate and is similar to the “hallucination control” dimension used in some public evaluations.

    3. Model-Assisted Review

    Use a stronger model to score responses according to a clear rubric.

    The key is to make the review criteria explainable, reproducible, and periodically aligned with human review results.

    4. Human Expert Review

    For high-risk scenarios, use domain experts to review samples. A double-review or cross-review mechanism can improve reliability.

    3.2 Hallucination Rate and Coverage: One Metric Alone Can Mislead

    If only the hallucination rate is measured, a model can reduce the hallucination rate by refusing to answer. The result may be a low hallucination rate but a significantly lower answer coverage, which still makes the model unusable in business scenarios.

    Therefore, hallucination control must be evaluated together with coverage.

    The following example shows how to calculate an explainable hallucination rate and a combined score:

    1. import math
    2. # n is the total number of samples.
    3. # k is the number of samples judged as hallucinations.
    4. def hallucination_rate(k, n, z=1.96):
    5. """
    6. Return the point estimate and Wilson confidence interval for the hallucination rate.
    7. This makes it easier to judge whether differences between versions are statistically meaningful.
    8. """
    9. if n == 0:
    10. return 0.0, (0.0, 0.0)
    11. p = k / n
    12. denom = 1 + z * z / n
    13. center = (p + z * z / (2 * n)) / denom
    14. margin = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denom
    15. return p, (center - margin, center + margin)
    16. def scored_hallucination_index(hallucination_rate, coverage, w=0.5):
    17. """
    18. Combined hallucination-control index.
    19. coverage is the proportion of valid answers.
    20. w is the weight assigned to coverage.
    21. """
    22. return (1 - hallucination_rate) * (1 - w) + coverage * w

    When reporting results, teams should provide:

    • hallucination rate,
    • coverage,
    • and the combined index.

    If the difference in the combined index between versions falls within the confidence interval, it is not appropriate to claim that the new version is better.

    In the example above, a coverage weight of 0.5 is used. This combined index essentially measures the proportion of content in answers that is not judged to be hallucinated. In practice, the weight should be adjusted based on how tolerant the business is of refusal to answer.

    3.3 Automated Faithfulness Evaluation for RAG

    In RAG scenarios, faithfulness evaluation can be designed as a statement-by-statement review task. The review model should output structured judgments so that results can be aggregated and attributed more easily.

    1. faithfulness_prompt = """
    2. Determine whether every piece of information in the [ANSWER] is supported by the [REFERENCE MATERIALS].
    3. Rules:
    4. 1. Treat the reference materials as the only source of truth. Do not use external knowledge.
    5. 2. Mark any content not mentioned in the reference materials as "not_supported".
    6. 3. Numbers, dates, and proper nouns must exactly match the reference materials.
    7. [QUESTION]
    8. {question}
    9. [REFERENCE MATERIALS]
    10. {context}
    11. [ANSWER]
    12. {answer}
    13. Return only a JSON array. Each item must contain two fields: claim and verdict.
    14. The verdict must be either "supported" or "not_supported".
    15. """

    When calculating business metrics, faithfulness can be defined as:

    1. faithfulness rate = number of supported claims / total number of claims

    This method is sensitive to prompt wording. It is recommended to calibrate the prompt with human-annotated samples and monitor how closely the model’s judgments align with human judgments.

    3.4 Common Engineering Methods for Reducing Hallucination

    In engineering practice, simply telling the model “do not make things up” is usually not enough. The following methods are often combined:

    • Prompt constraints.
      Require answers to be based only on the given materials. If no evidence is found, the model should explicitly output something like “not mentioned in the provided materials.”

    • Structured output validation.
      Validate key fields with schema checks. If the format is invalid, automatically retry or route the request to a human.

    • Retrieval augmentation.
      Include traceable reference materials in the context and require answers to include citation sources.

    • Reduce randomness.
      For factual Q&A scenarios, consider lowering the sampling temperature. In high-risk scenarios, the model can answer multiple times, followed by consistency checks across answers.

    • Layered fallback.
      Set confidence thresholds and human review steps for high-risk requests. Retain complete call logs to make problem tracing easier.

    4. Building Evaluation Sets: Making Results Trustworthy and Reproducible

    Public leaderboards can only serve as an initial screening reference.

    What enterprises really need is an internal evaluation set that matches their business distribution and can be continuously iterated over time.

    When building an evaluation set, the following principles should be followed:

    • Business alignment.
      Sample from real logs by scenario, intent, and difficulty. Avoid evaluation questions that are disconnected from online traffic distribution.

    • Desensitization and compliance.
      Remove personal information, customer identifiers, and sensitive data. Access controls for the evaluation set should be managed with the same rigor as production data.

    • Clear labels.
      For each sample, label the reference answer, scoring dimensions, and pass criteria. For subjective tasks, also provide scoring guidelines.

    • Reasonable scale.
      Estimate sample size based on task complexity and acceptable error. Each key scenario should retain at least dozens to hundreds of samples.

    • Version management.
      Put the evaluation set and evaluation scripts under version control. Whenever the model or prompt changes, use the same evaluation set version for regression testing.

    • Holdout set isolation.
      Keep a holdout set that is not used for tuning. This avoids overfitting to the evaluation set during repeated debugging.

    5. Platform Support: Integrating Evaluation into the Engineering System

    Evaluation is not a one-time activity. It should be embedded into the continuous iteration process of models, forming a closed loop:

    1. evaluation → selection → canary → monitoring → regression

    A minimal viable evaluation pipeline usually includes the following structure:

    1. DATASET_DIR/ # Layered business evaluation sets, organized by scenario
    2. MODELS/ # Model adapter layer with a unified invocation interface
    3. CONFIGS/ # Evaluation configurations: scoring dimensions, weights, and thresholds
    4. MODELS.json # Model registry: identifiers, versions, and price parameters
    5. # Anonymized or fictional values may be used when needed
    6. REPORTS/ # Evaluation reports for different versions
    7. run_eval.py # Main evaluation runner: batch invocation, scoring, and aggregation
    8. MIN_RUN_DIR/reports/ # Minimal input version directory
    9. README.md # Evaluation methodology: scoring rules and pass criteria

    The evaluation runner should support:

    • batch invocation,
    • resume-from-breakpoint execution,
    • failure retry,
    • result persistence,
    • and result comparison.

    Model versions, prompt versions, evaluation set versions, and cost parameters should be recorded together to ensure that results are traceable and reproducible.

    1. def run_eval(dataset, model_client, judge, rubrics):
    2. results = []
    3. for sample in dataset:
    4. answer = model_client.call(sample["prompt"]) # Invoke the model under evaluation
    5. scores = {}
    6. for dim, rubric in rubrics.items():
    7. # Objective questions can use rule checks.
    8. # Subjective questions can use model review or human review.
    9. scores[dim] = judge(sample, answer, rubric)
    10. results.append({
    11. "id": sample["id"],
    12. "answer": answer,
    13. "scores": scores
    14. })
    15. return results

    In this design, model invocation and scoring logic are separated. Scoring rules are configured through rubrics, and the same evaluation set can be applied consistently to different model versions.

    From a platform perspective, enterprises often combine model invocation services, evaluation capabilities, logging services, monitoring, and alerting to support:

    • unified model access,
    • automatic scoring,
    • cost accounting,
    • and performance tracking.

    This helps transform evaluation into an engineering workflow and reduces manual statistics and repetitive work.

    A practical rollout can follow these steps:

    1. Define evaluation objectives.
      Determine business scenarios, core metrics, and pass thresholds.

    2. Build the business evaluation set.
      Perform layered sampling, labeling, desensitization, and version management.

    3. Set up a unified evaluation framework.
      Use the same evaluation set and scoring rules for multiple candidate models.

    4. Make multidimensional decisions.
      Combine effectiveness, cost per effective task, latency, stability, and compliance requirements.

    5. Run canary validation.
      Launch to a small traffic share first, then sample and monitor real requests.

    6. Perform continuous regression.
      Every time the model, prompt, or knowledge base changes, run regression evaluation. If degradation is detected, roll back promptly.

    6. Selection Decision: Multidimensional Scoring, Not a Single Leaderboard

    It is recommended to organize evaluation results into a weighted scoring table. The weights should be adjusted according to business priorities.

    Evaluation Dimension Key Metrics Weight Score
    Business effectiveness Business evaluation set pass rate, combined hallucination-control index 30%
    Cost Cost per effective task, cost stability 25%
    Latency and stability Response latency, success rate, rate-limiting behavior 15%
    Feature fit Context length, structured output, tool-calling ability 15%
    Compliance and sustainability Data security, service support, ecosystem and migration cost 15%

    Among these dimensions, “ecosystem and migration cost” deserves special attention.

    When a business relies heavily on a particular model, the architecture should use a unified model adapter layer to isolate provider-specific details. This reduces the engineering cost of switching providers in the future.

    7. Common Pitfalls and Recommendations

    In practice, teams often fall into the following traps:

    • Relying only on the total leaderboard score.
      This ignores differences between the benchmark and the company’s own business distribution.

    • Comparing only token unit prices.
      This ignores output costs, cache hit rates, and task acceptance rates.

    • Looking only at the hallucination rate number.
      This ignores the experience cost caused by increased refusal to answer.

    • Treating a single evaluation as the final decision.
      Models iterate frequently, so regular regression evaluation is necessary.

    • Keeping the evaluation set unchanged.
      As the business evolves, the evaluation set should also be updated.

    8. Conclusion

    Large language model selection is an ongoing process. The value of evaluation is to turn “it feels good” into “it is supported by data.”

    By building a scientific evaluation system around token cost accounting and hallucination control, enterprises can find a better balance among effectiveness, cost, and reliability. Only then can large language models truly support business growth.