AI gateway (hay LLM gateway / LLM proxy) là middleware giữa app và các LLM provider — tương tự API gateway truyền thống nhưng có domain knowledge về LLM.
Tại sao cần:
1. Multi-provider — một số endpoint dùng OpenAI, số khác Anthropic, self-host. Không muốn từng app integrate riêng.
2. Cost & usage tracking — attribute token/cost theo team/feature/user; budget alert.
3. Rate limit & quota — per team/user, không để team lẻ đốt hết quota.
4. Fallback & failover — provider down → switch sang backup.
5. Caching — semantic + prompt cache, giảm cost.
6. Guardrails — input/output filter, PII redaction trung tâm hoá.
7. Observability — trace, log, metrics thống nhất.
8. Security — API key quản lý ở gateway, app không có direct key.
9. Compliance — audit log, data residency enforcement.
10. A/B testing — route traffic giữa model/prompt version.
Kiến trúc:
┌─────────────┐ ┌──────────────────────────────┐ ┌─────────────┐
│ App A/B/C │────▶│ AI Gateway │────▶│ OpenAI │
└─────────────┘ │ │────▶│ Anthropic │
│ ┌──────────────────────┐ │────▶│ Google │
│ │ Auth & Tenant │ │────▶│ Self-host │
│ ├──────────────────────┤ │ │ (vLLM) │
│ │ Rate limit / quota │ │ └─────────────┘
│ ├──────────────────────┤ │
│ │ Input guardrail │ │
│ ├──────────────────────┤ │
│ │ Router / Fallback │ │
│ ├──────────────────────┤ │
│ │ Cache (semantic) │ │
│ ├──────────────────────┤ │
│ │ Retry / Circuit brk │ │
│ ├──────────────────────┤ │
│ │ Output guardrail │ │
│ ├──────────────────────┤ │
│ │ Observability │ │
│ └──────────────────────┘ │
└──────────────────────────────┘Components chi tiết:
1. OpenAI-compatible API — expose /v1/chat/completions, /v1/embeddings → app dùng OpenAI SDK không đổi code, chỉ đổi base_url.
2. Auth & tenant — API key per team/app; kiểm tra scope (team X chỉ được dùng model Y).
3. Rate limit & quota — Redis-based token bucket; daily/monthly cap per team; alert khi vượt X%.
4. Router:
- Static routing: request model=smart → map sang Claude 3.5 Sonnet.
- Cost routing: dùng model rẻ nhất đáp ứng quality.
- Cascade routing: try small model → fallback larger nếu low confidence.
- Semantic routing: classify query → pick specialized model.
- Capability routing: tool use → OpenAI/Anthropic (tốt hơn); pure text → cheap local.
5. Fallback chain — primary Anthropic → fallback OpenAI → fallback Gemini. Trigger: timeout, rate limit, 5xx.
6. Cache:
- Exact hash cache cho deterministic request (temperature=0).
- Semantic cache cho Q&A (embedding similarity).
- TTL theo use case.
- Cache trust level (không cache personalized, user-specific).
7. Guardrail (centralized):
- Input: prompt injection detect, PII redact, topic filter, toxicity.
- Output: PII leak scan, content moderation.
- Pluggable → dùng Llama Guard, Presidio, Azure Content Safety.
8. Observability:
- Trace ID xuyên suốt request.
- Prometheus metrics: RPS, latency, error rate, cost/minute per provider/team.
- Log to S3/BigQuery for analysis.
- Tích hợp Langfuse/LangSmith cho LLM-specific trace.
9. Policy engine — rule per team: "team HR không được gọi Anthropic với data có PII", "team Finance phải dùng Azure OpenAI (data residency EU)".
10. Retry, circuit breaker — per-provider health tracking; circuit trip sau N fail liên tục.
Options deployment:
Self-build:
- Node.js/Python service + Redis + Postgres (usage tracking).
- Deploy Kubernetes / Cloud Run / Lambda.
- Thời gian: vài sprint cho MVP.
Open-source:
- LiteLLM (Python) — gateway + SDK, supports 100+ provider, built-in fallback, caching, logging. De facto standard.
- OpenRouter — hosted gateway, unified API.
- Portkey (open-core) — more features, dashboard.
Commercial:
- Kong AI Gateway — enterprise, Kong platform.
- Cloudflare AI Gateway — edge-based, free tier rộng.
- Vercel AI Gateway — tích hợp sâu Vercel stack (Next.js, AI SDK).
- Portkey, Helicone, TrueFoundry, Langsmith Proxy — managed.
Best practices:
1. Versioned API ở gateway — breaking change upstream không ảnh hưởng app.
2. Multi-region — gateway gần app, reduce latency.
3. Graceful degradation — khi tất cả provider down, return cached/default response không lỗi.
4. Kill switch per model/feature — rollback fast.
5. Usage dashboard cho cost awareness trong org.
6. Don't be a bottleneck — gateway latency < 50ms; nếu nặng quá → scale out hoặc skip cho streaming path.
Anti-patterns:
- Gateway chặn streaming → phá UX chat.
- Tất cả app share 1 API key → không attribute được cost.
- Không cache → tốn tiền vô lý cho query lặp.
- Logging raw prompt/response có PII → compliance breach.
- Không có circuit breaker → 1 provider down kéo theo cả hệ thống.