LLM Selection Guide: Evaluating Capabilities and Deploying Models in Production

    Learn how to compare large language models using task-specific evaluations, an enterprise scorecard, and a repeatable selection process. This guide also covers API integration, retrieval-augmented generation, and the cost, latency, and security considerations that shape production deployments.

    1. Define the Problem Before Choosing a Model

    Differences between large language models largely stem from their training data mix, optimization objectives, and alignment strategies. These differences affect reasoning, coding, Chinese-language processing, and general conversation. Model selection should therefore be based on tests designed around your business tasks—not brand recognition or overall leaderboard rankings.

    Public benchmarks such as MMLU, GSM8K, HumanEval, C-Eval, CMMLU, LongBench, and MT-Bench can help with initial screening. They provide a broad indication of model capabilities, but their results often differ from performance on real enterprise workloads. Production decisions should be based on your own evaluation dataset.

    2. Practical Tests for Four Core Capabilities

    Evaluating Complex Reasoning

    Prepare multi-hop questions, mathematical word problems, and instructions with multiple constraints, with at least 100 examples in each category. Use a fixed prompt template and set temperature to 0. Record three metrics:

    • Answer accuracy
    • Instruction compliance: Whether the output meets format, length, and field requirements
    • Completeness of reasoning steps

    Evaluating Code Generation and Understanding

    Assess coding capabilities at two levels.

    First, use HumanEval-style problems to calculate pass@1. Also track whether generated code compiles or passes static checks.

    Second, use your internal code repositories to test three tasks:

    • Explain what a function does.
    • Locate a known defect.
    • Add unit tests for a specified module.

    The second level provides a closer approximation of day-to-day software development.

    Evaluating Chinese-Language and Long-Context Capabilities

    For Chinese-language performance, use question formats from C-Eval and CMMLU as references, then add domain-specific terminology and colloquial expressions from your business documents.

    For long-context performance, use needle-in-a-haystack tests: place key information at different positions in documents of varying lengths and measure recall. You can also test information extraction from financial reports or contracts and calculate field-level F1.

    Evaluating General Conversation and Multilingual Capabilities

    Use MT-Bench-style multi-turn tasks to assess general conversation. Organize blind human evaluations in which reviewers compare two models’ responses side by side, then calculate the win rate.

    For multilingual performance, build separate question-and-answer datasets for each target language. English-language results should not be treated as a substitute for evaluations in other languages.

    3. An Enterprise Model Selection Scorecard

    The weights and thresholds below are illustrative starting points. Adjust them to match your business priorities.

    Evaluation dimension Weight Measurement method Acceptance threshold
    Business task accuracy 35% An internal evaluation set with at least 200 examples, assessed through double-blind human annotation At least 85%
    Instruction compliance 10% Test cases with format, length, and field constraints At least 95%
    P95 latency 15% 1,000 consecutive requests with equivalent input lengths No more than 3 seconds for interactive use
    Concurrent throughput (QPS) 10% Load testing at the target concurrency level At least 1.2 times peak business demand
    Per-task cost (TCO) 15% Token charges plus allocated compute costs per 1,000 requests Within the budget limit
    Security and compliance 15% Data retention terms, private deployment support, data masking, and audit logs Mandatory gate: all requirements must be met

    Measure P95 latency separately. Average latency can hide the user experience impact of long-tail requests. Cost calculations should include failed-request retries and the additional token consumption associated with very long contexts.

    4. A Repeatable Selection Process

    1. Identify three to five representative business tasks and define the primary evaluation dimensions for each.
    2. Sample real request logs to build an evaluation dataset. Have domain experts annotate reference answers.
    3. Eliminate candidates that do not meet security and compliance requirements.
    4. Test the remaining models under the same conditions, keeping prompts, temperature, and context length fixed.
    5. Calculate weighted scores using the scorecard, then select a primary model and a backup.
    6. Roll out gradually while monitoring accuracy, latency, and cost. Reevaluate monthly or whenever a model version changes.

    5. Engineering Practice: Integrating a Model API

    The following example demonstrates timeouts, retries, authentication, and HTTP status handling. Endpoints, authentication schemes, and response fields vary by provider; adapt the code to the official documentation.

    1. import os
    2. import time
    3. import requests
    4. # Read credentials and endpoints from environment variables or a secrets service.
    5. # Do not hard-code secrets or write them to logs.
    6. API_ENDPOINT = os.environ["LLM_API_ENDPOINT"]
    7. API_KEY = os.environ["LLM_API_KEY"]
    8. RETRYABLE_STATUS = {429, 500, 502, 503, 504}
    9. def generate_text(prompt_text, max_tokens=500, temperature=0.7,
    10. timeout_s=30, max_retries=3):
    11. headers = {
    12. "Authorization": f"Bearer {API_KEY}", # Follow the provider's authentication documentation.
    13. "Content-Type": "application/json",
    14. }
    15. payload = {
    16. "prompt": prompt_text,
    17. "max_tokens": max_tokens,
    18. "temperature": temperature,
    19. }
    20. for attempt in range(max_retries + 1):
    21. try:
    22. resp = requests.post(API_ENDPOINT, json=payload,
    23. headers=headers, timeout=timeout_s)
    24. except requests.RequestException:
    25. if attempt == max_retries:
    26. raise
    27. time.sleep(2 ** attempt)
    28. continue
    29. if resp.status_code == 200:
    30. data = resp.json()
    31. # Response field names vary by provider; this is only an example.
    32. return data.get("generated_text", "")
    33. if resp.status_code in RETRYABLE_STATUS and attempt < max_retries:
    34. time.sleep(2 ** attempt)
    35. continue
    36. if resp.status_code in (400, 401, 403):
    37. # Retrying parameter or authentication errors will not help.
    38. raise ValueError(f"Invalid request parameters or authentication failure: HTTP {resp.status_code}")
    39. raise RuntimeError(f"Request failed: HTTP {resp.status_code}")
    40. raise RuntimeError("Retries exhausted")

    The calling application must also handle empty responses, output truncated by length limits, and model refusals. These conditions should be recorded in monitoring and handled explicitly rather than passed directly to users.

    6. Seven Steps for Implementing RAG

    Retrieval-augmented generation (RAG) helps models answer using enterprise documents, reducing unsupported content. The settings below are common starting points and should be tuned against your evaluation dataset.

    1. Split documents. Divide content by heading or paragraph. For Chinese documents, start with chunks of 300–800 characters and an overlap of 50–100 characters between adjacent chunks.
    2. Generate embeddings. Choose an embedding model that supports Chinese when working with Chinese content. Use the same model throughout a knowledge base. Switching models requires rebuilding the entire index.
    3. Store the index. Write embeddings to a vector database, along with source filenames, page numbers, and version identifiers for traceability.
    4. Retrieve candidates. Initially retrieve the top 20 results, then retain 5–10 chunks for the model.
    5. Rerank and filter. Rank candidate chunks with a cross-encoder or rules. If similarity falls below the threshold, return an insufficient-information response rather than allowing the model to improvise.
    6. Constrain answers and require citations. Instruct the model to answer only from the supplied material and include citation numbers.
    7. Evaluate and provide fallbacks. Track citation rate, citation correctness, and hallucination rate. Return a predefined fallback message when retrieval produces no results.

    RAG does not replace model evaluation. Poor retrieval can lead even a capable model to produce incorrect answers, so retrieval recall must be evaluated separately.

    7. Engineering Boundaries: Cost, Latency, and Security

    Cost and latency depend heavily on deployment architecture. Container platforms support elastic scaling, message queues can absorb high volumes of asynchronous inference requests, and object storage can manage training and fine-tuning data.

    Platforms such as Baidu AI Cloud and Alibaba Cloud, or a self-managed Kubernetes cluster, can support this type of architecture. Compare billing models and operational costs when choosing an approach, and confirm service availability for your deployment region.

    Security requirements include the following:

    • Store API keys in a secrets management service, rotate them regularly, and grant read access only to services that need it.
    • Use TLS to encrypt requests in transit.
    • Mask sensitive data before sending it to external models. Replace or remove fields such as national identification numbers, phone numbers, and bank account numbers.
    • Set audit-log retention periods according to applicable industry regulations, and apply access controls to the logs themselves.
    • In highly regulated sectors such as finance and healthcare, verify support for private deployment. Confirm whether model weights, inference logs, and fine-tuning data remain within the enterprise-controlled environment.

    8. Common Mistakes

    • Using public leaderboard rankings as the sole basis for deployment while ignoring differences between benchmark data and business data.
    • Running only one test with temperature greater than 0, making results difficult to reproduce.
    • Tracking only average latency and overlooking P95 and P99 tail latency.
    • Failing to record model versions, making output-quality changes after provider updates difficult to trace.
    • Sending raw sensitive data directly to external APIs.
    • Allowing the model to answer questions outside the knowledge base without a fallback strategy.

    Conclusion

    Build an evaluation dataset first, and let its results—not leaderboard rankings—drive model selection.

    Route requests by task type: use lower-cost models for simpler requests and more capable models for complex reasoning.

    Finally, use RAG to ground answers in source material, and maintain a feedback loop through monitoring and regular reevaluation. Track accuracy, latency, and cost continuously.