Practical Guide to LLM Selection and Unified API Integration

    This guide provides an actionable workflow for evaluating, testing, and integrating multiple Large Language Models (LLMs) into a unified architecture. It covers model selection using weighted scoring, building custom test sets for fair comparison, implementing unified API access with fallback strategies, and monitoring costs effectively.

    Introduction: From Model Selection to Managing Multiple Models

    Large Language Models (LLMs) have entered a phase of parallel development across multiple vendors. For developers, the challenge is no longer finding an available model, but choosing among them, unifying API access, and continuously comparing their performance. Relying on a single model carries specific risks: quality drops in specific tasks, API rate limits, or price adjustments can directly impact live features. Consequently, more teams are adopting a multi-model architecture, encapsulating model calls into switchable capabilities.

    This article provides an executable workflow. Step 1: Evaluate candidate models using a weighted table. Step 2: Compare them on the same test set and record results. Step 3: Call models through unified access code. Step 4: Configure cost monitoring and fallback strategies. API endpoints, model IDs, and prices are placeholders; refer to the official documentation for actual usage.

    1. Selection Evaluation: Weight Tables and Scoring Methods

    It is recommended to define evaluation dimensions and weights before scoring candidate models. Weights should be determined by business needs. For example, customer support prioritizes latency and cost, while coding assistants prioritize code runnability. The table below offers a universal starting point:

    Evaluation Dimension Weight Observation Metric Measurement Method
    Task Correctness 35% Consistency rate with standard answers Rule-based or manual scoring, per question
    Code Runnability 15% Proportion of generated code passing unit tests Automated execution of fixed test cases
    Long Context Understanding 10% Recall of key information Embedding facts in long documents, tracking Q&A hit rate
    Instruction Following & Formatting 10% Proportion of output matching specified formats (e.g., JSON) Automated validation via parser
    Response Latency 10% Time to first token, P50 and P95 of total duration Recording request and response timestamps
    Cost per Task 15% Average cost per task Calculated by token usage and unit price
    Stability 5% Error rate and rate limit occurrences Proportion of non-2xx responses

    Convert each dimension to a 0-100 score, then calculate the weighted sum to get the total model score. The calculation formula is as follows:

    Total Score = Σ (Dimension Weight × Dimension Score)

    Decision rules can be set as follows: Candidate models scoring below 60 in correctness are eliminated, regardless of other dimensions. Models with a total score difference of less than 5 are considered insignificantly different; in this case, the cost per correct answer is the deciding factor.

    2. Building a Test Set: Comparing Models on the Same Questions

    Public leaderboards reflect general capabilities and may not match your business needs. It is recommended to build a small-scale test set covering real-world scenarios. A reference composition:

    • Code Generation: ~40 questions, e.g., implementing functions with boundary handling plus unit tests.
    • Long Context Understanding: ~20 questions, e.g., locating clauses in a long document and answering questions.
    • Logic & Math: ~30 questions, including error-prone word problems and common sense traps.
    • Multi-turn Consistency: ~15 questions, e.g., checking if constraints set earlier are maintained after 10 rounds of dialogue.

    Control variables during comparison. All models should use the same Prompt and input. Set the temperature parameter uniformly between 0 and 0.3 to reduce random fluctuations. Some providers’ models do not accept temperature or use fixed sampling strategies, so record the effective parameters. Repeat the same question 3 times to observe output variance rather than relying on a single run.

    Fill out a record table for each run for future review. Recommended fields: Case ID, Model ID, Run Count, Output Summary, Score, Input Tokens, Output Tokens, Duration, Error Message, Remarks.

    3. Unified Access: Minimum Viable Example

    Many providers offer API formats compatible with OpenAI. If the target provider offers this, you can use the same code to call different models by simply switching the endpoint, key, and model ID.

    Place keys and endpoints in environment variables; do not hardcode them or commit them to repositories:

    1. export LLM_BASE_URL="https://your-provider.example.com/v1" # Replace with the endpoint from the provider's documentation
    2. export LLM_API_KEY="sk-xxxx" # Replace with your own key

    Use curl for a minimal request:

    1. curl "$LLM_BASE_URL/chat/completions" \
    2. -H "Authorization: Bearer $LLM_API_KEY" \
    3. -H "Content-Type: application/json" \
    4. -d '{
    5. "model": "model-a",
    6. "messages": [{"role": "user", "content": "Explain what a hash table is in one sentence."}],
    7. "temperature": 0.2
    8. }'

    In Python, use the official openai client library with retry logic:

    1. import os
    2. import time
    3. from openai import OpenAI, APIStatusError, APITimeoutError, APIConnectionError
    4. client = OpenAI(
    5. api_key=os.environ["LLM_API_KEY"],
    6. base_url=os.environ["LLM_BASE_URL"],
    7. timeout=30.0,
    8. max_retries=0, # Retry logic is controlled uniformly by the function below
    9. )
    10. RETRYABLE_STATUS = {429, 500, 502, 503, 504}
    11. def chat_with_retry(model, messages, temperature=0.2, retries=3):
    12. for attempt in range(retries):
    13. try:
    14. resp = client.chat.completions.create(
    15. model=model,
    16. messages=messages,
    17. temperature=temperature,
    18. )
    19. return resp.choices[0].message.content
    20. except APIStatusError as e:
    21. # 401, 403, 404 indicate configuration issues; retries are invalid, raise directly
    22. if e.status_code in RETRYABLE_STATUS and attempt < retries - 1:
    23. time.sleep(2 ** attempt)
    24. continue
    25. raise
    26. except (APITimeoutError, APIConnectionError):
    27. if attempt < retries - 1:
    28. time.sleep(2 ** attempt)
    29. continue
    30. raise
    31. if __name__ == "__main__":
    32. answer = chat_with_retry(
    33. "model-a",
    34. [{"role": "user", "content": "Explain what a hash table is in one sentence."}],
    35. )
    36. print(answer)

    This code applies exponential backoff retries for rate limits (429) and server errors (5xx). Authentication and parameter errors are raised directly to avoid wasting quota on invalid retries.

    Common Errors and Troubleshooting Order

    Phenomenon Common Cause Solution
    401 Invalid key, revoked key, or extra spaces during copy Regenerate key, check environment variables
    403 Model not enabled for account, or key permissions exclude this model Verify model status and key scope in the console
    404 Typo in model ID or incorrect request path Check against the provider’s model list and API documentation
    429 Rate limit triggered, overly frequent requests Reduce concurrency, increase backoff wait time
    5xx Temporary server failure Retry, log the incident, switch to fallback model if necessary
    Timeout Unstable network or excessive output Increase timeout limit, restrict max output tokens

    Troubleshoot top-down. Verify network connectivity first, then key validity, and finally model ID and permissions.

    4. Scoring Table and Judgment Methods for Multi-Model Comparison

    Score each case’s output using unified criteria to avoid subjective judgment. The following scoring table can be used directly in manual reviews:

    Scoring Item 2 Points 1 Point 0 Points
    Correctness Conclusion and key steps are correct Conclusion correct, but steps flawed or missing Conclusion wrong
    Runnability (Code) Passes all test cases Passes some test cases Cannot run or syntax error
    Instruction Following Fully meets format and word count requirements Generally meets, minor deviations Obviously violates requirements
    Information Density No redundancy, key info complete Minor redundancy or omissions Extensive redundancy or missing key info

    Besides quality scores, track efficiency and cost metrics. The most valuable metric is the cost per correct answer, calculated as follows:

    Cost per correct answer = Total test set cost (including failed and retried requests) ÷ Number of correct answers

    This metric reflects quality, retry overhead, and price simultaneously. A low-priced model with a high error rate might actually cost more.

    5. Integration and Cost Monitoring

    1. Abstract Interface Layer

    Avoid hardcoding model IDs in business logic. Add a routing layer between business logic and the model to determine which models to use for each task type and to switch on failure.

    Configuration example:

    1. routes:
    2. code_generation:
    3. primary: model-a
    4. fallback: model-b
    5. summarization:
    6. primary: model-c
    7. fallback: model-a
    8. limits:
    9. daily_budget_cny: 300 # Daily budget limit, set according to actual needs
    10. request_timeout_s: 30
    11. max_output_tokens: 1024

    Pseudocode for routing logic:

    1. def call_with_route(task_type, messages):
    2. route = config["routes"][task_type]
    3. for model in [route["primary"], route["fallback"]]:
    4. if circuit_breaker.is_open(model):
    5. continue # Skip models currently in a circuit breaker state
    6. try:
    7. result = chat_with_retry(model, messages)
    8. circuit_breaker.record_success(model)
    9. return result
    10. except Exception:
    11. circuit_breaker.record_failure(model)
    12. raise RuntimeError(f"All candidate models for task {task_type} are unavailable")

    Circuit breaker rules can be set: if a model fails 10 consecutive times within 5 minutes, suspend calls to it for 10 minutes, then probe recovery with a small number of requests. Adjust thresholds based on the provider’s rate limit policies.

    2. Caching

    Cache results for identical requests. The cache key should include the model ID, Prompt content, and all parameters affecting the output. Two notes: First, even at low temperatures, model outputs may vary; caching ensures identical requests always return the same result, making it suitable only for scenarios requiring high consistency. Second, caches may contain user data, so expiration times and access scopes must be set.

    3. Cost Monitoring

    With parallel multi-model calls, costs can easily exceed expectations at month-end. Record the following fields for each call: Time, Task Type, Model ID, Input Tokens, Output Tokens, Duration, Status Code, and Estimated Cost.

    Costs are primarily affected by three factors, which need separate monitoring:

    • Output Tokens: In most pricing schemes,