Model Selection for Large Language Models: From Use Cases and Cost to Evaluation
This article provides a practical guide to selecting large language models (LLMs) for production use. It breaks down the vague notion of "ease of use" into measurable dimensions—task accuracy, cost, latency, context window, stability, compliance, and ecosystem—and explains how to weigh them according to your business scenario. It includes a concrete cost estimation method with code, step-by-step instructions for building a custom evaluation set, and strategies for multi-model routing and fallback. Engineering considerations such as prompt versioning, structured output, timeouts, monitoring, and sensitive data handling are also covered, along with a phased implementation plan for teams to follow.
Why “It Works Well” Has No Universal Answer
Developers often ask which large language model (LLM) is the best, but “works well” depends entirely on the use case. The same model may excel at code completion yet struggle with summarizing long documents. A model that delivers fast, low-cost responses in customer support may not be suitable for complex multi-step reasoning. Therefore, the first step in model selection is to decompose “works well” into measurable metrics.
In practice, common use cases include code generation and review, text summarization and information extraction, knowledge-base question answering, multi-turn dialogue, and structured data output. Each type of task places different demands on model capabilities and has different tolerances for cost and latency.
Core Dimensions for Model Selection
1. Task Performance. This is the most direct metric: the correctness, completeness, and format compliance of a model’s output on your target task. Performance should be evaluated using real business samples, not generic benchmark scores. General-purpose leaderboards reflect average capabilities, but how well they match your specific task must be verified separately.
2. Invocation Cost. Most services charge per token, with input and output often priced differently; output tokens usually cost more. Cost must be calculated together with request volume, average input length, and average output length.
3. Response Latency. This includes time to first token and total generation duration. Interactive products are sensitive to first-token latency, while batch processing tasks focus more on throughput.
4. Context Window. This determines how much text can be included in a single request. A longer context enables processing of larger documents, but the stability of information retrieval from long contexts also needs to be tested.
5. Stability and Rate-Limiting Behavior. This covers service availability, concurrency limits, timeout behavior, and retry handling. In production, occasional timeouts often cause more incidents than average latency does.
6. Data Compliance. When dealing with personal information, trade secrets, or industry-specific regulations, you must verify where the data is stored, how long it is retained, and whether it is used for model training.
7. Tools and Ecosystem. This includes function calling, structured output, multimodal input, and the integration cost with your existing systems.
Weights should be assigned to each dimension during selection. For example, a customer-support scenario might give high weight to latency and cost, while a contract-review scenario should emphasize performance and compliance.
Cost Estimation Methodology
The core formula for cost estimation is as follows:
Single-request cost = (input tokens ÷ 1000) × input price per 1000 tokens + (output tokens ÷ 1000) × output price per 1000 tokens
Monthly cost = daily requests × 30 × single-request cost
The following code demonstrates this calculation. Prices are illustrative and not from any service; please refer to the latest pricing from your provider.
def monthly_cost(daily_requests, avg_in, avg_out,price_in_per_k, price_out_per_k, days=30):"""Estimate monthly invocation cost. Prices are per 1,000 tokens."""per_request = (avg_in / 1000) * price_in_per_k \+ (avg_out / 1000) * price_out_per_kreturn daily_requests * days * per_request# Assumptions: 10,000 requests/day, average input 1,500 tokens, output 400 tokenscost = monthly_cost(10000, 1500, 400, 0.002, 0.008)print(f"Estimated monthly cost: {cost:.0f} currency units") # Outputs around 1860
Three points require attention when estimating. First, average token counts should be derived from actual logs, not guessed. Second, prompt templates also consume input tokens; the longer the system prompt, the higher the fixed cost. Third, retries and failed requests are still billed and must be included in the cost model.
Building a Custom Evaluation Set
General-purpose benchmarks cannot replace business-specific evaluation. Teams should draw representative samples from real business data, construct an evaluation set, and define scoring criteria.
Steps for constructing the evaluation set are as follows:
- Collect representative samples: Cover common requests, edge cases, and high-risk scenarios, with at least dozens of samples per category.
- Annotate expected results: For tasks with standard answers, annotate directly. For open-ended tasks, define clear scoring rules.
- Determine scoring methods: Use exact matching, keyword hits, structured field validation, or a separate model for scoring. When using a model-based scorer, manually review a subset to ensure consistency.
- Fix evaluation conditions: Use consistent prompt versions, sampling temperatures, and input formats so that comparisons across models are fair.
Below is a generic evaluation framework:
def evaluate(model_call, test_set, scorer):"""Run a single model over the test set and return the average score."""scores = []for case in test_set:output = model_call(case["prompt"])scores.append(scorer(output, case["expected"]))return sum(scores) / len(scores)def exact_match(output, expected):return 1.0 if output.strip() == expected.strip() else 0.0
The evaluation results should record the performance score, average latency, and per-request cost together. Only by comparing all three can you draw actionable conclusions. If two models have similar performance, the one with lower cost is usually the better choice.
Multi-Model Routing and Fallback Strategies
In real systems, a single model rarely satisfies all requirements. A common approach is to use tiered routing: simple tasks are handled by a fast, low-cost model, while complex tasks are escalated to a more capable model.
Routing can be rule-based—for example, based on input length, task type, or user tier—or classifier-based, where a separate model judges the difficulty of the request and decides the calling path. Routing rules should be periodically adjusted based on evaluation data and online feedback.
Fallback strategies are equally important. When the primary model times out, hits rate limits, or returns unexpected output, the system should automatically switch to a backup model and log the event. Fallback output quality may be lower, so the product layer should clearly communicate this to users or adopt a conservative default behavior.
Engineering Considerations
- Version your prompts. Prompts are business logic and should be versioned, with corresponding evaluation results tied to each version.
- Enforce structured output. Ask the model to return fixed formats like JSON, and validate on the server side to avoid parsing failures that affect business flows.
- Set timeouts and retry limits. Define a timeout for each call and limit retries, using exponential backoff to prevent traffic amplification.
- Monitor key metrics. Continuously track call volume, failure rate, latency percentiles, and unit cost. Abnormal cost spikes usually result from prompt changes or request pattern shifts and need immediate investigation.
- Control sensitive data. Redact personal information before sending requests, and avoid logging full original inputs.
- Keep human fallback. For high-risk outputs—such as financial amounts, legal clauses, or medical advice—set up a manual review step.
In enterprise environments, teams can also use a cloud platform such as Baidu AI Cloud to uniformly access and manage model services, reducing the complexity of managing multiple accounts, billing, and permissions. The choice of platform should still be based on the evaluation dimensions discussed earlier, using actual performance and cost data.
Recommended Implementation Steps
- Identify two or three core business scenarios and define success criteria for each.
- Extract samples from real logs and build an evaluation set of at least 100 items.
- Run unified evaluations across candidate models, recording performance, latency, and cost.
- Determine the primary and backup models based on the results, and design routing and fallback rules.
- After deployment, maintain continuous monitoring and review evaluation results and cost changes monthly.
Selecting a large language model is not a one-time decision. Replacing subjective impressions with quantifiable metrics enables teams to make reliable trade-offs among performance, cost, and stability.
