Large Language Model Selection and Orchestration for Enterprise Developers
There is no single model that excels at everything. A more effective approach for enterprise teams is to define task types first, assign each task type to the most suitable model, and refine key outputs with human spot checks. This article covers evaluation dimensions, model-category comparisons, a multi-model collaboration workflow, routing code, and a compliance checklist. The model-category judgments are based on qualitative descriptions and have not been re-tested. Model versions, scores, and prices change with platform updates, so teams should test on their own datasets before choosing.
1. Define Evaluation Dimensions and Acceptance Metrics First
Before selecting a model, turn “how well it works” into measurable metrics. For each task type, prepare 100 to 200 samples from real business scenarios, and have two or more people label reference answers. The table below lists common dimensions. Teams should set their own thresholds according to business risk; the example acceptance lines are for reference only.
| Dimension | Core metric | Measurement method | Example acceptance line |
|---|---|---|---|
| Logical reasoning | Answer accuracy | Auto-score against reference answers; manually review disputed items | No lower than the baseline set by the team |
| Code generation | First-pass unit test rate | Run test cases in a sandbox | First-pass rate above 70% |
| Math calculation | Final answer accuracy, time per problem | Compare with reference answers and record end-to-end latency | Accuracy no lower than 95% |
| Long-text processing | Key-information recall | Extract planted facts at different input lengths | Report by length bucket and identify the point where performance degrades |
| Translation and polishing | Terminology hit rate, back-translation consistency | Check against glossary; back-translate with another model and compare key entities | Terminology hit rate no lower than 95%; manually review 10% of samples |
| Cost | Token cost per 1,000 tasks | Aggregate the usage field in responses |
Set according to budget |
| Stability | Timeout rate, 429 rate-limit ratio, error-code distribution | Load testing and production log statistics | Timeout rate below 1% |
| Compliance | Cross-border data transfer, usage restrictions in the terms of service | Review by legal and security teams | May go live only after approval |
2. Compare Mainstream Model Categories and Their Boundaries
The table below divides models into three categories based on the source article. The judgments are qualitative and should be validated with the metrics in Section 1 during selection.
| Model category | Tasks it handles well | Main cost | Known risks | Recommended use |
|---|---|---|---|---|
| General-purpose model | Multimodal input/output, routine instruction following | Lower per-call cost | May skip steps in deep conceptual analysis; text can be verbose | Routine engineering tasks, terminology-standardized draft generation |
| Long-context deep-reasoning model | Code generation, complex reasoning, long-document understanding | High token consumption and high call cost | Strict rate limits; cross-language word order may deviate from English conventions; lightweight versions need separate stability testing | Complex code and architecture discussions, refinement and rewriting |
| Math-optimized model | Math and algorithm problems, high-concurrency multimodal generation | Specialized capabilities require separate integration | Performance on non-math tasks needs separate evaluation | Numerical computation, batch multimodal requests |
There is no absolute ranking among the three categories. Every judgment should correspond to your own test results. If a model category shows no advantage on your test set, do not prioritize it just because of its category label.
3. Multi-Model Collaboration Workflow
1. Draft plus refinement
For long-text translation or polishing, first use a general-purpose model to generate a structured, terminology-consistent draft, then hand it to a deep-reasoning model for contextual rewriting. The first model handles terminology standards; the second handles context and word order. Callers should assemble prompts using the template below.
You are a senior technical translator. Follow these rules:1. Terminology must follow the glossary. For technical terms not in the glossary, retain the original English term and put it in parentheses.2. Use active voice; each sentence should express one idea.3. Use parentheses or separate clauses for supplementary explanations; do not use dashes.4. Output only the translation, not explanations.Glossary:{glossary}Source text:{source_text}
During acceptance, check terminology hit rate, consistency of key entities after back-translation, and manually review a sample by proportion.
2. Structured output constraints
For results that need to be parsed by programs, require the model to output a fixed JSON structure and validate the schema in code. If validation fails, retry once; if it still fails, route the case to manual handling. Do not rely on the model to follow the format on its own.
3. Write output standards as checkable items
When multiple calls with the same prompt produce large variance, turn the standards into automatically checkable items, such as field count, required terms, forbidden symbols, and maximum length. Checks should be performed by programs, not by people reading item by item.
4. Routing and Engineering Implementation
The routing layer sits behind a unified API gateway. Business code passes only the task type; the model ID is determined by configuration. The example below includes timeouts, retries, concurrency limits, fallback, audit logging, and a translation refinement flow. Model IDs are placeholders; replace them with the actual model names from your platform.
import osimport timeimport loggingimport hashlibimport threadingimport httpxlogger = logging.getLogger("model_router")logging.basicConfig(level=logging.INFO)API_BASE = os.environ["LLM_API_BASE"]API_KEY = os.environ["LLM_API_KEY"]TIMEOUT_SECONDS = float(os.environ.get("LLM_TIMEOUT", "30"))MAX_RETRIES = int(os.environ.get("LLM_MAX_RETRIES", "3"))MAX_CONCURRENCY = int(os.environ.get("LLM_MAX_CONCURRENCY", "8"))MAX_INPUT_CHARS = 20000_semaphore = threading.BoundedSemaphore(MAX_CONCURRENCY)ROUTE_TABLE = {"code_generation": ["reasoning-model", "general-model"],"complex_reasoning": ["reasoning-model", "general-model"],"math_calculation": ["math-model", "reasoning-model"],"general": ["general-model"],}REFINE_PROMPT = """Rewrite the following translation so that the word order follows English conventions without changing terminology or facts.Output only the rewritten translation.Translation:{draft}"""class RetryableError(Exception):passdef call_model(model, prompt):payload = {"model": model, "messages": [{"role": "user", "content": prompt}]}headers = {"Authorization": f"Bearer {API_KEY}"}last_error = Nonefor attempt in range(MAX_RETRIES):try:with _semaphore:resp = httpx.post(f"{API_BASE}/chat/completions",json=payload,headers=headers,timeout=TIMEOUT_SECONDS,)if resp.status_code == 429 or resp.status_code >= 500:raise RetryableError(f"status {resp.status_code}")resp.raise_for_status()return resp.json()["choices"][0]["message"]["content"]except (httpx.TimeoutException, httpx.TransportError, RetryableError) as exc:last_error = excif attempt < MAX_RETRIES - 1:wait = 2 ** attemptlogger.warning("model=%s attempt=%d failed: %s, retry in %ds",model, attempt + 1, exc, wait)time.sleep(wait)raise RuntimeError(f"model {model} failed after {MAX_RETRIES} attempts") from last_errordef audit_log(task_type, model, prompt, output):logger.info("audit task=%s model=%s prompt_sha256=%s output_chars=%d",task_type, model,hashlib.sha256(prompt.encode("utf-8")).hexdigest(),len(output))def translate_with_refinement(prompt):draft = call_model("general-model", prompt)audit_log("translation", "general-model", prompt, draft)try:final = call_model("reasoning-model", REFINE_PROMPT.format(draft=draft))audit_log("translation", "reasoning-model", draft, final)return finalexcept RuntimeError as exc:logger.error("refinement failed, returning draft: %s", exc)return draftdef route_request(task_type, text):if len(text) > MAX_INPUT_CHARS:raise ValueError("Input exceeds the length limit; please split it into segments")if task_type == "translation":return translate_with_refinement(text)candidates = ROUTE_TABLE.get(task_type, ROUTE_TABLE["general"])last_error = Nonefor model in candidates:try:output = call_model(model, text)audit_log(task_type, model, text, output)return outputexcept (RuntimeError, httpx.HTTPStatusError) as exc:last_error = exclogger.error("model=%s failed, trying next candidate: %s", model, exc)raise RuntimeError("All candidate models failed") from last_errorif __name__ == "__main__":print(route_request("general", "Explain in one sentence what prompt engineering is."))
Several implementation points need explanation:
- The API key is read only from environment variables. If configuration is missing, the program fails at startup, avoiding running with incorrect configuration.
- Timeout is controlled by
LLM_TIMEOUT. Timeouts and network errors are retried with exponential backoff. 429 and 5xx responses are treated as retryable errors; other 4xx responses are raised directly to avoid invalid repeated calls. In production, when handling 429, the implementation should also read theRetry-Afterresponse header. - Concurrency is limited by a semaphore to prevent bursts of requests from triggering platform rate limits.
- Logs record only the SHA-256 hash of the prompt and the output length, not the original text. If the business needs to trace the original text, it should be written to access-controlled storage and redacted first.
- For cost control, you can accumulate the
usagefield from responses incall_modeland calculate daily statistics. When approaching the budget limit, send an alert and switch non-critical tasks to lower-cost models.
5. Risk and Compliance Checklist
- Terms of service: Confirm whether the platform allows enterprise use. When usage exceeds the quota, apply for quota or upgrade through official channels. Do not bypass rate limits through shared accounts or rotating accounts; this may violate the terms of service and create account suspension risks.
- Data boundaries: Whether customer data, personal information, and internal code can be sent to external models must be confirmed first by legal and security teams. Redact before sending.
- Degradation plan: When the primary model is rate-limited or unavailable, you can queue the request, switch to a lower-cost model, or return “try again later.” During degradation, inform users of the result source and explain possible quality differences.
- Output review: Terminology, code, and numerical results need human or automated test review and cannot be published directly.
6. Implementation Checklist
- Each task type has labeled samples and acceptance metrics.
- Model IDs, timeouts, retry counts, and concurrency limits are in configuration, not hardcoded.
- API keys come from environment variables or a secrets manager and are rotated regularly.
- Each task type has at least one fallback model, and the fallback path has been tested.
- Track cost, timeout rate, and rate-limit ratio weekly, and adjust the routing table when metrics are abnormal.
Selection conclusions should be based on your own test results, and you should re-test periodically after model version updates.
