DEV Community

Lee Jiang
Lee Jiang

Posted on Edited on Originally published at tokuse.com

How to Integrate Multiple AI Models in One API Gateway

Being locked into one model provider costs you twice: once when prices change, and again when a better model appears somewhere else and switching requires a code change. A gateway in front of several providers turns both problems into configuration work.

Try Tokuse: Create a free account and send your first request through one OpenAI-compatible endpoint.

Tokuse's current catalog covers the six families used in this guide: DeepSeek, Doubao, Kimi, GLM, Claude, and GPT. The gateway pattern is provider-neutral. Model availability, groups, and prices change, so check tokuse.com/pricing before you set a budget. For the DeepSeek cache model, read the 2026 DeepSeek cost guide.

What a gateway actually owns

A useful gateway is more than a proxy. It owns four things:

  1. Model routing. Map a task or an alias to a model ID and a fallback.
  2. Protocol adaptation. Accept an OpenAI-compatible request and, where needed, translate it to Anthropic-style Messages or another provider shape.
  3. Response normalization. Return one shape for text, tool calls, streaming events, usage, and errors.
  4. Control plane. Keep credentials, per-project keys, quotas, usage logs, and budget alerts in one place.

If the gateway only forwards bytes, the application still ends up with provider-specific branches. The value comes from moving those branches into one layer that you can test and observe.

Current model options and their routing roles

Family Example model Typical routing role
DeepSeek deepseek-flash classification, extraction, summaries, high-volume steps
DeepSeek deepseek-v4-pro harder reasoning when Flash misses the quality bar
Doubao doubao-seed-2-1-lite-260915 the cheapest default for chat and extraction
Doubao doubao-seed-2-1-turbo-260628 long input with very short output
Doubao doubao-seed-2-1-pro-260915 quality-sensitive analysis and agent steps
Kimi kimi-k3-1-pro-261024 long-context work that needs a frontier model
GLM glm-5-3-flash-260828 balanced general workloads
Claude claude-sonnet-5 coding, analysis, production agents
Claude claude-opus-5 difficult reasoning and high-stakes work
GPT gpt-6.1-terra capable everyday work at a lower rate
GPT gpt-6.1-sol balanced GPT routing
GPT gpt-6-astra the most demanding GPT workloads

Model names are routing labels, not a price list. For the live rate of any model in this table, use tokuse.com/pricing; group multipliers and availability change.

Price is a routing input, not a quality score. A cheap model that fails the evaluation is more expensive than a frontier model that passes on the first attempt, because retries, review time, and bad answers also cost money.

Architecture overview

Request router

Start with explicit rules, not a machine-learning classifier. You can add complexity later if the rules become unwieldy.

Signal Route
classification, extraction, short summary Doubao Lite or DeepSeek Flash
RAG answer, routine code, general chat GLM-5.3 Flash, GPT-6.1 Terra, Claude Sonnet 5
hard reasoning, long-horizon agent, high-stakes review Claude Opus 5, GPT-6 Astra, Kimi K3.1 Pro
timeout, 429, provider outage a fallback in the same tier, then the next tier

Keep every model name behind an alias. The application asks for chat-default or reasoning-hard; the gateway decides which model ID and provider serve it. A route change then becomes a configuration change rather than an application release.

Provider adapters

An adapter translates between the gateway's canonical request and the provider's API. At minimum, it should:

  • map the canonical message format to the provider's message format;
  • preserve tool-call IDs and JSON schemas;
  • translate stop reasons, usage fields, and streaming events;
  • normalize rate-limit and quota errors;
  • attach the provider request ID for debugging.

Version the adapters and test them against recorded fixtures. Provider APIs change, and an adapter regression looks like a model quality problem if you do not have contract tests.

Response normalizer

Return one response object regardless of provider. Include the text or tool calls, the finish reason, token usage, the model that actually served the request, the provider, and the request ID. Define an error taxonomy that the application can act on: authentication, rate limit, timeout, invalid request, content policy, and provider outage.

Do not leak raw provider error strings to every caller. They are useful in logs and useless in product logic.

Control plane

The control plane is where cost and access are managed. It should support per-project keys, usage tags, quotas, budget thresholds, audit logs, and a model catalog. If the gateway cannot answer "which project spent this money on which model", the cost controls are incomplete.

A minimal client

The application should not know which provider serves the request. It sends a model alias or a model ID to one endpoint:

import os

from openai import OpenAI

client = OpenAI(
    api_key=os.environ["TOKUSE_API_KEY"],
    base_url="https://tokuse.com/v1",
)

response = client.chat.completions.create(
    model="deepseek-flash",  # or a routing alias configured in the gateway
    messages=[
        {"role": "system", "content": "Return a compact JSON object."},
        {"role": "user", "content": "Classify this support ticket."},
    ],
    max_tokens=300,
)

print(response.choices[0].message.content)
Enter fullscreen mode Exit fullscreen mode

The same endpoint also exposes an Anthropic-compatible Messages path for clients that expect Claude-style requests. Keep the API key on the server, log the request ID and token usage, and redact prompt text by default if the logs are shared.

Failover without retry storms

Failover is easy to draw and easy to get wrong. A gateway that retries every failed request across every provider can turn a small outage into a large bill.

  • Set timeouts per route, not per provider.
  • Retry only requests that are safe to repeat, and cap the number of attempts.
  • Use exponential backoff with jitter.
  • Fall back by tier: if a cheap model is unavailable, try another cheap model before jumping to a frontier model.
  • Open a circuit breaker after repeated failures instead of sending traffic into a failing provider.
  • Log the route, fallback reason, and final model on every request.
  • Keep a canary route for a new model ID before moving all traffic to it.

A fallback that quietly upgrades every request to the most expensive model is worse than a clear error. Put a budget guard on the fallback path.

Cost control belongs in the gateway

  • Use per-project keys and usage tags so the bill maps to a product surface.
  • Set budget thresholds at the key and project level.
  • Use model aliases so a route change does not require a deployment.
  • Apply output limits and cache-friendly prompt structure at the adapter boundary.
  • Track cost per successful task, not just total spend.
  • Review the top routes by spend and the routes with the highest retry rate every week.

For a reproducible calculation, remember that the bill is not just the headline input rate. Output tokens often dominate. A model with a low input price and a high output price can lose to a more balanced model on a long-answer workload. Price your own token mix before deciding that one route is cheaper.

Migrate one endpoint at a time

  1. Inventory every model call: provider, model ID, token volume, latency, error rate, and monthly cost.
  2. Pick one low-risk, high-volume workload. Keep the old client behind a flag.
  3. Add the gateway route with the same model first. Compare output and usage on a fixed evaluation set.
  4. Move a small slice of traffic. Watch quality, latency, retries, and cost per successful task.
  5. Change one variable at a time: first the endpoint, then the model, then caching and output limits.
  6. Expand to the next workload only after the first one survives a full traffic cycle.

The most common failure is switching the endpoint and the model at the same time. If quality drops, you cannot tell which change caused it.

Best practices

  1. Always implement retry logic with a cap.
  2. Set reasonable timeouts per route.
  3. Monitor cost per successful task in real time or near real time.
  4. Version your adapters and test them against fixtures.
  5. Test failover on a schedule, not only after an incident.
  6. Keep a rollback path for every model route.
  7. Review the pricing page before each budget cycle.

A multi-model gateway provides flexibility, reliability, and cost control when the number of models, projects, or providers grows. Start with two routes and one clear fallback, then add models as evaluation data justifies them. Prices and model IDs change; use tokuse.com/pricing as the current catalog.

Top comments (0)