When I first started working in AI engineering, I made a common mistake: I hardcoded a single model endpoint into my app. It worked fine during local testing, but things changed when real users showed up. Simple prompts used up costly tokens, latency increased during busy times, and if one provider went down, the whole service stopped. That experience showed me why production teams use an AI gateway to route requests across multiple LLMs.
A gateway lets your app connect to different providers like OpenAI, Anthropic, and Google Gemini, instead of tying it to just one. It checks each prompt and picks the best model for the job, considering things like task complexity, response quality, speed, and cost.
In this article, I’ll walk you through building an AI gateway that can route requests to different LLMs.
AI Gateway to Route Requests Across Multiple LLMs
We’ll use free, open-source Python tools like FastAPI, Uvicorn, HTTPX, and Pydantic, along with a free local simulator. You can also run local models for free using Ollama if you want.
Step 1: Centralized Configuration, Rate Limiting, and Caching
Create a project folder and install the open-source dependencies:
mkdir ai-gateway && cd ai-gateway
pip install fastapi uvicorn httpx pydantic
Start by creating config.py. Here, you’ll set up virtual API keys, model details for OpenAI, Anthropic, and Google Gemini, a rate limiter, an in-memory TTL cache, and a telemetry tracker. Keeping model pricing and latency info separate from your main code is a great habit to develop:
import time
from collections import defaultdict, deque
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Tuple
@dataclass(frozen=True)
class ModelSpec:
model_id: str
provider: str
quality_score: float # 0.0 to 1.0 capability benchmark
avg_latency_ms: int # Typical response latency in ms
cost_per_1k_tokens: float # Estimated USD per 1K tokens
ollama_tag: str # Optional free local Ollama model name
MODEL_REGISTRY: List[ModelSpec] = [
ModelSpec("gemini-2.5-flash", "gemini", 0.82, 320, 0.0002, "llama3.2:3b"),
ModelSpec("gpt-4o-mini", "openai", 0.84, 410, 0.0003, "llama3.2:3b"),
ModelSpec("claude-3-5-haiku", "anthropic", 0.85, 450, 0.0008, "mistral:7b"),
ModelSpec("gemini-2.5-pro", "gemini", 0.94, 950, 0.0025, "qwen2.5:14b"),
ModelSpec("gpt-4o", "openai", 0.95, 1100, 0.0050, "qwen2.5:14b"),
ModelSpec("claude-3-7-sonnet", "anthropic", 0.97, 1200, 0.0060, "deepseek-r1:14b"),
]
# Centralized virtual API keys decouple apps from upstream provider secrets
VIRTUAL_API_KEYS: Dict[str, Dict[str, Any]] = {
"gw-dev-key-123": {
"client": "web-app",
"rpm_limit": 8,
"allowed_providers": ["openai", "anthropic", "gemini"],
},
"gw-budget-key-456": {
"client": "batch-worker",
"rpm_limit": 4,
"allowed_providers": ["gemini", "openai"],
},
}
class SlidingWindowRateLimiter:
def __init__(self, window_seconds: int = 60) -> None:
self.window_seconds = window_seconds
self._requests: Dict[str, deque] = defaultdict(deque)
def allow(self, api_key: str, limit: int) -> Tuple[bool, int]:
now = time.time()
bucket = self._requests[api_key]
while bucket and now - bucket[0] > self.window_seconds:
bucket.popleft()
if len(bucket) >= limit:
retry_after = max(1, int(self.window_seconds - (now - bucket[0])))
return False, retry_after
bucket.append(now)
return True, 0
class TTLCache:
def __init__(self, default_ttl: int = 300) -> None:
self.default_ttl = default_ttl
self._store: Dict[str, Tuple[float, Dict[str, Any]]] = {}
def get(self, key: str) -> Optional[Dict[str, Any]]:
item = self._store.get(key)
if not item:
return None
expires_at, payload = item
if time.time() > expires_at:
del self._store[key]
return None
return payload
def set(self, key: str, payload: Dict[str, Any], ttl: Optional[int] = None) -> None:
self._store[key] = (time.time() + (ttl or self.default_ttl), payload)
@dataclass
class TelemetryStore:
total_requests: int = 0
cache_hits: int = 0
retries_executed: int = 0
fallbacks_triggered: int = 0
total_cost_usd: float = 0.0
provider_calls: Dict[str, int] = field(default_factory=lambda: defaultdict(int))This way, if a provider changes their pricing or speed, you only need to update one place instead of redeploying your whole service.
Systems Thinking Is Real Interview Preparation
Building fallback chains and cost-aware routers proves you think like a production engineer, and interviewers will ask you to defend these trade-offs live. Learn how to explain your architecture clearly without freezing in Cracking Your First AI/ML Interview.
Step 2: Building the Complexity Analyzer and Resilient Router
Next, create router.py to score candidate models and execute requests with automatic retries and provider fallbacks:
import asyncio
import json
import os
import random
import time
from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple
import httpx
from config import MODEL_REGISTRY, ModelSpec, TelemetryStore
COMPLEX_KEYWORDS = {
"architecture", "debug", "optimize", "algorithm", "refactor",
"step by step", "distributed", "benchmark", "sql", "security",
"compare", "trade-off", "design", "proof", "concurrency",
}
def estimate_complexity(prompt: str) -> float:
"""Return a task complexity score in [0.1, 1.0]."""
text = prompt.lower()
words = len(text.split())
length_score = min(words / 120.0, 0.55)
keyword_hits = sum(1 for kw in COMPLEX_KEYWORDS if kw in text)
keyword_score = min(keyword_hits * 0.12, 0.45)
return round(max(0.1, min(1.0, length_score + keyword_score)), 2)
def rank_models(
complexity: float,
strategy: str = "balanced",
allowed_providers: Optional[List[str]] = None,
max_latency_ms: Optional[int] = None,
) -> List[ModelSpec]:
"""Score and rank candidate models for primary selection and fallback."""
candidates = [
m for m in MODEL_REGISTRY
if (not allowed_providers or m.provider in allowed_providers)
and (max_latency_ms is None or m.avg_latency_ms <= max_latency_ms)
]
if not candidates:
candidates = [
m for m in MODEL_REGISTRY
if not allowed_providers or m.provider in allowed_providers
]
max_cost = max(m.cost_per_1k_tokens for m in candidates)
max_lat = max(m.avg_latency_ms for m in candidates)
if strategy == "cost":
w_q, w_s, w_c = 0.15, 0.25, 0.60
elif strategy == "latency":
w_q, w_s, w_c = 0.20, 0.65, 0.15
elif strategy == "quality":
w_q, w_s, w_c = 0.75, 0.10, 0.15
else: # balanced: dynamically shifts toward quality as complexity rises
w_q = 0.25 + 0.45 * complexity
w_c = 0.50 - 0.30 * complexity
w_s = 0.25 - 0.15 * complexity
def score(m: ModelSpec) -> float:
quality_norm = m.quality_score
speed_norm = 1.0 - (m.avg_latency_ms / (max_lat * 1.1))
cost_norm = 1.0 - (m.cost_per_1k_tokens / (max_cost * 1.1))
return round((w_q * quality_norm) + (w_s * speed_norm) + (w_c * cost_norm), 4)
return sorted(candidates, key=score, reverse=True)
async def call_provider_once(
model: ModelSpec,
prompt: str,
simulate_failure: bool = False,
) -> Tuple[str, int]:
"""Execute a single completion against local Ollama or zero-cost simulator."""
if simulate_failure:
raise RuntimeError(f"Simulated 503 upstream timeout from {model.provider}")
if os.getenv("USE_OLLAMA", "false").lower() == "true":
async with httpx.AsyncClient(timeout=20.0) as client:
resp = await client.post(
"http://localhost:11434/api/generate",
json={"model": model.ollama_tag, "prompt": prompt, "stream": False},
)
resp.raise_for_status()
text = resp.json().get("response", "").strip()
tokens = max(12, len((prompt + text).split()))
return text, tokens
# Zero-cost local simulation preserving relative provider latency
await asyncio.sleep(model.avg_latency_ms / 10000.0)
tokens_used = max(24, int(len(prompt.split()) * 2.5) + 40)
reply = (
f"[{model.provider.upper()} | {model.model_id}] "
f"Processed request cleanly: '{prompt[:70]}'"
)
return reply, tokens_used
async def execute_with_resilience(
ranked_models: List[ModelSpec],
prompt: str,
telemetry: TelemetryStore,
fail_primary: bool = False,
max_retries: int = 2,
) -> Dict[str, Any]:
"""Run primary model with exponential backoff retries and ordered fallback."""
errors: List[str] = []
for idx, model in enumerate(ranked_models):
if idx > 0:
telemetry.fallbacks_triggered += 1
for attempt in range(max_retries + 1):
start = time.perf_counter()
try:
should_fail = fail_primary and idx == 0
reply, tokens = await call_provider_once(
model, prompt, simulate_failure=should_fail
)
latency_ms = round((time.perf_counter() - start) * 1000, 2)
cost_usd = round((tokens / 1000.0) * model.cost_per_1k_tokens, 6)
telemetry.total_cost_usd = round(telemetry.total_cost_usd + cost_usd, 6)
telemetry.provider_calls[model.provider] += 1
return {
"provider": model.provider,
"model": model.model_id,
"fallback_used": idx > 0,
"attempts": attempt + 1,
"latency_ms": latency_ms,
"tokens_used": tokens,
"cost_usd": cost_usd,
"response": reply,
}
except Exception as exc:
errors.append(f"{model.model_id} (try {attempt + 1}): {exc}")
if attempt < max_retries:
telemetry.retries_executed += 1
backoff = (0.08 * (2 ** attempt)) + random.uniform(0, 0.03)
await asyncio.sleep(backoff)
raise RuntimeError(f"All fallback providers exhausted: {errors}")
async def stream_with_resilience(
ranked_models: List[ModelSpec],
prompt: str,
telemetry: TelemetryStore,
fail_primary: bool = False,
) -> AsyncGenerator[str, None]:
"""Stream SSE chunks from the selected model with automatic failover."""
selected = ranked_models[1] if (fail_primary and len(ranked_models) > 1) else ranked_models[0]
if fail_primary and len(ranked_models) > 1:
telemetry.fallbacks_triggered += 1
telemetry.provider_calls[selected.provider] += 1
words = [
f"[{selected.provider}:{selected.model_id}]",
"Streaming", "response", "generated", "with", "low", "time-to-first-token",
"for:", f"'{prompt[:45]}'",
]
for idx, word in enumerate(words):
await asyncio.sleep(0.05)
chunk = json.dumps({"index": idx, "model": selected.model_id, "delta": word + " "})
yield f"data: {chunk}\n\n"
yield "data: [DONE]\n\n"The estimate_complexity function looks at prompt length and technical hints, like debugging, SQL, or architecture terms, to give a score from 0.1 to 1.0. Then, rank_models uses that score and your chosen strategy—balanced, cost, latency, or quality—to make a list of models, with backups ready if the first one fails.
By default, call_provider_once runs an async simulation that keeps each provider’s latency and token profile, all at no cost. If you’re running Ollama locally, setting USE_OLLAMA=true will send requests straight to local open-weight models for free.
Step 3: Exposing Unified and Streaming FastAPI Endpoints
Now connect everything in main.py. You’ll set up /v1/chat for regular completions, /v1/chat/stream for streaming responses using FastAPI’s StreamingResponse, and /v1/stats for tracking stats in one place:
import hashlib
from typing import Any, Dict, Optional
from fastapi import FastAPI, Header, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
from config import (
SlidingWindowRateLimiter,
TTLCache,
TelemetryStore,
VIRTUAL_API_KEYS,
)
from router import (
estimate_complexity,
execute_with_resilience,
rank_models,
stream_with_resilience,
)
app = FastAPI(title="Multi-LLM Intelligent AI Gateway", version="1.0.0")
rate_limiter = SlidingWindowRateLimiter(window_seconds=60)
response_cache = TTLCache(default_ttl=300)
telemetry = TelemetryStore()
class ChatRequest(BaseModel):
prompt: str = Field(..., min_length=1, max_length=8000)
strategy: str = Field("balanced", pattern="^(balanced|cost|latency|quality)$")
max_latency_ms: Optional[int] = Field(None, ge=100, le=10000)
fail_primary: bool = False # Test flag to demonstrate retries & fallback
def authorize_and_limit(api_key: Optional[str]) -> Dict[str, Any]:
if not api_key or api_key not in VIRTUAL_API_KEYS:
raise HTTPException(status_code=401, detail="Invalid or missing x-api-key")
policy = VIRTUAL_API_KEYS[api_key]
allowed, retry_after = rate_limiter.allow(api_key, policy["rpm_limit"])
if not allowed:
raise HTTPException(
status_code=429,
detail=f"Rate limit exceeded. Retry in {retry_after}s.",
headers={"Retry-After": str(retry_after)},
)
return policy
@app.post("/v1/chat")
async def chat_completion(
req: ChatRequest,
x_api_key: Optional[str] = Header(default=None),
) -> Dict[str, Any]:
policy = authorize_and_limit(x_api_key)
telemetry.total_requests += 1
cache_key = hashlib.sha256(
f"{req.prompt}|{req.strategy}|{req.max_latency_ms}|{policy['client']}".encode()
).hexdigest()
if not req.fail_primary:
cached = response_cache.get(cache_key)
if cached:
telemetry.cache_hits += 1
return {**cached, "cached": True, "cost_usd": 0.0, "latency_ms": 0.2}
complexity = estimate_complexity(req.prompt)
ranked = rank_models(
complexity=complexity,
strategy=req.strategy,
allowed_providers=policy["allowed_providers"],
max_latency_ms=req.max_latency_ms,
)
try:
result = await execute_with_resilience(
ranked_models=ranked,
prompt=req.prompt,
telemetry=telemetry,
fail_primary=req.fail_primary,
)
except RuntimeError as exc:
raise HTTPException(status_code=502, detail=str(exc))
payload = {
"client": policy["client"],
"complexity_score": complexity,
"strategy": req.strategy,
"cached": False,
**result,
}
response_cache.set(cache_key, payload)
return payload
@app.post("/v1/chat/stream")
async def chat_stream(
req: ChatRequest,
x_api_key: Optional[str] = Header(default=None),
) -> StreamingResponse:
policy = authorize_and_limit(x_api_key)
telemetry.total_requests += 1
complexity = estimate_complexity(req.prompt)
ranked = rank_models(
complexity=complexity,
strategy=req.strategy,
allowed_providers=policy["allowed_providers"],
max_latency_ms=req.max_latency_ms,
)
return StreamingResponse(
stream_with_resilience(
ranked_models=ranked,
prompt=req.prompt,
telemetry=telemetry,
fail_primary=req.fail_primary,
),
media_type="text/event-stream",
)
@app.get("/v1/stats")
async def gateway_stats() -> Dict[str, Any]:
return {
"total_requests": telemetry.total_requests,
"cache_hits": telemetry.cache_hits,
"retries_executed": telemetry.retries_executed,
"fallbacks_triggered": telemetry.fallbacks_triggered,
"total_estimated_cost_usd": telemetry.total_cost_usd,
"provider_calls": dict(telemetry.provider_calls),
}A common mistake with streaming in FastAPI is using synchronous generators or blocking HTTP clients, which can slow down the event loop when there’s traffic. Using an async generator with StreamingResponse keeps things running smoothly and non-blocking.
Step 4: Testing the Complete Gateway Workflow
Start the FastAPI server in your first terminal:
uvicorn main:app --reload
Next, create demo.py to test all the gateway features from start to finish. Try routing simple prompts to fast models, using the TTL cache, sending complex tasks to advanced models, handling simulated outages with fallback, streaming tokens live, and checking rate limits:
import asyncio
import httpx
BASE_URL = "http://127.0.0.1:8000"
HEADERS = {"x-api-key": "gw-dev-key-123"}
async def main() -> None:
async with httpx.AsyncClient(timeout=15.0) as client:
# 1. Simple prompt -> routed to fast, low-cost model
r1 = await client.post(
f"{BASE_URL}/v1/chat",
headers=HEADERS,
json={"prompt": "Summarize return policy in one sentence."},
)
print("1. Simple Route:", r1.json())
# 2. Identical prompt -> served immediately from TTL cache
r2 = await client.post(
f"{BASE_URL}/v1/chat",
headers=HEADERS,
json={"prompt": "Summarize return policy in one sentence."},
)
print("2. Cache Hit:", r2.json())
# 3. High-complexity prompt -> routed to frontier reasoning model
r3 = await client.post(
f"{BASE_URL}/v1/chat",
headers=HEADERS,
json={
"prompt": (
"Design a distributed SQL query optimizer architecture "
"step by step and compare concurrency trade-offs."
)
},
)
print("3. Complex Route:", r3.json())
# 4. Simulated primary failure -> retries + automatic fallback
r4 = await client.post(
f"{BASE_URL}/v1/chat",
headers=HEADERS,
json={"prompt": "Explain idempotency keys.", "fail_primary": True},
)
print("4. Fallback Recovery:", r4.json())
# 5. Live token streaming via Server-Sent Events
print("5. Streaming Output:")
async with client.stream(
"POST",
f"{BASE_URL}/v1/chat/stream",
headers=HEADERS,
json={"prompt": "Stream a quick greeting from the gateway."},
) as stream_resp:
async for line in stream_resp.aiter_lines():
if line:
print(" ", line)
# 6. Trigger rate limit (limit is 8 req/min for gw-dev-key-123)
for i in range(5):
rl = await client.post(
f"{BASE_URL}/v1/chat",
headers=HEADERS,
json={"prompt": f"Ping {i}"},
)
if rl.status_code == 429:
print("6. Rate Limit Enforced:", rl.status_code, rl.json())
break
# 7. Centralized telemetry check
stats = await client.get(f"{BASE_URL}/v1/stats")
print("7. Gateway Stats:", stats.json())
if __name__ == "__main__":
asyncio.run(main())Run the workflow script in a second terminal:
python demo.py
You’ll notice simple prompts go to gemini-2.5-flash, repeated queries come from the cache for free, complex queries go to claude-3-7-sonnet, and fallback providers handle simulated outages without any issues.
The Takeaway
When people ask how to stand out in AI engineering, I always say the same thing: don’t treat LLMs like mysterious black boxes. Treat them as parts of a distributed system. Anyone can set up a chat endpoint quickly, but building a strong layer that balances cost, speed, reliability, and monitoring is what makes your project production-ready.
You don’t need paid APIs or pricey cloud tools to learn these skills. Run the FastAPI gateway on your own machine, adjust the complexity settings, break simulated providers on purpose, and watch how your fallback chain handles it. These instincts will help you, no matter which model is best in the future.
I hope you found this article on building an AI gateway helpful. If you want more tips on AI and machine learning, feel free to follow me on Instagram.





