Building a Unified LLM Gateway with Official APIs

    This article explains how to build a unified gateway that sits between your applications and multiple large language model (LLM) providers. It covers the overall architecture, protocol adaptation, key and routing boundaries, context compression, caching, deployment, security, and compliance checks—all based on officially authorized API keys and in accordance with each provider's terms of service.

    Building a Unified LLM Gateway with Official APIs

    Why You Need a Unified Gateway

    In many teams, different tools, editor plugins, automation scripts, and business services each talk to different model providers. Every provider has its own request format, streaming event structure, and tool-calling conventions. This means developers must re-adapt each new tool to every provider. Meanwhile, rate limits, concurrency caps, and quota systems vary widely—and when a single service hits a rate limit, the entire pipeline can break.

    A unified gateway acts as a lightweight proxy between the caller and the model services. Callers use one consistent interface, and the gateway translates requests to the upstream provider, handling authentication, rate limiting, logging, and monitoring in one place.

    A prerequisite: all calls use official API keys that you or your organization are authorized to hold, and you must comply with the relevant provider’s terms of service. Personal account credentials or web session tokens must not be used as upstream credentials for the gateway.

    Overall Architecture

    The gateway should be split into four modules:

    • Protocol Adaptation Layer: Exposes one or two standard interfaces (e.g., chat completion style and message style). Receives requests, translates them to upstream formats, and translates responses back.
    • Key and Routing Layer: Manages multiple authorized API keys or upstream endpoints within the organization. Chooses targets based on quotas, latency, and error rates. The goal is to respect quotas, not bypass them.
    • Context Management Layer: Compresses or summarizes long conversations and caches reusable intermediate results.
    • Management and Observability Layer: Provides key issuance, per-caller quotas, request logs, and metrics dashboards.

    The runtime can be a single-process service deployed on a container platform. For higher traffic, rate-limit counters, request logs, and circuit-breaker state must be stored in a shared store such as Redis or a relational database—otherwise multiple instances cannot stay consistent. For smaller single-instance deployments, local storage is acceptable, but backups must be planned and the process must be able to recover state after a restart.

    Protocol Adaptation

    The core of the adaptation layer is field mapping. For a chat-completion-style request, the table below shows fields that need translation:

    Caller Field Upstream Handling Notes
    messages with role “system” Extracted to the upstream system prompt field Multiple system messages are concatenated in order
    messages with role “user”, “assistant” Mapped to upstream role names Unrecognized roles are rejected with HTTP 400
    max_tokens Mapped to the upstream output limit parameter If it exceeds the upstream maximum, truncate and log a warning
    temperature, top_p Passed through with the same name or equivalent parameter If unsupported by the upstream, ignore and log
    tools Converted to the upstream tool definition format Parameter schemas must be validated field by field
    stream Determines whether incremental events are returned When true, enable the streaming conversion described below

    Authentication is also handled in this layer. The gateway receives the caller’s Bearer token and compares it against a locally issued key table. A failed check returns 401, a depleted quota returns 429, and an upstream failure returns 502 with a retryable marker.

    A simplified pseudocode example with error handling:

    1. function adaptRequest(req):
    2. if not validateApiKey(req.headers.authorization): return error(401)
    3. if not validateSchema(req.body): return error(400)
    4. system = join(req.messages where role == "system", "\n")
    5. upstreamReq = {
    6. system: system,
    7. messages: mapRoles(req.messages where role != "system"),
    8. maxTokens: min(req.max_tokens, UPSTREAM_LIMIT),
    9. tools: mapTools(req.tools)
    10. }
    11. return upstreamReq

    For streaming output, the gateway must parse each upstream event and repackage it as an SSE (Server-Sent Events) block starting with data:. Each incremental block should match the delta semantics expected by the caller. At the end of the stream, the gateway must send the termination marker data: [DONE]. If the upstream connection is interrupted, the gateway should send an error event instead of abruptly closing the connection. A caller receiving an incomplete output with no error message is extremely difficult to debug.

    Tool calls require bidirectional mapping. The upstream’s tool call intent must be converted to a standard tool_calls field, including the id, function name, and argument string. The client’s tool execution results must be mapped back to the upstream’s tool-result format using the id. If the upstream output includes reasoning or thinking tags, the adaptation layer should strip or preserve them based on configuration, ensuring that the remaining text is still complete and readable.

    Key and Routing Boundaries

    Scheduling across multiple API keys is a common need—for example, allocating quotas per project, or load balancing across multiple official projects within an organization. The following principles should be followed:

    • Use only authorized keys: Each key’s ownership, purpose, and quota must be documented.
    • Schedule by quota, do not bypass limits: The gateway reads upstream responses and rate-limit headers, then proactively slows down. When a rate limit is encountered, it must not switch to another account and retry endlessly.
    • Retry with a cap: The same request should be retried at most two or three times, with exponential backoff and random jitter.
    • Circuit breaker: If an endpoint’s error rate exceeds a threshold, pause scheduling to that endpoint for a period, then test with a small traffic after recovery.
    • Audit logging: Every scheduling choice, reason, and result should be logged.

    Explicitly prohibited practices include: using multiple personal accounts to rotate around rate limits or quotas, sharing or pooling login credentials of others, and reselling model access through the gateway. These behaviors typically violate provider terms of service and can lead to account bans. If a provider’s terms do not allow gateway-style invocation, stop that approach and use the provider’s official enterprise interface instead.

    Context Compression and Caching

    Long conversations eventually exceed the model’s context window. A common strategy is to set a trigger threshold—for example, when the historical messages exceed 70% of the model’s window, the earliest part of the conversation is sent to a model for summarization, replacing the original text, while keeping the most recent full turns.

    Compression must handle failures gracefully. If the summarization request times out or fails, the gateway should degrade to simply truncating the earliest messages and mark the event in logs, rather than failing the entire request.

    Caching can be split into two categories. Session-summary cache uses the session ID and a hash of the original messages as keys; it becomes invalid when the original messages change. For deterministic non-streaming requests, response caching is possible, but the cache key must include the model name, parameters, and a hash of the system prompt—to avoid mixing results from different configurations. Cache expiration must comply with the upstream’s data-use policy.

    Deployment and Security

    Deployment can be broken into three steps: prepare the runtime and dependencies, configure environment variables, and start the service behind a reverse proxy. Environment variables must at least include the gateway access key, upstream API keys, and the admin panel password. Example:

    1. export GATEWAY_API_KEY="replace with a randomly generated long string"
    2. export UPSTREAM_API_KEY="inject from a secrets manager, do not commit to the repository"
    3. export ADMIN_PASSWORD="use a password manager to generate"
    4. ./gateway --config ./config.yaml

    The configuration file should list the listening port, upstream endpoints, rate-limit parameters, and log level. Recommended security requirements:

    1. All keys must be injected via environment variables or a secrets manager, and must never be written into code or logs.
    2. Production services must be exposed only over HTTPS; TLS can be terminated at a reverse proxy.
    3. Each caller uses a separate key with its own quota, making revocation and accountability possible.
    4. Keys should be rotated periodically; old and new keys can coexist briefly during rotation.
    5. The gateway process runs with least privilege, opens only required ports, and logs are sanitized to avoid leaking prompt content.

    Pre-Launch Compliance Checklist

    Before production deployment, confirm the following:

    • Every upstream key is legally owned by you or your organization and is properly authorized.
    • The provider’s terms of service allow gateway or proxy invocation, and your use case is permitted.
    • Data handling by the caller meets company and user privacy requirements.
    • The gateway will not be used to bypass rate limits, quotas, or other usage restrictions.