LLM API Selection and Cost Optimization: From Evaluation to Production

    This article presents a practical engineering approach to selecting large language model APIs under task, budget, and risk constraints. It covers evaluation dimensions, building an in-house evaluation set, assessing multimodal tasks, modeling and reducing costs, and implementing multi-model routing with fallback.

    1. Why LLM Selection Needs a Method

    Model release cycles are fast, and new versions often introduce new comparisons in general benchmarks, task-specific tests, or pricing. For business teams, this information is useful as a reference but difficult to turn directly into production decisions. There are three reasons. First, the task distribution of public benchmarks may not match the team’s own business scenarios. Second, results from a single test are affected by prompts, sampling parameters, and data distribution, so reproducibility is limited. Third, model pricing, rate limits, and service availability change with versions and provisioning methods, so decisions need to be based on actual billing and measured data.

    The goal of model selection is therefore not to find the “strongest” model, but to find the most suitable model under current task, budget, and risk constraints. Teams should treat model selection as an engineering problem: clarify requirements, define metrics, measure with their own data, and review continuously.

    2. Break Down Evaluation Dimensions

    Model selection should cover at least the following five dimensions.

    • Task capability: Accuracy on core business tasks. Examples include field-level accuracy for information extraction, unit test pass rate for code generation, and human satisfaction for customer service Q&A.
    • Output quality and stability: Consistency of results across multiple calls with the same input, format adherence (for example, whether the model consistently outputs valid JSON), refusal rate, and hallucination rate.
    • Latency and throughput: Time to first token, overall generation time, and concurrency limits. Interactive scenarios are sensitive to time to first token, while batch scenarios focus more on throughput.
    • Cost: Per-call cost based on input and output token pricing, plus hidden overhead from retries, context expansion, and tool calls.
    • Compliance and operations: Data retention policies, regional requirements, service-level agreements, and version deprecation cycles.

    These dimensions often constrain one another. Stronger model capability often comes with higher unit cost and latency. Teams need to assign weights to each dimension according to business priorities rather than optimizing all of them.

    3. Build an In-House Evaluation Set

    Public benchmarks only show how models perform on general tasks. What really determines production performance is an in-house evaluation set. The build steps are as follows:

    1. Sample from real online requests, covering high-frequency scenarios and edge cases, with at least dozens of examples per category.
    2. Write reference answers or scoring criteria for each sample. For open-ended tasks, break the task into a set of checkable criteria.
    3. Fix the prompt template, temperature and other sampling parameters, and system instructions so that different models are compared under the same conditions.
    4. Combine automated scoring with manual spot checks, and record the types of failure cases to help locate problems.

    Example code (evaluation framework skeleton):

    1. import json
    2. from dataclasses import dataclass
    3. @dataclass
    4. class EvalCase:
    5. prompt: str
    6. expected_fields: dict
    7. def score_output(raw_text: str, expected: dict) -> float:
    8. """Check whether the output is valid JSON and compare fields one by one."""
    9. try:
    10. data = json.loads(raw_text)
    11. except json.JSONDecodeError:
    12. return 0.0
    13. hits = sum(1 for k, v in expected.items() if data.get(k) == v)
    14. return hits / len(expected) if expected else 0.0
    15. def run_eval(cases, call_model) -> float:
    16. """call_model is a function that calls the model under test; each team implements it."""
    17. scores = [score_output(call_model(c.prompt), c.expected_fields) for c in cases]
    18. return sum(scores) / len(scores) if scores else 0.0

    The evaluation framework is decoupled from specific models. When a new model is released, teams only need to replace the implementation of call_model to reuse all samples.

    4. Key Evaluation Points for Multimodal Tasks

    Image understanding, document parsing, and visual generation are difficult to measure with a single accuracy metric. Split evaluation by task:

    • Image QA: Use annotated image sets and check whether key information is correctly recognized.
    • Document and table parsing: Compare the completeness of structural restoration, including headers, merged cells, and numerical precision.
    • Visual aesthetic tasks: Use blind scoring by multiple reviewers and record the review criteria to avoid a single reviewer’s preferences dominating the conclusion.

    For aesthetic outputs, combine subjective scores with quantifiable checks, such as composition rule checks and text readability detection. This reduces variance between reviewers and makes conclusions more stable.

    5. Cost Modeling and Optimization

    5.1 Single-Call Cost Model

    Most usage-based models price input tokens and output tokens separately. Daily cost can be estimated with the following formula:

    Daily cost = daily requests × (average input tokens × input unit price + average output tokens × output unit price) × (1 + retry rate)

    The retry rate includes timeout retries and regeneration after format validation failures. Many teams count only first attempts, which leads to underestimated budgets.

    5.2 Common Cost Reduction Methods

    • Trim prompts: Remove repeated system instructions and replace long documents with relevant retrieved chunks.
    • Result caching: Reuse historical results for identical or highly similar requests; suitable for FAQ-type scenarios.
    • Limit output length: Explicitly require concise formats and set a maximum output token count.
    • Batch processing: Combine requests for offline tasks to reduce scheduling overhead and improve resource utilization.
    • Tiered routing: Send simple tasks to lower-cost models and escalate complex tasks to higher-capability models.

    Cost reduction must not come at the expense of quality. After every change to prompts or routing rules, validate on the evaluation set that accuracy has not dropped significantly.

    6. Multi-Model Routing and Fallback

    Relying on a single model creates availability risk. The routing layer can select a model based on task type, latency budget, and historical success rate, and automatically fall back on failure.

    1. ROUTES = [
    2. {"name": "primary", "timeout_ms": 3000},
    3. {"name": "fallback", "timeout_ms": 8000},
    4. ]

    The routing layer can implement a function such as call_with_fallback to apply these routes and handle fallback.