LLM Selection Practice: Unified Access and Multi-Model Comparison

    This article explores a systematic approach to Large Language Model (LLM) selection. It covers the costs associated with integration, runtime, and evaluation, and provides a practical guide to building a unified access layer, standardizing the integration process, designing evaluation dimensions, and executing parallel multi-model comparisons. By following these practices, development teams can establish a reproducible evaluation workflow to identify the most suitable model for their specific business needs.

    1. Why Systematic Model Selection is Needed

    The number of Large Language Models (LLMs) is growing rapidly, and different models show significant performance variations in general Q&A, code generation, long-context understanding, and linguistic expression. Public leaderboards can provide references, but the test questions and scoring methods they use may not align with specific business tasks. A model ranking high on a leaderboard may not perform best in customer service Q&A or contract summarization tasks. Therefore, teams need a reproducible evaluation workflow.

    Selection decisions typically involve three types of costs, each requiring a clear measurement standard:

    • Integration Cost: The labor hours spent from account registration to the first successful API call. Record the personnel, date, and blocking issues encountered for future reuse.
    • Runtime Cost: The cost per 1,000 calls, P50 and P95 latency, and failure rate. Latency and cost should be calculated using the same batch of test requests to ensure data consistency.
    • Evaluation Cost: The labor hours required to build test sets, organize manual scoring, and archive results. Each evaluation round should record the time spent to determine whether the evaluation process itself is sustainable.

    Looking at a single metric often leads to skewed conclusions. A reasonable approach is to combine the three cost types and output quality into a single table for comprehensive judgment.

    2. General Structure of the Access Layer

    Most model services provide capabilities through network interfaces. The caller sends a structured request, and the server returns the generated result. While details vary across services, common access elements are largely consistent:

    Configuration Field Description Required Suggested Default
    LLM_BASE_URL Base URL of the API, pointing to the server entry Yes None, obtain from service documentation
    LLM_API_KEY Authentication key, placed in request header as Bearer Yes None, read from environment variables
    model_name Model identifier string, determining which model processes the request Yes None, fill according to service documentation
    messages Role-based message list, including system instructions and user input Yes None
    temperature Generation randomness, should be fixed during evaluation No 0.2
    max_tokens Maximum output length for a single response No 1024
    timeout Timeout in seconds for a single request No 30

    After abstracting these fields into configuration items, switching models only requires changing model_name without modifying business code. This is the primary benefit of a unified access approach.

    Different services do not define field names and return structures identically. For example, some services place reply text in a choices list, while others use different field names. The team should set up an adapter layer in the code, responsible for converting field names and return structures. Business code should only call unified functions. This way, adding a new service only requires modifying the adapter layer, without changing individual callers.

    2.1 Key Management Essentials

    Credential leakage directly leads to resource abuse and financial loss, so they must be managed following the principle of least privilege.

    1. Do not hardcode keys in source code or version control systems; inject them into the runtime environment via environment variables or a key management service.
    2. Create separate keys for different application purposes. If an issue occurs in one application, only the corresponding key needs to be revoked.
    3. Do not distribute keys to browsers or mobile clients. The frontend should call your own backend, which holds the key and forwards the request.
    4. Mask keys in logs, retaining only the last 4 characters for troubleshooting.

    2.2 Key Rotation Checklist

    Long-term keys are only suitable for controlled temporary environments. Production environments should follow this rotation checklist.

    • Naming Convention: Use the format “service-purpose-environment-YYYYMM”, e.g., llm-eval-test-202611.
    • Purpose Tags: Add purpose, owner, and creation date to each key in the platform or key management service.
    • Validity Period: Production keys should not exceed 90 days, with a reminder sent 14 days before expiration.
    • Rotation Steps: First create a new key, deploy it to the runtime environment, and verify successful calls, then revoke the old key. Keep a brief overlap period between the two steps to avoid service interruption.
    • Revocation Process: Immediately revoke relevant keys upon detecting a leak or personnel change, and record the revocation time and reason in a ticket.
    • Audit Frequency: Check the key list monthly and delete keys without an owner or long-unused keys.

    3. Standardized Steps for the Access Process

    Breaking down the access process into fixed steps reduces configuration discrepancies among team members.

    Step 1: Registration and Verification. Most platforms require account registration and email or phone verification. Some platforms have additional requirements for phone number format, identity verification, or regional access. Read their terms of service before starting.

    Step 2: Obtain Credentials. After logging in, create an access key in the account settings and record the creation time and purpose. Some platforms only display the full key once upon generation; save it to a secure location immediately.

    Step 3: Configure Client and Verify Connectivity. Fill in the service URL and key in the environment variables, then run the following example. The API path and return fields in the code should follow your service’s documentation.

    1. import os
    2. import time
    3. import requests
    4. BASE_URL = os.environ["LLM_BASE_URL"].rstrip("/")
    5. API_KEY = os.environ["LLM_API_KEY"]
    6. CHAT_PATH = "/chat/completions" # Refer to service documentation
    7. TIMEOUT_SECONDS = 30
    8. MAX_RETRIES = 3
    9. RETRY_STATUS = {429, 500, 502, 503, 504}
    10. def ask_model(model_name, messages, temperature=0.2, max_tokens=1024):
    11. url = BASE_URL + CHAT_PATH
    12. headers = {
    13. "Authorization": f"Bearer {API_KEY}",
    14. "Content-Type": "application/json",
    15. }
    16. payload = {
    17. "model": model_name,
    18. "messages": messages,
    19. "temperature": temperature,
    20. "max_tokens": max_tokens,
    21. }
    22. last_error = None
    23. for attempt in range(1, MAX_RETRIES + 1):
    24. try:
    25. resp = requests.post(
    26. url, headers=headers, json=payload, timeout=TIMEOUT_SECONDS
    27. )
    28. except requests.RequestException as exc:
    29. last_error = exc
    30. else:
    31. if resp.status_code == 200:
    32. data = resp.json()
    33. content = data["choices"][0]["message"]["content"]
    34. if not content:
    35. raise RuntimeError("Returned content is empty, please check max_tokens and model identifier")
    36. return content
    37. if resp.status_code not in RETRY_STATUS:
    38. # Retrying errors like 400, 401, 403, 404 is meaningless, raise directly
    39. raise RuntimeError(f"HTTP {resp.status_code}: {resp.text[:200]}")
    40. last_error = RuntimeError(f"HTTP {resp.status_code}")
    41. time.sleep(2 ** attempt)
    42. raise RuntimeError(f"Failed after {MAX_RETRIES} retries: {last_error}")
    43. if __name__ == "__main__":
    44. messages = [
    45. {"role": "system", "content": "You are a concise assistant."},
    46. {"role": "user", "content": "Introduce yourself in one sentence."},
    47. ]
    48. print(ask_model("Replace with model identifier from documentation", messages))

    Once connectivity is verified, proceed to batch testing. The table below lists troubleshooting directions for common errors.

    Status Code or Phenomenon Common Cause Handling Method
    401 Incorrect key, revoked key, or incomplete format Verify environment variables, regenerate key
    403 Account lacks permission for the model, or region restricted Confirm permissions and region settings in console
    404 Incorrect API path or model identifier typo Check path and model name against service documentation
    400 Request body fields do not meet requirements, e.g., max_tokens exceeds limit Check parameter ranges, reduce gradually and retry
    429 Rate limit triggered Back off according to wait time in response headers, reduce concurrency
    5xx or Timeout Temporary server failure Use exponential backoff retry, record failure time

    Every call may incur costs, including failed requests. Control concurrency during the debugging phase and set budget limits for test keys.

    4. Evaluation Dimensions and Test Sets

    Once access is complete, the team needs to answer one question: which model is better suited for their tasks? Answering this requires clear evaluation dimensions, a reproducible test set, and unified scoring standards.

    4.1 Evaluation Dimension Design

    Evaluation dimensions should derive from business requirements. The table below is a general template; teams can adjust weights based on tasks.

    Dimension Description Suggested Weight Scoring Method
    Factual Accuracy Whether the answer aligns with reference materials and avoids fabrication 30% Manual 1 to 5 points
    Instruction Following Whether constraints like word count, format, and steps are met 20% Rule validation plus manual review
    Chinese Expression Whether the language is natural and terminology is standard 15% Manual 1 to 5 points
    Format Stability Consistency of structure across multiple runs, e.g., JSON parseable 15% Automated validation, calculate pass rate
    Response Latency P50 and P95 latency 10% Automated statistics
    Cost per Call Average cost calculated by token 10% Automated statistics

    Accuracy and instruction following carry the highest weights because incorrect answers directly impact business outcomes. Latency and cost determine whether large-scale deployment is feasible. Weights should be documented before evaluation begins and must not be adjusted during the process.

    4.2 Test Set Construction

    The test set determines the credibility of the evaluation results. Follow these steps when building it:

    1. Determine sample source. Prioritize anonymized real business data, such as historical tickets, customer service chats, or contract snippets. If real data is insufficient, business experts can write supplementary samples.
    2. Stratify by task. Establish separate subsets for each task type. For example, extract samples for customer service Q&A, contract summarization, and code generation, with 50 to 200 samples per subset recommended.
    3. Cover edge cases. Include vague questions, missing information, extra-long inputs, and samples containing technical jargon. These samples best differentiate model capabilities.
    4. Annotate reference answers or scoring points. Provide standard answers for factual questions; for open-ended questions, list mandatory key points and prohibited content.
    5. Desensitize and control access. Remove personal information like names, phone numbers, and ID numbers. Store test sets in directories with access controls and record version numbers.

    Once the test set is finalized, freeze the version. Subsequent new samples should be placed in a new version; otherwise, historical results cannot be compared horizontally.

    4.3 Scoring Standards

    Manual scoring requires a unified scale. Each score should have a corresponding description, for example:

    • 5 points: Information is completely accurate, meets all constraints, naturally expressed, no modification needed.
    • 3 points: Main information is correct, but has omissions or minor non-compliance; usable after modification.
    • 1 point: Information is incorrect or irrelevant to the question; unusable.

    Scorers should complete a trial evaluation on the same batch of samples before formal evaluation to calculate inter-rater reliability. If discrepancies between two scorers are significant, unify standards before formal scoring. Model names should be hidden during scoring to prevent brand bias.

    5. Parallel Comparison in the Same Session and Result Recording

    After determining the test set, you can send the same set of messages to multiple models and retrieve responses in parallel. Parallel calls shorten the evaluation cycle and ensure that every model receives the exact same input.

    1. from concurrent.futures import ThreadPoolExecutor
    2. MODELS = ["model_identifier_A", "model_identifier_B", "model_identifier_C"] # Replace with model identifier from documentation
    3. def compare_models(messages):
    4. def run(model_name):
    5. try:
    6. return model_name, ask_model(model_name, messages, temperature=0.2)
    7. except RuntimeError as exc:
    8. return model_name, f"[Call Failed] {exc}"
    9. with ThreadPoolExecutor(max_workers=3) as pool:
    10. return dict(pool.map(run, MODELS))

    Pay attention to concurrency limits during parallel calls. Each service has its own rate limiting rules, and the number of worker threads should be lower than the account’s concurrency quota. Records of failed calls should also be retained, as the failure rate itself is an important basis for selection.

    Each evaluation should generate a structured record with the following fields:

    Field Description Example
    test_set_version Test set version number v1.2
    sample_id Sample ID CS-0137
    model_name Model identifier Replace with actual identifier
    run_time Call time, unified using UTC timestamp 2026-11-24T10:16:45Z
    temperature Generation randomness parameter 0.2
    max_tokens Output length limit 1024
    latency_ms End-to-end duration in milliseconds 1830
    input_tokens / output_tokens Number of input and output tokens 512 / 286
    cost Cost of this call Calculated based on service billing
    score_accuracy, etc. Manual or automated scores for each dimension 4
    failure_reason Reason for failure, leave blank if none HTTP 429

    Records should be saved in a version control system or database table for future recalculation. Repeated runs under the same test set and parameters should yield largely consistent results. If fluctuations are large, it indicates high randomness in model output. You should increase the sample size or lower the temperature parameter before comparing again.

    6. Conclusion and Next Steps

    Unified access, standardized evaluation, and complete recording are all indispensable. The access layer ensures models are interchangeable, the evaluation layer provides comparable conclusions, and the recording layer ensures conclusions can be reviewed. After completing the first round of evaluation, the team should compare the scoring results with real business feedback, check whether the evaluation dimension weights are reasonable, and adjust the test set for the next round accordingly.