Engineering a Multi-Model LLM Aggregation and Routing Platform

    This article walks through the engineering practices behind building an LLM aggregation and routing layer. It explains why model selection should be decoupled from business code, how to design a unified request abstraction with adapters, and how to use logical models, capability tags, and a candidate registry to switch backends without code changes. It also covers routing strategies such as weighted random, least in-flight requests, cost-first, quality tiering, and session affinity, along with fault tolerance, rate limiting, fallback chains, observability, governance, and a phased rollout plan.

    1. Why You Need a Model Aggregation and Routing Layer

    As large models evolve quickly, no single model can simultaneously satisfy competing goals such as complex reasoning, long context, low cost at high concurrency, and low-latency responses. A common engineering conclusion is to decouple model selection from business code and push it down into a platform capability, where a unified aggregation layer handles integration, scheduling, and governance.

    The aggregation and routing layer addresses four core problems:

    • Fragmented integration: Different model providers differ in authentication, request body structure, streaming protocols, and error code semantics. Integrating with them directly creates tight coupling and high migration costs.
    • Capability differences: Context windows, function calling, structured output, and multimodal input vary across models and need to be described uniformly through capability tags.
    • Cost and latency: Models differ significantly in cost per token and time to first token, so trade-offs must be made per scenario.
    • Stability: Any single backend can be rate-limited or become unstable, so retry, circuit breaking, and fallback paths are essential.

    2. Unified Integration Abstraction: Containing Differences in the Adapter Layer

    A practical approach is to combine a unified request model with adapters. Business code targets a single internal data structure, while adapters handle bidirectional translation.

    1. from dataclasses import dataclass, field
    2. from typing import List, Optional
    3. @dataclass
    4. class ChatMessage:
    5. role: str # system / user / assistant / tool
    6. content: str
    7. @dataclass
    8. class ChatRequest:
    9. messages: List[ChatMessage]
    10. model_alias: str # logical model name, not tied to a specific backend
    11. temperature: Optional[float] = 0.7
    12. max_tokens: Optional[int] = None
    13. stream: bool = False
    14. tools: List[dict] = field(default_factory=list)
    15. extra: dict = field(default_factory=dict) # provider-specific parameters
    16. @dataclass
    17. class ChatResponse:
    18. text: str
    19. finish_reason: str
    20. usage: dict # prompt/completion tokens
    21. provider: str
    22. latency_ms: int

    The abstraction layer should focus on normalizing three types of differences. First, error semantics: map rate limiting, authentication failures, content moderation blocks, and context length overflow to unified internal error codes. Second, streaming protocols: normalize incremental formats from different backends into “incremental text plus finish reason.” Third, usage statistics: provide a consistent basis for cost accounting and quota management.

    3. Capability Registry and Logical Models

    Business code should not be aware of specific backends. Instead, maintain a registry that maps a logical model to candidate backends, and tag each backend with its capabilities.

    1. logical_models:
    2. fast_chat:
    3. candidates:
    4. - backend: A
    5. weight: 70
    6. tags: [low_latency, cheap]
    7. - backend: B
    8. weight: 30
    9. tags: [low_latency]
    10. long_context:
    11. candidates:
    12. - backend: C
    13. weight: 100
    14. tags: [ctx_128k, reasoning]
    15. structured:
    16. candidates:
    17. - backend: D
    18. weight: 100
    19. tags: [json_mode, tool_call]

    Routing first applies hard constraint filtering (capabilities that must be satisfied, such as context length or tool calling support), then scores the remaining candidates according to a policy. Adding or retiring a backend then requires only a registry change, with zero changes to business code.

    4. Routing Strategy Design

    Common strategies can be combined:

    1. Weighted random: Distribute traffic by weight, suitable for canary releases and capacity sharing.
    2. Least in-flight requests: Prefer the candidate with the fewest current concurrent requests, which handles differences in backend processing time well.
    3. Cost-first: Among candidates that meet the quality threshold, choose the one with the lowest unit cost.
    4. Quality tiering: Use a small model for simple requests first, then escalate to a larger model when confidence is insufficient or complexity is high, forming a cascading call pattern.
    5. Session affinity: Route the same session to the same backend as much as possible to improve cache hit rates and experience consistency.

    A simplified scoring function example:

    1. def score(candidate, req, metrics):
    2. s = 0.0
    3. s -= candidate.cost_per_1k * req.estimated_tokens / 1000 * COST_W
    4. s += metrics.p95_latency(candidate.name) * (-LATENCY_W)
    5. s += candidate.quality_score * QUALITY_W
    6. if req.stream and "stream" not in candidate.tags:
    7. s -= 1e6
    8. return s

    5. Fault Tolerance, Rate Limiting, and Fallback

    Stability design should be systematic rather than a collection of scattered patches:

    • Retry: Retry only idempotent and recoverable errors (rate limiting, timeouts, 5xx) with exponential backoff plus jitter, and set an overall time limit to avoid request avalanches.
    • Circuit breaking: Track failure rates over a sliding window, briefly reject a backend once the threshold is exceeded, and probe for recovery during a half-open period.
    • Fallback chain: When the primary model is unavailable, try candidates with the same capability in order, and finally fall back to a “smaller model” or “cached answer/template response” to keep the chain running.
    • Quotas and priority: Set token buckets per tenant to guarantee quotas for critical workloads; degrade non-core traffic during peak periods.
    • Timeout budget: Set a budget for the entire chain and decrease it hop by hop to prevent slow calls at the end from dragging down the whole system.

    6. Cost, Observability, and Governance

    Much of the aggregation layer’s value comes from being measurable. At minimum, collect request volume, success rate, time to first token, total latency, token usage, cost per request, error distribution across backends, and the number of fallback triggers. These metrics support capacity planning, weight tuning, and cost accounting.

    Governance also requires attention to masking sensitive information in prompts and maintaining audit trails, pre- and post-checks for content safety, version management of prompt templates, and a regression evaluation set for model changes (running a fixed set of test cases to compare baselines before switching backends).

    1. First build the unified request/response structures and adapter layer, and consolidate existing calls into them.
    2. Introduce logical models and a capability registry to enable non-intrusive switching.
    3. Add retry, circuit breaking, fallback, and quotas.
    4. Connect metrics and logs to build a cost dashboard.
    5. Finally introduce cascading and intelligent scoring to continuously optimize the quality-to-cost ratio.

    When elastic compute and managed capabilities are needed, the aggregation layer can be hosted on general capabilities such as the container platform, message queue, object storage, log service, and monitoring and alerting offered by Baidu AI Cloud, achieving unified deployment, scaling, and operations.