Architecture Design and API Cost Control for Multi-Model Aggregation Platforms

    A multi-model aggregation platform routes requests across multiple LLM providers through a unified gateway. This article explains how to design the gateway abstraction layer, route and schedule requests by task type, calculate and control token costs, and implement semantic caching, dynamic downgrade strategies, and cloud-native deployment.

    Why Build a Multi-Model Aggregation Platform

    No single model can cover all needs—code generation, logical reasoning, long-text processing, and multimodal interaction—at once. Integrating multiple model APIs directly creates three problems: inconsistent interface formats, hard-to-track costs, and API keys scattered across services. An aggregation platform centralizes all of this in a single gateway. This article covers gateway design, routing and scheduling, cost accounting, semantic caching, dynamic downgrade, and cloud-native deployment.

    Designing the Unified Gateway

    The gateway exposes a fixed set of RESTful endpoints to business services. The request body includes messages in a unified format, context parameters, task_type, and the desired model category. Before forwarding, the gateway performs authentication, rate limiting, and parameter validation. Failed validation returns a 400 immediately without consuming any model quota.

    Each underlying model has its own adapter. Adapters implement two methods: prepare_request converts the unified request into the model’s proprietary format, and parse_response converts the model’s output back into the unified structure. For example, one model may require a specific value for the role field, while another uses a different streaming event format. Adapters isolate these differences in one place so business code stays unchanged.

    Streaming responses are uniformly wrapped as SSE. The gateway sends a heartbeat comment line every 15 seconds to prevent intermediate proxies from closing idle connections. Error codes are mapped through a fixed table: upstream 429 becomes rate_limited, upstream timeout becomes upstream_timeout, and content moderation blocks become content_filtered. Business services only need to handle one set of error codes.

    API keys are never stored in code or config files. Keys are encrypted in a KMS, pulled on demand at gateway startup, and kept only in memory. Each key is granted minimal permissions—for example, access to a single specified model. Every key usage is written to an audit log. When a key returns 401 repeatedly, the gateway automatically marks it invalid and raises an alert. When rotating keys, add the new key and verify it works before retiring the old one.

    How to Select a Model for Each Request

    Routing is determined by looking up task_type. The table below is sample configuration; models are shown as generic placeholders, and actual values should be measured with your own business traffic.

    task_type Primary Model Fallback Order First-Token Latency Target Cost Tier
    Intent classification Small-parameter model Mid-size model 800 ms Low
    Code generation Code-specialized model General flagship model 3 s High
    Long-text summarization Long-context model General flagship model 5 s High

    When the primary model is unavailable, the scheduler switches along the fallback order. When multiple candidate models serve the same task, they can be ranked by a weighted score:

    Composite score = 0.5 × success rate + 0.3 × (1 − normalized latency) + 0.2 × (1 − normalized unit price)

    These weights are only a starting point. After launch, adjust them based on your business priorities for stability versus cost.

    Circuit breaker example rules: if a model has handled at least 20 requests in the last 60 seconds and its failure rate reaches 50%, the breaker opens for 30 seconds and rejects new requests for that model. After 30 seconds it enters a half-open state, letting through 3 probe requests. If all succeed, the breaker closes; any failure reopens it.

    Retry example rules: retry only on 429, 5xx, and timeouts, up to 2 times, with backoff of 200 ms and 400 ms plus random jitter. Non-streaming requests can be retried safely. For streaming requests, once content has been sent to the client, do not retry—otherwise the client receives garbled concatenated text. Each retry consumes tokens and should be tracked separately in monitoring.

    How to Calculate and Control Token Costs

    The cost of a single request is calculated as:

    Cost per request = input tokens × input price + output tokens × output price

    Input tokens include the system prompt, conversation history, and the current user message.