Enterprise LLM Selection and Inference Service Integration: A Practical Guide

    As the number of Large Language Models (LLMs) grows rapidly, enterprises face two critical questions: which model fits their business needs, and how to stably integrate multiple models into existing systems. This guide covers inference microservice architecture, evaluation dimensions for model selection, executable testing methods, a unified gateway implementation example, and a pre-launch checklist.

    The number of large language models is growing rapidly, with an increasing number of models topping the leaderboards. Enterprises need to answer two fundamental questions: which model is suitable for their business, and how to stably integrate multiple models into existing systems. This article starts with the architecture of inference microservices, provides evaluation dimensions for selection, executable testing methods, an implementation example of a unified gateway, and a pre-launch checklist.

    I. Inference Microservices: The Foundation of Multi-Model Management

    Before selecting models, it is necessary to determine the deployment form. A common practice is to encapsulate each LLM as an independent inference microservice. The service internally manages model weights, inference engines, and GPU scheduling, exposing only a unified HTTP interface to the outside. The calling method of the business system remains consistent; switching models only requires modifying routing configurations without altering business code.

    This decoupling reduces the complexity of multi-model management. The trade-off is the need to maintain a gateway, health checks, and a monitoring system, and the team must account for these costs in the total cost of ownership.

    II. How to Evaluate Models

    1. How to Evaluate Vertical Domain Capability?

    Leaderboard scores only indicate the general level of a model. Enterprises should validate models using their private test sets. It is recommended to collect 200 to 500 real business samples, each with a standard answer or scoring rubric. Taking frontend code generation as an example, three aspects can be checked: whether the generated code compiles, whether it renders the expected page, and whether it passes business unit tests. For tasks that cannot be automatically determined, arrange two reviewers to score independently and calculate consistency.

    Since leaderboard questions may have entered the model’s training data, leaderboard scores have limited reference value. Private test sets should be updated regularly and not published publicly.

    2. How to Stress Test Latency and Throughput?

    First, define the metrics. Time to First Token (TTFT) measures the time a user waits for the first token and has the greatest impact on interactive experience. Throughput should record two metrics simultaneously: output tokens per second (tokens/s) and completed requests per second (QPS).

    Test conditions must be fixed, otherwise, results cannot be compared:

    • Input length is divided into three tiers, e.g., 512, 2048, and 8192 tokens.
    • Output length is fixed, e.g., 256 tokens.
    • Concurrency is set to 1, 4, 16, and 64.
    • Each tier runs stably for at least 10 minutes, discarding the first 1 minute of warm-up data.
    • Record P50, P95, and P99; do not just look at averages. Averages can mask long-tail requests.

    The stress test report must also record hardware models, batch processing parameters, and quantization methods. Suppose the SLA for interactive Q&A requires a P95 TTFT of no more than 1.5 seconds. In that case, a model that exceeds this value under target concurrency does not meet the standard, even if its average latency is very low.

    3. How to Verify Long-Context Capability?

    Many models claim to support ultra-long contexts, but their retrieval capabilities for information at different positions vary greatly. You can use the “needle in a haystack” test to verify this, with the following steps:

    1. Insert an irrelevant fact into a long text, such as “The test key is ZX-4917”.
    2. Set the insertion position to 10%, 30%, 50%, 70%, and 90% of the text length.
    3. Use length gradients of 4K, 16K, 32K, and 128K tokens.
    4. Repeat each grid at least 20 times and record the exact match rate.
    5. If the accuracy in the middle section (30% to 70%) is 20 percentage points lower than both ends, it is judged as the “lost in the middle” phenomenon.

    Synthetic text often differs in difficulty from real business documents, so the test should be repeated using real documents.

    4. Comprehensive Selection Comparison Table

    The table below provides starting weights, which teams can adjust according to business priorities. Compliance is a veto item and does not participate in the weighted calculation.

    Dimension Starting Weight Scoring Method Pass Line Example
    Vertical task quality 35% Private test set pass rate Not less than 80%
    TTFT 20% P95 TTFT under target concurrency Not higher than 1.5s
    Throughput 15% Tokens/s and QPS per card Meets business peak
    Long context 15% Grid test accuracy 128K mid-section not less than 70%
    Unit cost 10% USD per million tokens Below budget cap
    Compliance 5% (veto) License, data residency requirements Must be fully met

    III. Unified API Gateway Implementation

    The gateway’s responsibility is to shield the differences between various model interfaces and handle timeouts, retries, and error mapping. The following example uses httpx to implement asynchronous calls. The upstream interface is assumed to be in JSON format, with the request body containing prompt and max_tokens, and the response body containing a text field. When integrating real models, you need to modify the payload and parsing logic according to the actual protocol.

    1. import asyncio
    2. import os
    3. from dataclasses import dataclass
    4. import httpx
    5. @dataclass
    6. class ModelEndpoint:
    7. name: str
    8. url: str # Full address of the inference service
    9. api_key_env: str # Environment variable name for the key, do not hardcode keys
    10. timeout: float = 30.0
    11. max_retries: int = 2
    12. class GatewayError(Exception):
    13. def __init__(self, code: str, message: str):
    14. super().__init__(message)
    15. self.code = code
    16. self.message = message
    17. class ModelGateway:
    18. def __init__(self, endpoints: dict[str, ModelEndpoint]):
    19. self.endpoints = endpoints
    20. self.client = httpx.AsyncClient()
    21. async def generate(self, model: str, prompt: str, max_tokens: int = 512) -> dict:
    22. ep = self.endpoints.get(model)
    23. if ep is None:
    24. raise GatewayError("MODEL_NOT_FOUND", f"Unregistered model: {model}")
    25. api_key = os.environ.get(ep.api_key_env, "")
    26. if not api_key:
    27. raise GatewayError("AUTH_MISSING", f"Missing environment variable {ep.api_key_env}")
    28. payload = {"prompt": prompt, "max_tokens": max_tokens}
    29. headers = {"Authorization": f"Bearer {api_key}"}
    30. last_error: GatewayError | None = None
    31. for attempt in range(ep.max_retries + 1):
    32. try:
    33. resp = await self.client.post(
    34. ep.url, json=payload, headers=headers, timeout=ep.timeout
    35. )
    36. # 429 and 5xx are treated as temporarily unavailable upstream, can retry after backoff
    37. if resp.status_code == 429 or resp.status_code >= 500:
    38. last_error = GatewayError("UPSTREAM_BUSY", f"Upstream returned {resp.status_code}")
    39. await asyncio.sleep(0.5 * (2 ** attempt))
    40. continue
    41. # Other non-200 statuses are not retried, return error directly
    42. if resp.status_code != 200:
    43. raise GatewayError(
    44. "UPSTREAM_REJECTED", f"Upstream returned {resp.status_code}: {resp.text[:200]}"
    45. )
    46. data = resp.json()
    47. return {"model": model, "text": data.get("text", ""), "status": "success"}
    48. except httpx.TimeoutException:
    49. last_error = GatewayError("TIMEOUT", "Inference request timed out")
    50. await asyncio.sleep(0.5 * (2 ** attempt))
    51. raise last_error
    52. async def close(self) -> None:
    53. await self.client.aclose()
    54. async def main() -> None:
    55. gateway = ModelGateway({
    56. "small-chat": ModelEndpoint(
    57. "small-chat", "http://small-model.internal/v1/generate", "SMALL_API_KEY"
    58. ),
    59. "flagship-code": ModelEndpoint(
    60. "flagship-code", "http://flagship.internal/v1/generate",
    61. "FLAGSHIP_API_KEY", timeout=120.0,
    62. ),
    63. })
    64. try:
    65. result = await gateway.generate("small-chat", "Introduce inference microservices in one sentence.")
    66. print(result)
    67. finally:
    68. await gateway.close()
    69. if __name__ == "__main__":
    70. asyncio.run(main())

    There are a few points to note in this implementation. Timeouts, rate limiting (429), and 5xx errors use exponential backoff for retries, while other errors are returned directly to avoid repeatedly retrying clear request errors. Error codes are categorized into MODEL_NOT_FOUND, AUTH_MISSING, UPSTREAM_BUSY, TIMEOUT, etc., allowing callers to decide on degradation or alerting based on these. Keys are read from environment variables and do not appear in code or logs.

    IV. Dynamic Routing Strategy

    Enterprises typically deploy both lightweight models and flagship models simultaneously. Simple Q&A can be routed to lightweight models to save costs, while complex code generation is routed to flagship models to ensure quality. Routing rules can be written in configuration files for easy adjustment:

    1. routing_rules: # Rules are matched in order, the first match takes effect
    2. - name: Long text task
    3. match: {input_tokens_gt: 32000}
    4. target: long-context-model
    5. fallback: flagship-code
    6. - name