Practical Guide to LLM Selection and Local API Integration
This guide outlines a structured approach to evaluating and selecting large language models (LLMs) for business tasks, setting up unified inference platforms, and integrating APIs locally. It covers defining evaluation criteria, managing API keys securely, implementing robust code with retry logic, and estimating costs effectively.
1. Define Evaluation Criteria Before Selection
Many developers select models based solely on parameter count or marketing claims. However, parameter count does not always correlate with actual performance, so selection should be centered around your specific business tasks. Public third-party leaderboards (such as those for code generation or web development capabilities) can serve as an initial screening tool, but you should record the leaderboard name, evaluation time, and task type. While some leading flagship models rank highly on these leaderboards, your final decision should always be based on your own test data.
It is recommended to use the following scoring table for horizontal comparison. Weights can be adjusted according to your business needs:
| Evaluation Dimension | Suggested Weight | Key Considerations |
|---|---|---|
| Code & Logic Capability | 30% | Generation quality in common languages, algorithm design, debugging ability |
| Context Window | 15% | Stability during long document Q&A and large codebase analysis |
| Latency & Throughput | 15% | Time To First Token (TTFT), tokens generated per second |
| Unit Price & Cost | 20% | Input/output unit price, additional consumption from retries |
| Compliance & Data | 20% | Data retention policies, regional requirements, auditing capabilities |
A practical approach is to prepare 30 to 50 real business questions as a fixed test set, call candidate models using the same prompt, score them by dimension, and then calculate the weighted total score.
2. Unified Inference Platforms: The “Model Supermarket”
In the past, testing different models required registering accounts and applying for quotas with multiple vendors. Today, some inference platforms offer a unified entry point, allowing developers to call multiple models with a single API key. These platforms are often referred to as “model supermarkets.” Initially focused on foreign open-source models, they have recently begun integrating models from various global and regional providers.
There are three main benefits to unified interfaces:
- They are typically compatible with mainstream API formats, meaning minimal client-side changes are needed when switching models.
- Billing and quotas are centrally managed, making cost control easier.
- Comparing models within the same environment is much more convenient.
However, unified interfaces have compatibility boundaries. The unified format usually only covers common fields. Capabilities such as tool calling, streaming output details, multimodal input, and single-call maximum output token limits may vary across different models. Before switching models, run the same test set to ensure that the output format and key functions work normally.
3. Integration Practices
The integration process is divided into three steps: obtaining credentials, configuring the client, and making code calls.
1. Create Keys and Security Management
Create keys in the “API Keys” or “Credential Management” module of the platform’s console, following these best practices:
- Create separate keys for different projects and environments; do not share keys across development, testing, and production.
- Set clear expiration dates, such as 90 days, and establish a regular rotation schedule.
- Grant only the necessary permissions and quotas; avoid using overly permissive general keys.
- If you suspect a leak, immediately revoke the key in the console and generate a new one.
- Store keys only in environment variables or a key management service. Do not hardcode them, print them to logs, or commit them to code repositories. Add
.envto your.gitignorefile.
Example of setting an environment variable:
export LLM_API_KEY="your-api-key-here"
2. Configure the Local Client
The client typically requires three parameters:
- API Key: The key generated in the previous step.
- Base URL: The access address provided in the platform console. The address in this article is just a placeholder and must be replaced with the actual console value. Most OpenAI-compatible clients will automatically append
/chat/completions, so the Base URL generally ends at/v1. If the client requires the full path, follow its documentation and do not duplicate the path. - Model ID: Copy this directly from the model list in the console. IDs are case-sensitive, so do not type them from memory. If the platform has not yet launched the latest version, test with the currently available version first; you will only need to change the ID later.
3. Code Example
The following example uses the requests library, reads environment variables, sets a timeout, and implements an exponential backoff retry mechanism for rate limiting and server-side errors. The Base URL and Model ID are placeholders and must be replaced with actual console values before running.
import osimport timeimport requestsAPI_KEY = os.getenv("LLM_API_KEY")BASE_URL = os.getenv("LLM_BASE_URL", "https://api.example.com/v1") # Placeholder, replace with console addressMODEL_ID = os.getenv("LLM_MODEL_ID", "your-model-id") # Placeholder, replace with console model IDif not API_KEY:raise SystemExit("Environment variable LLM_API_KEY not found")def chat(messages, max_retries=3):url = f"{BASE_URL.rstrip('/')}/chat/completions"headers = {"Authorization": f"Bearer {API_KEY}","Content-Type": "application/json",}payload = {"model": MODEL_ID,"messages": messages,"temperature": 0.7,"max_tokens": 1024,}for attempt in range(max_retries + 1):try:resp = requests.post(url, headers=headers, json=payload, timeout=60)except requests.RequestException:if attempt == max_retries:raisetime.sleep(2 ** attempt)continueif resp.status_code == 200:return resp.json()["choices"][0]["message"]["content"]retryable = resp.status_code in (429, 500, 502, 503, 504)if retryable and attempt < max_retries:time.sleep(2 ** attempt)continueraise RuntimeError(f"Request failed: {resp.status_code}, {resp.text}")if __name__ == "__main__":answer = chat([{"role": "system", "content": "You are a professional full-stack development assistant."},{"role": "user", "content": "Write a quicksort algorithm in Python and explain its time complexity."},])print(answer)
If the call fails, you can diagnose the cause based on the status code:
- 401: The key is invalid, expired, or revoked. Check for extra spaces and ensure the request header follows the
Bearer {key}format. - 404: The Base URL path is incorrect (e.g., missing or duplicating
/v1), or the Model ID does not exist or is not enabled. Verify the address and Model ID. - 400: The request parameters are invalid, such as
max_tokensexceeding the model’s limit. Adjust parameters based on the error message. - 429: Rate limit triggered or quota exhausted. Reduce concurrency, use exponential backoff retries, and check your balance and quota.
- 5xx: Server-side error. Retry later. If it persists, check the platform’s status page.
4. Cost Estimation and Budget Control
API fees are usually priced separately for input and output tokens, calculated as follows:
Single Call Cost = Input Token Count × Input Unit Price + Output Token Count × Output Unit Price
Assume a single request has 2,000 input tokens and 800 output tokens, with unit prices as published in the console. The actual cost must also account for two amplifying factors. First, retries will result in duplicate billing. Second, concurrent calls will multiply usage. It is recommended to set up daily or monthly budget alerts to maintain control over expenses.
