How dhananjaylab/llm-gateway works
Purpose and Entry Points
This is a FastAPI LLM gateway that exposes one OpenAI-style chat API over OpenAI, Anthropic, Ollama, and Gemini. It applies team policy, quotas, budget enforcement, provider routing/fallback, and observability before returning normalized or streamed responses.
Primary runtime entry point: app/main.py. Public and administrative surfaces are in app/api/v1_chat.py and app/api/admin.py.
Application Composition and Startup
app/main.py builds the FastAPI app, initializes Redis-backed state, provider registry, metrics/tracing, and lifespan bootstrapping for team configuration. It serves health/readiness and Prometheus metrics alongside API routes.
Settings and bootstrap configuration are centralized in app/core/config.py; static policy inputs come from config/teams.yaml, config/tiers.yaml, and config/pricing.yaml. Runtime mutations are persisted through the Redis-backed team store in app/core/team_store.py.
Request Admission and Policy Boundary
Chat requests enter app/api/v1_chat.py, where the gateway authenticates X-Gateway-API-Key, resolves a team, normalizes the request schema, and applies policy before provider execution.
Core controls include API-key authentication (app/core/auth.py), system-prompt/PII policy (app/core/policy.py), and audit logging for administrative changes (app/core/audit.py). The boundary is deliberate: clients see a unified schema (app/core/schema.py), while provider-specific requests remain internal.
Quotas, Cost, and Redis Atomicity
Rate and token limits, request priority, and dollar budgets are Redis-backed and use Lua scripts for atomic checks/updates. This prevents concurrency races across gateway instances.
Key stages: combined quota checking in app/ratelimit/combined.py, token/RPM/TPM controls in app/ratelimit/limiter.py, and budget reservation/reconciliation in app/ratelimit/budget.py. Atomic operations are implemented in scripts such as app/ratelimit/combined_check.lua and app/ratelimit/budget_increment.lua. Pricing calculation uses app/core/pricing.py with config/pricing.yaml.
Provider Abstraction and Routing
Provider adapters implement distinct upstream wire protocols behind a common interface. app/providers/registry.py resolves literal provider:model targets or tier chains; adapters in app/providers/openai_adapter.py, app/providers/anthropic_adapter.py, and app/providers/gemini_adapter.py translate request, response, error, and streaming formats.
Tier definitions in config/tiers.yaml permit policy-controlled model selection and fallback without exposing vendor protocol differences to callers.
Resilience Execution Path
The fallback router executes a resolved provider chain, classifies retryable provider failures, retries with backoff, and records circuit state. It supports both standard completion and streaming paths, including fallback before streaming output is committed.
Core implementation: app/resilience/fallback.py, app/resilience/retry.py, and Redis/Lua-backed circuit logic in app/resilience/circuit_breaker.py. Active/passive provider health assessment is in app/resilience/health.py.
Observability and Operating Stack
Each request and provider attempt is instrumented with OpenTelemetry spans and Prometheus metrics. Per-app instrumentation avoids process-global state, supporting repeated app construction in tests and embedded usage.
Metrics/tracing implementations are app/observability/metrics.py and app/observability/tracing.py. The containerized operating stack in docker-compose.yml includes Redis, Prometheus, Grafana, Alertmanager, and Jaeger; Jaeger v2 receives OTLP via deploy/jaeger/config.yaml.
Deterministic Demo, Integration, and Load Boundary
The default deployment routes adapters to a wire-compatible mock-provider service rather than vendor APIs. deploy/mock-providers/main.py implements provider-shaped endpoints, while deploy/mock-providers/chaos.py exposes live outage/latency injection used to exercise retries, fallback, and circuit behavior.
The gateway image is defined in Dockerfile; stack orchestration is docker-compose.yml. loadtest/k6_gateway_stress.js compares direct mock-provider latency with gateway latency and injects a mid-run provider outage.
Main entry points: v1_chat.py Chat API · main.py FastAPI app · fallback.py Fallback router · team_store.py Team store
Components 18
Gateway API
- FastAPI app · Builds the gateway and owns lifespan startup.
app/main.py - Chat API · OpenAI-style chat completion entry point.
app/api/v1_chat.py - Admin API · Administrative configuration surface.
app/api/admin.py - Unified schema · Client-facing normalized request and response contract.
app/core/schema.py
Policy & State
- Settings & static config · Loads team, tier, and pricing policy inputs.
app/core/config.py - Team store · Persists runtime team mutations in Redis.
app/core/team_store.py - Auth & policy · Authenticates keys and enforces prompt and PII rules.
app/core/auth.py - Redis · Shared state for teams, limits, budgets, and circuits.
- Quota & budget control · Atomically checks limits and reserves or reconciles spend.
app/ratelimit/combined.py - Pricing calculator · Calculates model usage cost from pricing policy.
app/core/pricing.py
Routing & Resilience
- Provider registry · Resolves explicit provider models or tier chains.
app/providers/registry.py - Fallback router · Executes provider chains for standard and streaming completions.
app/resilience/fallback.py - Retry & backoff · Classifies retryable failures and schedules retries.
app/resilience/retry.py - Circuit breaker · Uses Redis-backed circuit state to isolate unhealthy providers.
app/resilience/circuit_breaker.py
Provider Boundary
- Provider adapters · Translates OpenAI, Anthropic, Gemini, and Ollama protocols.
app/providers/openai_adapter.py - Mock providers · Wire-compatible default upstream with chaos injection.
deploy/mock-providers/main.py
Operating Stack
- Metrics & tracing · Per-app Prometheus metrics and OpenTelemetry spans.
app/observability/metrics.py - Operations stack · Runs Redis, Prometheus, Grafana, Alertmanager, and Jaeger.
docker-compose.yml
Connections 24
- FastAPI app → Chat API: mounts
- FastAPI app → Admin API: mounts
- FastAPI app → Settings & static config: loads
- FastAPI app → Team store: bootstraps
- FastAPI app → Metrics & tracing: initializes
- Chat API → Unified schema: normalizes
- Chat API → Auth & policy: authenticates and checks
- Chat API → Quota & budget control: admits request
- Chat API → Provider registry: resolves target
- Admin API → Team store: mutates teams
- Settings & static config → Team store: seeds configuration
- Team store → Redis: persists in
- Quota & budget control → Redis: atomic Lua state
- Quota & budget control → Pricing calculator: calculates spend
- Provider registry → Fallback router: provider chain
- Fallback router → Retry & backoff: retryable failures
- Fallback router → Circuit breaker: checks circuit
- Circuit breaker → Redis: stores circuit state
- Fallback router → Provider adapters: dispatches attempts
- Provider adapters → Mock providers: provider protocols
- Chat API → Metrics & tracing: request telemetry
- Fallback router → Metrics & tracing: attempt telemetry
- Operations stack → Redis: runs
- Operations stack → Metrics & tracing: scrapes and exports