From 610b6c3367e407cb6323eb012b0f3f894da61649 Mon Sep 17 00:00:00 2001 From: Anibal Angulo Date: Fri, 6 Mar 2026 16:26:25 +0000 Subject: [PATCH] Add deployment guides --- Dockerfile | 24 +- README.md | 764 +++++++++++++++++++++---- docs/DOCKER_DEPLOYMENT.md | 471 ++++++++++++++++ docs/README.md | 74 +++ k8s/README.md | 1122 +++++++++++++++++++++++++++---------- 5 files changed, 2051 insertions(+), 404 deletions(-) create mode 100644 docs/DOCKER_DEPLOYMENT.md create mode 100644 docs/README.md diff --git a/Dockerfile b/Dockerfile index 51d348e..0914e82 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,9 +1,23 @@ # Multi-stage build for Go LLM Gateway -# Stage 1: Build the Go binary + +# Stage 1: Build the frontend +FROM node:18-alpine AS frontend-builder + +WORKDIR /frontend + +# Copy package files for better caching +COPY frontend/admin/package*.json ./ +RUN npm ci --only=production + +# Copy frontend source and build +COPY frontend/admin/ ./ +RUN npm run build + +# Stage 2: Build the Go binary FROM golang:alpine AS builder # Install build dependencies -RUN apk add --no-cache git ca-certificates tzdata +RUN apk add --no-cache git ca-certificates tzdata gcc musl-dev WORKDIR /build @@ -14,10 +28,12 @@ RUN go mod download # Copy source code COPY . . +# Copy pre-built frontend assets from stage 1 +COPY --from=frontend-builder /frontend/dist ./internal/admin/dist + # Build the binary with optimizations # CGO is required for SQLite support -RUN apk add --no-cache gcc musl-dev && \ - CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build \ +RUN CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build \ -ldflags='-w -s -extldflags "-static"' \ -a -installsuffix cgo \ -o gateway \ diff --git a/README.md b/README.md index f0781d4..26290d9 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,47 @@ # latticelm +> A production-ready LLM proxy gateway written in Go with enterprise features + +## Table of Contents + +- [Overview](#overview) +- [Supported Providers](#supported-providers) +- [Key Features](#key-features) +- [Status](#status) +- [Use Cases](#use-cases) +- [Architecture](#architecture) +- [Quick Start](#quick-start) +- [API Standard](#api-standard) +- [API Reference](#api-reference) +- [Tech Stack](#tech-stack) +- [Project Structure](#project-structure) +- [Configuration](#configuration) +- [Chat Client](#chat-client) +- [Conversation Management](#conversation-management) +- [Observability](#observability) +- [Circuit Breakers](#circuit-breakers) +- [Azure OpenAI](#azure-openai) +- [Azure Anthropic](#azure-anthropic-microsoft-foundry) +- [Admin Web UI](#admin-web-ui) +- [Deployment](#deployment) +- [Authentication](#authentication) +- [Production Features](#production-features) +- [Roadmap](#roadmap) +- [Documentation](#documentation) +- [Contributing](#contributing) +- [License](#license) + ## Overview -A lightweight LLM proxy gateway written in Go that provides a unified API interface for multiple LLM providers. Similar to LiteLLM, but built natively in Go using each provider's official SDK. +A production-ready LLM proxy gateway written in Go that provides a unified API interface for multiple LLM providers. Similar to LiteLLM, but built natively in Go using each provider's official SDK with enterprise features including rate limiting, circuit breakers, observability, and authentication. -## Purpose +## Supported Providers -Simplify LLM integration by exposing a single, consistent API that routes requests to different providers: - **OpenAI** (GPT models) -- **Azure OpenAI** (Azure-deployed models) -- **Anthropic** (Claude) -- **Google Generative AI** (Gemini) +- **Azure OpenAI** (Azure-deployed OpenAI models) +- **Anthropic** (Claude models) +- **Azure Anthropic** (Microsoft Foundry-hosted Claude models) +- **Google Generative AI** (Gemini models) - **Vertex AI** (Google Cloud-hosted Gemini models) Instead of managing multiple SDK integrations in your application, call one endpoint and let the gateway handle provider-specific implementations. @@ -31,11 +62,24 @@ latticelm (unified API) ## Key Features +### Core Functionality - **Single API interface** for multiple LLM providers - **Native Go SDKs** for optimal performance and type safety - **Provider abstraction** - switch providers without changing client code -- **Lightweight** - minimal overhead, fast routing -- **Easy configuration** - manage API keys and provider settings centrally +- **Streaming support** - Server-Sent Events for all providers +- **Conversation tracking** - Efficient context management with `previous_response_id` + +### Production Features +- **Circuit breakers** - Automatic failure detection and recovery per provider +- **Rate limiting** - Per-IP token bucket algorithm with configurable limits +- **OAuth2/OIDC authentication** - Support for Google, Auth0, and any OIDC provider +- **Observability** - Prometheus metrics and OpenTelemetry tracing +- **Health checks** - Kubernetes-compatible liveness and readiness endpoints +- **Admin Web UI** - Built-in dashboard for monitoring and configuration + +### Configuration +- **Easy setup** - YAML configuration with environment variable overrides +- **Flexible storage** - In-memory, SQLite, MySQL, PostgreSQL, or Redis for conversations ## Use Cases @@ -45,43 +89,70 @@ latticelm (unified API) - A/B testing across different models - Centralized LLM access for microservices -## πŸŽ‰ Status: **WORKING!** +## Status -βœ… **All providers integrated with official Go SDKs:** +**Production Ready** - All core features implemented and tested. + +### Provider Integration +βœ… All providers use official Go SDKs: - OpenAI β†’ `github.com/openai/openai-go/v3` - Azure OpenAI β†’ `github.com/openai/openai-go/v3` (with Azure auth) - Anthropic β†’ `github.com/anthropics/anthropic-sdk-go` -- Google β†’ `google.golang.org/genai` +- Azure Anthropic β†’ `github.com/anthropics/anthropic-sdk-go` (with Azure auth) +- Google Gen AI β†’ `google.golang.org/genai` - Vertex AI β†’ `google.golang.org/genai` (with GCP auth) -βœ… **Compiles successfully** (36MB binary) -βœ… **Provider auto-selection** (gptβ†’Azure/OpenAI, claudeβ†’Anthropic, geminiβ†’Google) -βœ… **Configuration system** (YAML with env var support) -βœ… **Streaming support** (Server-Sent Events for all providers) -βœ… **OAuth2/OIDC authentication** (Google, Auth0, any OIDC provider) -βœ… **Terminal chat client** (Python with Rich UI, PEP 723) -βœ… **Conversation tracking** (previous_response_id for efficient context) -βœ… **Rate limiting** (Per-IP token bucket with configurable limits) -βœ… **Health & readiness endpoints** (Kubernetes-compatible health checks) -βœ… **Admin Web UI** (Dashboard with system info, health checks, provider status) +### Features +βœ… Provider auto-selection (gptβ†’OpenAI, claudeβ†’Anthropic, geminiβ†’Google) +βœ… Streaming responses (Server-Sent Events) +βœ… Conversation tracking with `previous_response_id` +βœ… OAuth2/OIDC authentication +βœ… Rate limiting with token bucket algorithm +βœ… Circuit breakers for fault tolerance +βœ… Observability (Prometheus metrics + OpenTelemetry tracing) +βœ… Health & readiness endpoints +βœ… Admin Web UI dashboard +βœ… Terminal chat client (Python with Rich UI) ## Quick Start +### Prerequisites + +- Go 1.21+ (for building from source) +- Docker (optional, for containerized deployment) +- Node.js 18+ (optional, for Admin UI development) + +### Running Locally + ```bash -# 1. Set API keys +# 1. Clone the repository +git clone https://github.com/yourusername/latticelm.git +cd latticelm + +# 2. Set API keys export OPENAI_API_KEY="your-key" export ANTHROPIC_API_KEY="your-key" export GOOGLE_API_KEY="your-key" -# 2. Build (includes Admin UI) -cd latticelm +# 3. Copy and configure settings (optional) +cp config.example.yaml config.yaml +# Edit config.yaml to customize settings + +# 4. Build (includes Admin UI) make build-all -# 3. Run +# 5. Run ./bin/llm-gateway -# 4. Test (non-streaming) -curl -X POST http://localhost:8080/v1/chat/completions \ +# Gateway starts on http://localhost:8080 +# Admin UI available at http://localhost:8080/admin/ +``` + +### Testing the API + +**Non-streaming request:** +```bash +curl -X POST http://localhost:8080/v1/responses \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4o-mini", @@ -92,9 +163,11 @@ curl -X POST http://localhost:8080/v1/chat/completions \ } ] }' +``` -# 5. Test streaming -curl -X POST http://localhost:8080/v1/chat/completions \ +**Streaming request:** +```bash +curl -X POST http://localhost:8080/v1/responses \ -H "Content-Type: application/json" \ -N \ -d '{ @@ -109,6 +182,20 @@ curl -X POST http://localhost:8080/v1/chat/completions \ }' ``` +### Development Mode + +Run backend and frontend separately for live reloading: + +```bash +# Terminal 1: Backend with auto-reload +make dev-backend + +# Terminal 2: Frontend dev server +make dev-frontend +``` + +Frontend runs on `http://localhost:5173` with hot module replacement. + ## API Standard This gateway implements the **[Open Responses](https://www.openresponses.org)** specification β€” an open-source, multi-provider API standard for LLM interfaces based on OpenAI's Responses API. @@ -125,64 +212,245 @@ By following the Open Responses spec, this gateway ensures: For full specification details, see: **https://www.openresponses.org** +## API Reference + +### Core Endpoints + +#### POST /v1/responses +Create a chat completion response (streaming or non-streaming). + +**Request body:** +```json +{ + "model": "gpt-4o-mini", + "stream": false, + "input": [ + { + "role": "user", + "content": [{"type": "input_text", "text": "Hello!"}] + } + ], + "previous_response_id": "optional-conversation-id", + "provider": "optional-explicit-provider" +} +``` + +**Response (non-streaming):** +```json +{ + "id": "resp_abc123", + "object": "response", + "model": "gpt-4o-mini", + "provider": "openai", + "output": [ + { + "role": "assistant", + "content": [{"type": "text", "text": "Hello! How can I help you?"}] + } + ], + "usage": { + "input_tokens": 10, + "output_tokens": 8 + } +} +``` + +**Response (streaming):** +Server-Sent Events with `data: {...}` lines containing deltas. + +#### GET /v1/models +List available models. + +**Response:** +```json +{ + "object": "list", + "data": [ + {"id": "gpt-4o-mini", "provider": "openai"}, + {"id": "claude-3-5-sonnet", "provider": "anthropic"}, + {"id": "gemini-1.5-flash", "provider": "google"} + ] +} +``` + +### Health Endpoints + +#### GET /health +Liveness probe (always returns 200 if server is running). + +**Response:** +```json +{ + "status": "healthy", + "timestamp": 1709438400 +} +``` + +#### GET /ready +Readiness probe (checks conversation store and providers). + +**Response:** +```json +{ + "status": "ready", + "timestamp": 1709438400, + "checks": { + "conversation_store": "healthy", + "providers": "healthy" + } +} +``` + +Returns 503 if any check fails. + +### Admin Endpoints + +#### GET /admin/ +Web dashboard (when admin UI is enabled). + +#### GET /admin/api/info +System information. + +#### GET /admin/api/health +Detailed health status. + +#### GET /admin/api/config +Current configuration (secrets masked). + +### Observability Endpoints + +#### GET /metrics +Prometheus metrics (when observability is enabled). + ## Tech Stack - **Language:** Go - **API Specification:** [Open Responses](https://www.openresponses.org) -- **SDKs:** - - `google.golang.org/genai` (Google Generative AI) - - Anthropic Go SDK - - OpenAI Go SDK -- **Transport:** RESTful HTTP (potentially gRPC in the future) - -## Status - -🚧 **In Development** - Project specification and initial setup phase. - -## Getting Started - -1. **Copy the example config** and fill in provider API keys: - - ```bash - cp config.example.yaml config.yaml - ``` - - You can also override API keys via environment variables (`GOOGLE_API_KEY`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`). - -2. **Run the gateway** using the default configuration path: - - ```bash - go run ./cmd/gateway --config config.yaml - ``` - - The server listens on the address configured under `server.address` (defaults to `:8080`). - -3. **Call the Open Responses endpoint**: - - ```bash - curl -X POST http://localhost:8080/v1/responses \ - -H 'Content-Type: application/json' \ - -d '{ - "model": "gpt-4o-mini", - "input": [ - {"role": "user", "content": [{"type": "input_text", "text": "Hello!"}]} - ] - }' - ``` - - Include `"provider": "anthropic"` (or `google`, `openai`) to pin a provider; otherwise the gateway infers it from the model name. +- **Official SDKs:** + - `google.golang.org/genai` (Google Generative AI & Vertex AI) + - `github.com/anthropics/anthropic-sdk-go` (Anthropic & Azure Anthropic) + - `github.com/openai/openai-go/v3` (OpenAI & Azure OpenAI) +- **Observability:** + - Prometheus for metrics + - OpenTelemetry for distributed tracing +- **Resilience:** + - Circuit breakers via `github.com/sony/gobreaker` + - Token bucket rate limiting +- **Transport:** RESTful HTTP with Server-Sent Events for streaming ## Project Structure -- `cmd/gateway`: Entry point that loads configuration, wires providers, and starts the HTTP server. -- `internal/config`: YAML configuration loader with environment overrides for API keys. -- `internal/api`: Open Responses request/response types and validation helpers. -- `internal/server`: HTTP handlers that expose `/v1/responses`. -- `internal/providers`: Provider abstractions plus provider-specific scaffolding in `google`, `anthropic`, and `openai` subpackages. +``` +latticelm/ +β”œβ”€β”€ cmd/gateway/ # Main application entry point +β”œβ”€β”€ internal/ +β”‚ β”œβ”€β”€ admin/ # Admin UI backend and embedded frontend +β”‚ β”œβ”€β”€ api/ # Open Responses types and validation +β”‚ β”œβ”€β”€ auth/ # OAuth2/OIDC authentication +β”‚ β”œβ”€β”€ config/ # YAML configuration loader +β”‚ β”œβ”€β”€ conversation/ # Conversation tracking and storage +β”‚ β”œβ”€β”€ logger/ # Structured logging setup +β”‚ β”œβ”€β”€ metrics/ # Prometheus metrics +β”‚ β”œβ”€β”€ providers/ # Provider implementations +β”‚ β”‚ β”œβ”€β”€ anthropic/ +β”‚ β”‚ β”œβ”€β”€ azureanthropic/ +β”‚ β”‚ β”œβ”€β”€ azureopenai/ +β”‚ β”‚ β”œβ”€β”€ google/ +β”‚ β”‚ β”œβ”€β”€ openai/ +β”‚ β”‚ └── vertexai/ +β”‚ β”œβ”€β”€ ratelimit/ # Rate limiting implementation +β”‚ β”œβ”€β”€ server/ # HTTP server and handlers +β”‚ └── tracing/ # OpenTelemetry tracing +β”œβ”€β”€ frontend/admin/ # Vue.js Admin UI +β”œβ”€β”€ k8s/ # Kubernetes manifests +β”œβ”€β”€ tests/ # Integration tests +β”œβ”€β”€ config.example.yaml # Example configuration +β”œβ”€β”€ Makefile # Build and development tasks +└── README.md +``` + +## Configuration + +The gateway uses a YAML configuration file with support for environment variable overrides. + +### Basic Configuration + +```yaml +server: + address: ":8080" + max_request_body_size: 10485760 # 10MB + +logging: + format: "json" # or "text" for development + level: "info" # debug, info, warn, error + +# Configure providers (API keys can use ${ENV_VAR} syntax) +providers: + openai: + type: "openai" + api_key: "${OPENAI_API_KEY}" + anthropic: + type: "anthropic" + api_key: "${ANTHROPIC_API_KEY}" + google: + type: "google" + api_key: "${GOOGLE_API_KEY}" + +# Map model names to providers +models: + - name: "gpt-4o-mini" + provider: "openai" + - name: "claude-3-5-sonnet" + provider: "anthropic" + - name: "gemini-1.5-flash" + provider: "google" +``` + +### Advanced Configuration + +```yaml +# Rate limiting +rate_limit: + enabled: true + requests_per_second: 10 + burst: 20 + +# Authentication +auth: + enabled: true + issuer: "https://accounts.google.com" + audience: "your-client-id.apps.googleusercontent.com" + +# Observability +observability: + enabled: true + metrics: + enabled: true + path: "/metrics" + tracing: + enabled: true + service_name: "llm-gateway" + exporter: + type: "otlp" + endpoint: "localhost:4317" + +# Conversation storage +conversations: + store: "sql" # memory, sql, or redis + ttl: "1h" + driver: "sqlite3" + dsn: "conversations.db" + +# Admin UI +admin: + enabled: true +``` + +See `config.example.yaml` for complete configuration options with detailed comments. ## Chat Client -Interactive terminal chat interface with beautiful Rich UI: +Interactive terminal chat interface with beautiful Rich UI powered by Python and the Rich library: ```bash # Basic usage @@ -196,20 +464,118 @@ You> /model claude You> /models # List all available models ``` -The chat client automatically uses `previous_response_id` to reduce token usage by only sending new messages instead of the full conversation history. +Features: +- **Syntax highlighting** for code blocks +- **Markdown rendering** for formatted responses +- **Model switching** on the fly with `/model` command +- **Conversation history** with automatic `previous_response_id` tracking +- **Streaming responses** with real-time display -See **[CHAT_CLIENT.md](./CHAT_CLIENT.md)** for full documentation. +The chat client uses [PEP 723](https://peps.python.org/pep-0723/) inline script metadata, so `uv run` automatically installs dependencies. ## Conversation Management -The gateway implements conversation tracking using `previous_response_id` from the Open Responses spec: +The gateway implements efficient conversation tracking using `previous_response_id` from the Open Responses spec: -- πŸ“‰ **Reduced token usage** - Only send new messages -- ⚑ **Smaller requests** - Less bandwidth -- 🧠 **Server-side context** - Gateway maintains history -- ⏰ **Auto-expire** - Conversations expire after 1 hour +- πŸ“‰ **Reduced token usage** - Only send new messages, not full history +- ⚑ **Smaller requests** - Less bandwidth and faster responses +- 🧠 **Server-side context** - Gateway maintains conversation state +- ⏰ **Auto-expire** - Conversations expire after configurable TTL (default: 1 hour) -See **[CONVERSATIONS.md](./CONVERSATIONS.md)** for details. +### Storage Options + +Choose from multiple storage backends: + +```yaml +conversations: + store: "memory" # "memory", "sql", or "redis" + ttl: "1h" # Conversation expiration + + # SQLite (default for sql) + driver: "sqlite3" + dsn: "conversations.db" + + # MySQL + # driver: "mysql" + # dsn: "user:password@tcp(localhost:3306)/dbname?parseTime=true" + + # PostgreSQL + # driver: "pgx" + # dsn: "postgres://user:password@localhost:5432/dbname?sslmode=disable" + + # Redis + # store: "redis" + # dsn: "redis://:password@localhost:6379/0" +``` + +## Observability + +The gateway provides comprehensive observability through Prometheus metrics and OpenTelemetry tracing. + +### Metrics + +Enable Prometheus metrics to monitor gateway performance: + +```yaml +observability: + enabled: true + metrics: + enabled: true + path: "/metrics" # Default endpoint +``` + +Available metrics include: +- Request counts and latencies per provider and model +- Error rates and types +- Circuit breaker state changes +- Rate limit hits +- Conversation store operations + +Access metrics at `http://localhost:8080/metrics` (Prometheus scrape format). + +### Tracing + +Enable OpenTelemetry tracing for distributed request tracking: + +```yaml +observability: + enabled: true + tracing: + enabled: true + service_name: "llm-gateway" + sampler: + type: "probability" # "always", "never", or "probability" + rate: 0.1 # Sample 10% of requests + exporter: + type: "otlp" # Send to OpenTelemetry Collector + endpoint: "localhost:4317" # gRPC endpoint + insecure: true # Use TLS in production +``` + +Traces include: +- End-to-end request flow +- Provider API calls +- Conversation store lookups +- Circuit breaker operations +- Authentication checks + +Use with Jaeger, Zipkin, or any OpenTelemetry-compatible backend. + +## Circuit Breakers + +The gateway automatically wraps each provider with a circuit breaker for fault tolerance. When a provider experiences failures, the circuit breaker: + +1. **Closed state** - Normal operation, requests pass through +2. **Open state** - Fast-fail after threshold reached, returns errors immediately +3. **Half-open state** - Allows test requests to check if provider recovered + +Default configuration (per provider): +- **Max requests in half-open**: 3 +- **Interval**: 60 seconds (resets failure count) +- **Timeout**: 30 seconds (open β†’ half-open transition) +- **Failure ratio**: 0.5 (50% failures trips circuit) + +Circuit breaker state changes are logged and exposed via metrics. ## Azure OpenAI @@ -235,7 +601,33 @@ export AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com" ./gateway ``` -The `provider_model_id` field lets you map a friendly model name to the actual provider identifier (e.g., an Azure deployment name). If omitted, the model `name` is used directly. See **[AZURE_OPENAI.md](./AZURE_OPENAI.md)** for complete setup guide. +The `provider_model_id` field lets you map a friendly model name to the actual provider identifier (e.g., an Azure deployment name). If omitted, the model `name` is used directly. + +## Azure Anthropic (Microsoft Foundry) + +The gateway supports Azure-hosted Anthropic models through Microsoft's AI Foundry: + +```yaml +providers: + azureanthropic: + type: "azureanthropic" + api_key: "${AZURE_ANTHROPIC_API_KEY}" + endpoint: "https://your-resource.services.ai.azure.com/anthropic" + +models: + - name: "claude-sonnet-4-5" + provider: "azureanthropic" + provider_model_id: "claude-sonnet-4-5-20250514" # optional +``` + +```bash +export AZURE_ANTHROPIC_API_KEY="..." +export AZURE_ANTHROPIC_ENDPOINT="https://your-resource.services.ai.azure.com/anthropic" + +./gateway +``` + +Azure Anthropic provides Claude models with Azure's compliance, security, and regional deployment options. ## Admin Web UI @@ -277,11 +669,94 @@ make dev-frontend Frontend dev server runs on `http://localhost:5173` and proxies API requests to backend. +## Deployment + +### Docker + +**See the [Docker Deployment Guide](./docs/DOCKER_DEPLOYMENT.md)** for complete instructions on using pre-built images. + +Build and run with Docker: + +```bash +# Build Docker image (includes Admin UI automatically) +docker build -t llm-gateway:latest . + +# Run container +docker run -d \ + --name llm-gateway \ + -p 8080:8080 \ + -e GOOGLE_API_KEY="your-key" \ + -e ANTHROPIC_API_KEY="your-key" \ + -e OPENAI_API_KEY="your-key" \ + llm-gateway:latest + +# Check status +docker logs llm-gateway +``` + +The Docker build uses a multi-stage process that automatically builds the frontend, so you don't need Node.js installed locally. + +**Using Docker Compose:** + +```yaml +version: '3.8' +services: + llm-gateway: + build: . + ports: + - "8080:8080" + environment: + - OPENAI_API_KEY=${OPENAI_API_KEY} + - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY} + - GOOGLE_API_KEY=${GOOGLE_API_KEY} + restart: unless-stopped +``` + +```bash +docker-compose up -d +``` + +The Docker image: +- Uses 3-stage build (frontend β†’ backend β†’ runtime) for minimal size (~50MB) +- Automatically builds and embeds the Admin UI +- Runs as non-root user (UID 1000) for security +- Includes health checks for orchestration +- No need for Node.js or Go installed locally + +### Kubernetes + +Production-ready Kubernetes manifests are available in the `k8s/` directory: + +```bash +# Deploy to Kubernetes +kubectl apply -k k8s/ + +# Or deploy individual manifests +kubectl apply -f k8s/namespace.yaml +kubectl apply -f k8s/deployment.yaml +kubectl apply -f k8s/service.yaml +kubectl apply -f k8s/ingress.yaml +``` + +Features included: +- **High availability** - 3+ replicas with pod anti-affinity +- **Auto-scaling** - HorizontalPodAutoscaler (3-20 replicas) +- **Security** - Non-root, read-only filesystem, network policies +- **Monitoring** - ServiceMonitor and PrometheusRule for Prometheus Operator +- **Storage** - Redis StatefulSet for conversation persistence +- **Ingress** - TLS with cert-manager integration + +See **[k8s/README.md](./k8s/README.md)** for complete deployment guide including: +- Cloud-specific configurations (AWS EKS, GCP GKE, Azure AKS) +- Secrets management (External Secrets Operator, Sealed Secrets) +- Monitoring and alerting setup +- Troubleshooting guide + ## Authentication -The gateway supports OAuth2/OIDC authentication. See **[AUTH.md](./AUTH.md)** for setup instructions. +The gateway supports OAuth2/OIDC authentication for securing API access. -**Quick example with Google OAuth:** +### Configuration ```yaml auth: @@ -349,12 +824,109 @@ The readiness endpoint verifies: - At least one provider is configured - Returns 503 if any check fails -## Next Steps +## Roadmap -- βœ… ~~Implement streaming responses~~ -- βœ… ~~Add OAuth2/OIDC authentication~~ -- βœ… ~~Implement conversation tracking with previous_response_id~~ -- ⬜ Add structured logging, tracing, and request-level metrics -- ⬜ Support tool/function calling -- ⬜ Persistent conversation storage (Redis/database) -- ⬜ Expand configuration to support routing policies (cost, latency, failover) +### Completed βœ… +- βœ… Streaming responses (Server-Sent Events) +- βœ… OAuth2/OIDC authentication +- βœ… Conversation tracking with `previous_response_id` +- βœ… Persistent conversation storage (SQL and Redis) +- βœ… Circuit breakers for fault tolerance +- βœ… Rate limiting +- βœ… Observability (Prometheus metrics and OpenTelemetry tracing) +- βœ… Admin Web UI +- βœ… Health and readiness endpoints + +### In Progress 🚧 +- ⬜ Tool/function calling support across providers +- ⬜ Request-level cost tracking and budgets +- ⬜ Advanced routing policies (cost optimization, latency-based, failover) +- ⬜ Multi-tenancy with per-tenant rate limits and quotas +- ⬜ Request caching for identical prompts +- ⬜ Webhook notifications for events (failures, circuit breaker changes) + +## Documentation + +Comprehensive guides and documentation are available in the `/docs` directory: + +- **[Docker Deployment Guide](./docs/DOCKER_DEPLOYMENT.md)** - Deploy with pre-built images or build from source +- **[Kubernetes Deployment Guide](./k8s/README.md)** - Production deployment with Kubernetes +- **[Admin UI Documentation](./docs/ADMIN_UI.md)** - Using the web dashboard +- **[Configuration Reference](./config.example.yaml)** - All configuration options explained + +See the **[docs directory README](./docs/README.md)** for a complete documentation index. + +## Contributing + +Contributions are welcome! Here's how you can help: + +### Reporting Issues + +- **Bug reports**: Include steps to reproduce, expected vs actual behavior, and environment details +- **Feature requests**: Describe the use case and why it would be valuable +- **Security issues**: Email security concerns privately (don't open public issues) + +### Development Workflow + +1. **Fork and clone** the repository +2. **Create a branch** for your feature: `git checkout -b feature/your-feature-name` +3. **Make your changes** with clear, atomic commits +4. **Add tests** for new functionality +5. **Run tests**: `make test` +6. **Run linter**: `make lint` +7. **Update documentation** if needed +8. **Submit a pull request** with a clear description + +### Code Standards + +- Follow Go best practices and idioms +- Write tests for new features and bug fixes +- Keep functions small and focused +- Use meaningful variable names +- Add comments for complex logic +- Run `go fmt` before committing + +### Testing + +```bash +# Run all tests +make test + +# Run specific package tests +go test ./internal/providers/... + +# Run with coverage +make test-coverage + +# Run integration tests (requires API keys) +make test-integration +``` + +### Adding a New Provider + +1. Create provider implementation in `internal/providers/yourprovider/` +2. Implement the `Provider` interface +3. Add provider registration in `internal/providers/providers.go` +4. Add configuration support in `internal/config/` +5. Add tests and update documentation + +## License + +MIT License - see the repository for details. + +## Acknowledgments + +- Built with official SDKs from OpenAI, Anthropic, and Google +- Inspired by [LiteLLM](https://github.com/BerriAI/litellm) +- Implements the [Open Responses](https://www.openresponses.org) specification +- Uses [gobreaker](https://github.com/sony/gobreaker) for circuit breaker functionality + +## Support + +- **Documentation**: Check this README and the files in `/docs` +- **Issues**: Open a GitHub issue for bugs or feature requests +- **Discussions**: Use GitHub Discussions for questions and community support + +--- + +**Made with ❀️ in Go** diff --git a/docs/DOCKER_DEPLOYMENT.md b/docs/DOCKER_DEPLOYMENT.md new file mode 100644 index 0000000..0917549 --- /dev/null +++ b/docs/DOCKER_DEPLOYMENT.md @@ -0,0 +1,471 @@ +# Docker Deployment Guide + +> Deploy the LLM Gateway using pre-built Docker images or build your own. + +## Table of Contents + +- [Quick Start](#quick-start) +- [Using Pre-Built Images](#using-pre-built-images) +- [Configuration](#configuration) +- [Docker Compose](#docker-compose) +- [Building from Source](#building-from-source) +- [Production Considerations](#production-considerations) +- [Troubleshooting](#troubleshooting) + +## Quick Start + +Pull and run the latest image: + +```bash +docker run -d \ + --name llm-gateway \ + -p 8080:8080 \ + -e OPENAI_API_KEY="sk-your-key" \ + -e ANTHROPIC_API_KEY="sk-ant-your-key" \ + -e GOOGLE_API_KEY="your-key" \ + ghcr.io/yourusername/llm-gateway:latest + +# Verify it's running +curl http://localhost:8080/health +``` + +## Using Pre-Built Images + +Images are automatically built and published via GitHub Actions on every release. + +### Available Tags + +- `latest` - Latest stable release +- `v1.2.3` - Specific version tags +- `main` - Latest commit on main branch (unstable) +- `sha-abc1234` - Specific commit SHA + +### Pull from Registry + +```bash +# Pull latest stable +docker pull ghcr.io/yourusername/llm-gateway:latest + +# Pull specific version +docker pull ghcr.io/yourusername/llm-gateway:v1.2.3 + +# List local images +docker images | grep llm-gateway +``` + +### Basic Usage + +```bash +docker run -d \ + --name llm-gateway \ + -p 8080:8080 \ + --env-file .env \ + ghcr.io/yourusername/llm-gateway:latest +``` + +## Configuration + +### Environment Variables + +Create a `.env` file with your API keys: + +```bash +# Required: At least one provider +OPENAI_API_KEY=sk-your-openai-key +ANTHROPIC_API_KEY=sk-ant-your-anthropic-key +GOOGLE_API_KEY=your-google-key + +# Optional: Server settings +SERVER_ADDRESS=:8080 +LOGGING_LEVEL=info +LOGGING_FORMAT=json + +# Optional: Features +ADMIN_ENABLED=true +RATE_LIMIT_ENABLED=true +RATE_LIMIT_REQUESTS_PER_SECOND=10 +RATE_LIMIT_BURST=20 + +# Optional: Auth +AUTH_ENABLED=false +AUTH_ISSUER=https://accounts.google.com +AUTH_AUDIENCE=your-client-id.apps.googleusercontent.com + +# Optional: Observability +OBSERVABILITY_ENABLED=false +OBSERVABILITY_METRICS_ENABLED=false +OBSERVABILITY_TRACING_ENABLED=false +``` + +Run with environment file: + +```bash +docker run -d \ + --name llm-gateway \ + -p 8080:8080 \ + --env-file .env \ + ghcr.io/yourusername/llm-gateway:latest +``` + +### Using Config File + +For more complex configurations, use a YAML config file: + +```bash +# Create config from example +cp config.example.yaml config.yaml +# Edit config.yaml with your settings + +# Mount config file into container +docker run -d \ + --name llm-gateway \ + -p 8080:8080 \ + -v $(pwd)/config.yaml:/app/config.yaml:ro \ + ghcr.io/yourusername/llm-gateway:latest \ + --config /app/config.yaml +``` + +### Persistent Storage + +For persistent conversation storage with SQLite: + +```bash +docker run -d \ + --name llm-gateway \ + -p 8080:8080 \ + -v llm-gateway-data:/app/data \ + -e OPENAI_API_KEY="your-key" \ + -e CONVERSATIONS_STORE=sql \ + -e CONVERSATIONS_DRIVER=sqlite3 \ + -e CONVERSATIONS_DSN=/app/data/conversations.db \ + ghcr.io/yourusername/llm-gateway:latest +``` + +## Docker Compose + +The project includes a production-ready `docker-compose.yaml` file. + +### Basic Setup + +```bash +# Create .env file with API keys +cat > .env < Production-ready Kubernetes manifests for deploying the LLM Gateway with high availability, monitoring, and security. -## Prerequisites +## Table of Contents -- Kubernetes cluster (v1.24+) -- `kubectl` configured -- Container registry access -- (Optional) Prometheus Operator for monitoring -- (Optional) cert-manager for TLS certificates -- (Optional) nginx-ingress-controller or cloud load balancer +- [Quick Start](#quick-start) +- [Prerequisites](#prerequisites) +- [Deployment](#deployment) +- [Configuration](#configuration) +- [Secrets Management](#secrets-management) +- [Monitoring](#monitoring) +- [Storage Options](#storage-options) +- [Scaling](#scaling) +- [Updates and Rollbacks](#updates-and-rollbacks) +- [Security](#security) +- [Cloud Provider Guides](#cloud-provider-guides) +- [Troubleshooting](#troubleshooting) ## Quick Start -### 1. Build and Push Docker Image +Deploy with default settings using pre-built images: ```bash -# Build the image -docker build -t your-registry/llm-gateway:v1.0.0 . +# Update kustomization.yaml with your image +cd k8s/ +vim kustomization.yaml # Set image to ghcr.io/yourusername/llm-gateway:v1.0.0 -# Push to registry -docker push your-registry/llm-gateway:v1.0.0 +# Create secrets +kubectl create namespace llm-gateway +kubectl create secret generic llm-gateway-secrets \ + --from-literal=OPENAI_API_KEY="sk-your-key" \ + --from-literal=ANTHROPIC_API_KEY="sk-ant-your-key" \ + --from-literal=GOOGLE_API_KEY="your-key" \ + -n llm-gateway + +# Deploy +kubectl apply -k . + +# Verify +kubectl get pods -n llm-gateway +kubectl logs -n llm-gateway -l app=llm-gateway ``` -### 2. Configure Secrets +## Prerequisites + +- **Kubernetes**: v1.24+ cluster +- **kubectl**: Configured and authenticated +- **Container images**: Access to `ghcr.io/yourusername/llm-gateway` + +**Optional but recommended:** +- **Prometheus Operator**: For metrics and alerting +- **cert-manager**: For automatic TLS certificates +- **Ingress Controller**: nginx, ALB, or GCE +- **External Secrets Operator**: For secrets management + +## Deployment + +### Using Kustomize (Recommended) -**Option A: Using kubectl** ```bash -kubectl create namespace llm-gateway +# Review and customize +cd k8s/ +vim kustomization.yaml # Update image, namespace, etc. +vim configmap.yaml # Configure gateway settings +vim ingress.yaml # Set your domain +# Deploy all resources +kubectl apply -k . + +# Deploy with Kustomize overlays +kubectl apply -k overlays/production/ +``` + +### Using kubectl + +```bash +kubectl apply -f namespace.yaml +kubectl apply -f serviceaccount.yaml +kubectl apply -f secret.yaml +kubectl apply -f configmap.yaml +kubectl apply -f redis.yaml +kubectl apply -f deployment.yaml +kubectl apply -f service.yaml +kubectl apply -f ingress.yaml +kubectl apply -f hpa.yaml +kubectl apply -f pdb.yaml +kubectl apply -f networkpolicy.yaml +``` + +### With Monitoring + +If Prometheus Operator is installed: + +```bash +kubectl apply -f servicemonitor.yaml +kubectl apply -f prometheusrule.yaml +``` + +## Configuration + +### Image Configuration + +Update `kustomization.yaml`: + +```yaml +images: + - name: llm-gateway + newName: ghcr.io/yourusername/llm-gateway + newTag: v1.2.3 # Or 'latest', 'main', 'sha-abc123' +``` + +### Gateway Configuration + +Edit `configmap.yaml` for gateway settings: + +```yaml +apiVersion: v1 +kind: ConfigMap +metadata: + name: llm-gateway-config +data: + config.yaml: | + server: + address: ":8080" + + logging: + level: info + format: json + + rate_limit: + enabled: true + requests_per_second: 10 + burst: 20 + + observability: + enabled: true + metrics: + enabled: true + tracing: + enabled: true + exporter: + type: otlp + endpoint: tempo:4317 + + conversations: + store: redis + dsn: redis://redis:6379/0 + ttl: 1h +``` + +### Resource Limits + +Default resources (adjust based on load testing): + +```yaml +resources: + requests: + cpu: 100m + memory: 128Mi + limits: + cpu: 1000m + memory: 512Mi +``` + +### Ingress Configuration + +Edit `ingress.yaml` for your domain: + +```yaml +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: llm-gateway + annotations: + cert-manager.io/cluster-issuer: letsencrypt-prod + nginx.ingress.kubernetes.io/ssl-redirect: "true" +spec: + ingressClassName: nginx + tls: + - hosts: + - llm-gateway.yourdomain.com + secretName: llm-gateway-tls + rules: + - host: llm-gateway.yourdomain.com + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: llm-gateway + port: + number: 80 +``` + +## Secrets Management + +### Option 1: kubectl (Development) + +```bash kubectl create secret generic llm-gateway-secrets \ - --from-literal=GOOGLE_API_KEY="your-key" \ - --from-literal=ANTHROPIC_API_KEY="your-key" \ - --from-literal=OPENAI_API_KEY="your-key" \ + --from-literal=OPENAI_API_KEY="sk-..." \ + --from-literal=ANTHROPIC_API_KEY="sk-ant-..." \ + --from-literal=GOOGLE_API_KEY="..." \ --from-literal=OIDC_AUDIENCE="your-client-id" \ -n llm-gateway ``` -**Option B: Using External Secrets Operator (Recommended)** -- Uncomment the ExternalSecret in `secret.yaml` -- Configure your SecretStore (AWS Secrets Manager, Vault, etc.) +### Option 2: External Secrets Operator (Production) -### 3. Update Configuration +Install ESO, then create ExternalSecret: -Edit `configmap.yaml`: -- Update Redis connection string if using external Redis -- Configure observability endpoints (Tempo, Prometheus) -- Adjust rate limits as needed -- Set OIDC issuer and audience - -Edit `ingress.yaml`: -- Replace `llm-gateway.example.com` with your domain -- Configure TLS certificate annotations - -Edit `kustomization.yaml`: -- Update image registry and tag - -### 4. Deploy - -**Using Kustomize (Recommended):** -```bash -kubectl apply -k k8s/ +```yaml +apiVersion: external-secrets.io/v1beta1 +kind: ExternalSecret +metadata: + name: llm-gateway-secrets + namespace: llm-gateway +spec: + refreshInterval: 1h + secretStoreRef: + name: aws-secretsmanager # or vault, gcpsm, etc. + kind: ClusterSecretStore + target: + name: llm-gateway-secrets + data: + - secretKey: OPENAI_API_KEY + remoteRef: + key: llm-gateway/openai-key + - secretKey: ANTHROPIC_API_KEY + remoteRef: + key: llm-gateway/anthropic-key + - secretKey: GOOGLE_API_KEY + remoteRef: + key: llm-gateway/google-key ``` -**Using kubectl directly:** +### Option 3: Sealed Secrets + ```bash -kubectl apply -f k8s/namespace.yaml -kubectl apply -f k8s/serviceaccount.yaml -kubectl apply -f k8s/secret.yaml -kubectl apply -f k8s/configmap.yaml -kubectl apply -f k8s/redis.yaml -kubectl apply -f k8s/deployment.yaml -kubectl apply -f k8s/service.yaml -kubectl apply -f k8s/ingress.yaml -kubectl apply -f k8s/hpa.yaml -kubectl apply -f k8s/pdb.yaml -kubectl apply -f k8s/networkpolicy.yaml +# Encrypt secrets +echo -n "sk-your-key" | kubectl create secret generic llm-gateway-secrets \ + --dry-run=client --from-file=OPENAI_API_KEY=/dev/stdin -o yaml | \ + kubeseal -o yaml > sealed-secret.yaml + +# Commit sealed-secret.yaml to git +kubectl apply -f sealed-secret.yaml ``` -**With Prometheus Operator:** -```bash -kubectl apply -f k8s/servicemonitor.yaml -kubectl apply -f k8s/prometheusrule.yaml +## Monitoring + +### Metrics + +ServiceMonitor for Prometheus Operator: + +```yaml +apiVersion: monitoring.coreos.com/v1 +kind: ServiceMonitor +metadata: + name: llm-gateway +spec: + selector: + matchLabels: + app: llm-gateway + endpoints: + - port: http + path: /metrics + interval: 30s ``` -### 5. Verify Deployment +**Available metrics:** +- `gateway_requests_total` - Total requests by provider/model +- `gateway_request_duration_seconds` - Request latency histogram +- `gateway_provider_errors_total` - Errors by provider +- `gateway_circuit_breaker_state` - Circuit breaker state changes +- `gateway_rate_limit_hits_total` - Rate limit violations + +### Alerts + +PrometheusRule with common alerts: + +```yaml +apiVersion: monitoring.coreos.com/v1 +kind: PrometheusRule +metadata: + name: llm-gateway-alerts +spec: + groups: + - name: llm-gateway + interval: 30s + rules: + - alert: HighErrorRate + expr: rate(gateway_requests_total{status=~"5.."}[5m]) > 0.05 + for: 5m + annotations: + summary: High error rate detected + + - alert: PodDown + expr: kube_deployment_status_replicas_available{deployment="llm-gateway"} < 2 + for: 5m + annotations: + summary: Less than 2 gateway pods running +``` + +### Logging + +View logs: ```bash -# Check pods +# Tail logs +kubectl logs -n llm-gateway -l app=llm-gateway -f + +# Filter by level +kubectl logs -n llm-gateway -l app=llm-gateway | jq 'select(.level=="error")' + +# Search logs +kubectl logs -n llm-gateway -l app=llm-gateway | grep "circuit.*open" +``` + +### Tracing + +Configure OpenTelemetry collector: + +```yaml +observability: + tracing: + enabled: true + exporter: + type: otlp + endpoint: tempo:4317 # or jaeger-collector:4317 +``` + +## Storage Options + +### In-Memory (Default) + +No persistence, lost on pod restart: + +```yaml +conversations: + store: memory +``` + +### Redis (Recommended) + +Deploy Redis StatefulSet: + +```bash +kubectl apply -f redis.yaml +``` + +Configure gateway: + +```yaml +conversations: + store: redis + dsn: redis://redis:6379/0 + ttl: 1h +``` + +### External Redis + +For production, use managed Redis: + +```yaml +conversations: + store: redis + dsn: redis://:password@redis.example.com:6379/0 + ttl: 1h +``` + +**Cloud providers:** +- **AWS**: ElastiCache for Redis +- **GCP**: Memorystore for Redis +- **Azure**: Azure Cache for Redis + +### PostgreSQL + +```yaml +conversations: + store: sql + driver: pgx + dsn: postgres://user:pass@postgres:5432/llm_gateway?sslmode=require + ttl: 1h +``` + +## Scaling + +### Horizontal Pod Autoscaler + +Default HPA configuration: + +```yaml +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: llm-gateway +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: llm-gateway + minReplicas: 3 + maxReplicas: 20 + metrics: + - type: Resource + resource: + name: cpu + target: + type: Utilization + averageUtilization: 70 + - type: Resource + resource: + name: memory + target: + type: Utilization + averageUtilization: 80 +``` + +Monitor HPA: + +```bash +kubectl get hpa -n llm-gateway +kubectl describe hpa llm-gateway -n llm-gateway +``` + +### Manual Scaling + +```bash +# Scale to specific replica count +kubectl scale deployment/llm-gateway --replicas=10 -n llm-gateway + +# Check status +kubectl get deployment llm-gateway -n llm-gateway +``` + +### Pod Disruption Budget + +Ensures availability during disruptions: + +```yaml +apiVersion: policy/v1 +kind: PodDisruptionBudget +metadata: + name: llm-gateway +spec: + minAvailable: 2 + selector: + matchLabels: + app: llm-gateway +``` + +## Updates and Rollbacks + +### Rolling Updates + +```bash +# Update image +kubectl set image deployment/llm-gateway \ + gateway=ghcr.io/yourusername/llm-gateway:v1.2.3 \ + -n llm-gateway + +# Watch rollout +kubectl rollout status deployment/llm-gateway -n llm-gateway + +# Pause rollout if issues +kubectl rollout pause deployment/llm-gateway -n llm-gateway + +# Resume rollout +kubectl rollout resume deployment/llm-gateway -n llm-gateway +``` + +### Rollback + +```bash +# Rollback to previous version +kubectl rollout undo deployment/llm-gateway -n llm-gateway + +# Rollback to specific revision +kubectl rollout history deployment/llm-gateway -n llm-gateway +kubectl rollout undo deployment/llm-gateway --to-revision=3 -n llm-gateway +``` + +### Blue-Green Deployment + +```bash +# Deploy new version with different label +kubectl apply -f deployment-v2.yaml + +# Test new version +kubectl port-forward -n llm-gateway deployment/llm-gateway-v2 8080:8080 + +# Switch service to new version +kubectl patch service llm-gateway -n llm-gateway \ + -p '{"spec":{"selector":{"version":"v2"}}}' + +# Delete old version after verification +kubectl delete deployment llm-gateway-v1 -n llm-gateway +``` + +## Security + +### Pod Security + +Deployment includes security best practices: + +```yaml +securityContext: + runAsNonRoot: true + runAsUser: 1000 + fsGroup: 1000 + seccompProfile: + type: RuntimeDefault + +containers: + - name: gateway + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL +``` + +### Network Policies + +Restrict traffic to/from gateway pods: + +```yaml +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: llm-gateway +spec: + podSelector: + matchLabels: + app: llm-gateway + policyTypes: + - Ingress + - Egress + ingress: + - from: + - namespaceSelector: + matchLabels: + name: ingress-nginx + ports: + - protocol: TCP + port: 8080 + egress: + - to: # Allow DNS + - namespaceSelector: {} + podSelector: + matchLabels: + k8s-app: kube-dns + ports: + - protocol: UDP + port: 53 + - to: # Allow Redis + - podSelector: + matchLabels: + app: redis + ports: + - protocol: TCP + port: 6379 + - to: # Allow external LLM providers (HTTPS) + - namespaceSelector: {} + ports: + - protocol: TCP + port: 443 +``` + +### RBAC + +ServiceAccount with minimal permissions: + +```yaml +apiVersion: v1 +kind: ServiceAccount +metadata: + name: llm-gateway +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: llm-gateway +rules: + - apiGroups: [""] + resources: ["configmaps"] + verbs: ["get", "list", "watch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: llm-gateway +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: llm-gateway +subjects: + - kind: ServiceAccount + name: llm-gateway +``` + +## Cloud Provider Guides + +### AWS EKS + +```bash +# Install AWS Load Balancer Controller +kubectl apply -k "github.com/aws/eks-charts/stable/aws-load-balancer-controller//crds?ref=master" +helm install aws-load-balancer-controller eks/aws-load-balancer-controller \ + -n kube-system \ + --set clusterName=my-cluster + +# Update ingress for ALB +# Add annotations to ingress.yaml: +metadata: + annotations: + kubernetes.io/ingress.class: alb + alb.ingress.kubernetes.io/scheme: internet-facing + alb.ingress.kubernetes.io/target-type: ip +``` + +**IRSA for secrets:** + +```bash +# Create IAM role and associate with ServiceAccount +eksctl create iamserviceaccount \ + --name llm-gateway \ + --namespace llm-gateway \ + --cluster my-cluster \ + --attach-policy-arn arn:aws:iam::aws:policy/SecretsManagerReadWrite \ + --approve +``` + +**ElastiCache Redis:** + +```yaml +conversations: + store: redis + dsn: redis://my-cluster.cache.amazonaws.com:6379/0 +``` + +### GCP GKE + +```bash +# Enable Workload Identity +gcloud container clusters update my-cluster \ + --workload-pool=PROJECT_ID.svc.id.goog + +# Create service account with Secret Manager access +gcloud iam service-accounts create llm-gateway + +gcloud projects add-iam-policy-binding PROJECT_ID \ + --member "serviceAccount:llm-gateway@PROJECT_ID.iam.gserviceaccount.com" \ + --role "roles/secretmanager.secretAccessor" + +# Bind K8s SA to GCP SA +kubectl annotate serviceaccount llm-gateway \ + -n llm-gateway \ + iam.gke.io/gcp-service-account=llm-gateway@PROJECT_ID.iam.gserviceaccount.com +``` + +**Memorystore Redis:** + +```yaml +conversations: + store: redis + dsn: redis://10.0.0.3:6379/0 # Private IP from Memorystore +``` + +### Azure AKS + +```bash +# Install Application Gateway Ingress Controller +az aks enable-addons \ + --resource-group myResourceGroup \ + --name myAKSCluster \ + --addons ingress-appgw \ + --appgw-name myApplicationGateway + +# Configure Azure AD Workload Identity +az aks update \ + --resource-group myResourceGroup \ + --name myAKSCluster \ + --enable-oidc-issuer \ + --enable-workload-identity +``` + +**Azure Key Vault with ESO:** + +```yaml +apiVersion: external-secrets.io/v1beta1 +kind: SecretStore +metadata: + name: azure-keyvault +spec: + provider: + azurekv: + authType: WorkloadIdentity + vaultUrl: https://my-vault.vault.azure.net +``` + +## Troubleshooting + +### Pods Not Starting + +```bash +# Check pod status kubectl get pods -n llm-gateway -# Check services -kubectl get svc -n llm-gateway +# Describe pod for events +kubectl describe pod llm-gateway-xxx -n llm-gateway -# Check ingress -kubectl get ingress -n llm-gateway +# Check logs +kubectl logs -n llm-gateway llm-gateway-xxx -# View logs -kubectl logs -n llm-gateway -l app=llm-gateway --tail=100 -f +# Check previous container logs (if crashed) +kubectl logs -n llm-gateway llm-gateway-xxx --previous +``` -# Check health +**Common issues:** +- Image pull errors: Check registry credentials +- CrashLoopBackOff: Check logs for startup errors +- Pending: Check resource quotas and node capacity + +### Health Check Failures + +```bash +# Port-forward to test locally kubectl port-forward -n llm-gateway svc/llm-gateway 8080:80 + +# Test endpoints curl http://localhost:8080/health +curl http://localhost:8080/ready + +# Check from inside pod +kubectl exec -n llm-gateway deployment/llm-gateway -- wget -O- http://localhost:8080/health +``` + +### Provider Connection Issues + +```bash +# Test egress from pod +kubectl exec -n llm-gateway deployment/llm-gateway -- wget -O- https://api.openai.com + +# Check secrets +kubectl get secret llm-gateway-secrets -n llm-gateway -o jsonpath='{.data.OPENAI_API_KEY}' | base64 -d + +# Verify network policies +kubectl get networkpolicy -n llm-gateway +kubectl describe networkpolicy llm-gateway -n llm-gateway +``` + +### Redis Connection Issues + +```bash +# Test Redis connectivity +kubectl exec -n llm-gateway deployment/llm-gateway -- nc -zv redis 6379 + +# Connect to Redis +kubectl exec -it -n llm-gateway redis-0 -- redis-cli + +# Check Redis logs +kubectl logs -n llm-gateway redis-0 +``` + +### Performance Issues + +```bash +# Check resource usage +kubectl top pods -n llm-gateway +kubectl top nodes + +# Check HPA status +kubectl describe hpa llm-gateway -n llm-gateway + +# Check for throttling +kubectl describe pod llm-gateway-xxx -n llm-gateway | grep -i throttl +``` + +### Debug Container + +For distroless/minimal images: + +```bash +# Use ephemeral debug container +kubectl debug -it -n llm-gateway llm-gateway-xxx --image=busybox --target=gateway + +# Or use debug pod +kubectl run debug --rm -it --image=nicolaka/netshoot -n llm-gateway -- /bin/bash +``` + +## Useful Commands + +```bash +# View all resources +kubectl get all -n llm-gateway + +# Check deployment status +kubectl rollout status deployment/llm-gateway -n llm-gateway + +# Tail logs from all pods +kubectl logs -n llm-gateway -l app=llm-gateway -f --max-log-requests=10 + +# Get events +kubectl get events -n llm-gateway --sort-by='.lastTimestamp' + +# Check resource quotas +kubectl describe resourcequota -n llm-gateway + +# Export current config +kubectl get deployment llm-gateway -n llm-gateway -o yaml > deployment-backup.yaml + +# Force pod restart +kubectl rollout restart deployment/llm-gateway -n llm-gateway + +# Delete and recreate deployment +kubectl delete deployment llm-gateway -n llm-gateway +kubectl apply -f deployment.yaml ``` ## Architecture Overview ``` -β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” -β”‚ Internet/Clients β”‚ -β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ - β”‚ - β–Ό -β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” -β”‚ Ingress Controller β”‚ -β”‚ (nginx/ALB/GCE with TLS) β”‚ -β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ - β”‚ - β–Ό -β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” -β”‚ LLM Gateway Service β”‚ -β”‚ (LoadBalancer) β”‚ -β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ - β”‚ - β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” - β–Ό β–Ό β–Ό -β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” -β”‚ Gateway β”‚ β”‚ Gateway β”‚ β”‚ Gateway β”‚ -β”‚ Pod 1 β”‚ β”‚ Pod 2 β”‚ β”‚ Pod 3 β”‚ -β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜ - β”‚ β”‚ β”‚ - β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ - β”‚ - β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” - β–Ό β–Ό β–Ό -β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” -β”‚ Redis β”‚ β”‚ Prometheus β”‚ β”‚ Tempo β”‚ -β”‚ (Persistent) β”‚ β”‚ (Metrics) β”‚ β”‚ (Traces) β”‚ -β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ -``` - -## Resource Specifications - -### Default Resources -- **Requests**: 100m CPU, 128Mi memory -- **Limits**: 1000m CPU, 512Mi memory -- **Replicas**: 3 (min), 20 (max with HPA) - -### Scaling -- HPA scales based on CPU (70%) and memory (80%) -- PodDisruptionBudget ensures minimum 2 replicas during disruptions - -## Configuration Options - -### Environment Variables (from Secret) -- `GOOGLE_API_KEY`: Google AI API key -- `ANTHROPIC_API_KEY`: Anthropic API key -- `OPENAI_API_KEY`: OpenAI API key -- `OIDC_AUDIENCE`: OIDC client ID for authentication - -### ConfigMap Settings -See `configmap.yaml` for full configuration options: -- Server address -- Logging format and level -- Rate limiting -- Observability (metrics/tracing) -- Provider endpoints -- Conversation storage -- Authentication - -## Security - -### Security Features -- Non-root container execution (UID 1000) -- Read-only root filesystem -- No privilege escalation -- All capabilities dropped -- Network policies for ingress/egress control -- SeccompProfile: RuntimeDefault - -### TLS/HTTPS -- Ingress configured with TLS -- Uses cert-manager for automatic certificate provisioning -- Force SSL redirect enabled - -### Secrets Management -**Never commit secrets to git!** - -Production options: -1. **External Secrets Operator** (Recommended) - - AWS Secrets Manager - - HashiCorp Vault - - Google Secret Manager - -2. **Sealed Secrets** - - Encrypted secrets in git - -3. **Manual kubectl secrets** - - Created outside of git - -## Monitoring - -### Metrics -- Exposed on `/metrics` endpoint -- Scraped by Prometheus via ServiceMonitor -- Key metrics: - - HTTP request rate, latency, errors - - Provider request rate, latency, token usage - - Conversation store operations - - Rate limiting hits - -### Alerts -See `prometheusrule.yaml` for configured alerts: -- High error rate -- High latency -- Provider failures -- Pod down -- High memory usage -- Rate limit threshold exceeded -- Conversation store errors - -### Logs -Structured JSON logs with: -- Request IDs -- Trace context (trace_id, span_id) -- Log levels (debug/info/warn/error) - -View logs: -```bash -kubectl logs -n llm-gateway -l app=llm-gateway --tail=100 -f -``` - -## Maintenance - -### Rolling Updates -```bash -# Update image -kubectl set image deployment/llm-gateway gateway=your-registry/llm-gateway:v1.0.1 -n llm-gateway - -# Check rollout status -kubectl rollout status deployment/llm-gateway -n llm-gateway - -# Rollback if needed -kubectl rollout undo deployment/llm-gateway -n llm-gateway -``` - -### Scaling -```bash -# Manual scale -kubectl scale deployment/llm-gateway --replicas=5 -n llm-gateway - -# HPA will auto-scale within min/max bounds (3-20) -``` - -### Configuration Updates -```bash -# Edit ConfigMap -kubectl edit configmap llm-gateway-config -n llm-gateway - -# Restart pods to pick up changes -kubectl rollout restart deployment/llm-gateway -n llm-gateway -``` - -### Debugging -```bash -# Exec into pod -kubectl exec -it -n llm-gateway deployment/llm-gateway -- /bin/sh - -# Port forward for local access -kubectl port-forward -n llm-gateway svc/llm-gateway 8080:80 - -# Check events -kubectl get events -n llm-gateway --sort-by='.lastTimestamp' -``` - -## Production Considerations - -### High Availability -- Minimum 3 replicas across availability zones -- Pod anti-affinity rules spread pods across nodes -- PodDisruptionBudget ensures service availability during disruptions - -### Performance -- Adjust resource limits based on load testing -- Configure HPA thresholds based on traffic patterns -- Use node affinity for GPU nodes if needed - -### Cost Optimization -- Use spot/preemptible instances for non-critical workloads -- Set appropriate resource requests/limits -- Monitor token usage and implement quotas - -### Disaster Recovery -- Redis persistence (if using StatefulSet) -- Regular backups of conversation data -- Multi-region deployment for geo-redundancy -- Document runbooks for incident response - -## Cloud-Specific Notes - -### AWS EKS -- Use AWS Load Balancer Controller for ALB -- Configure IRSA for service account -- Use ElastiCache for Redis -- Store secrets in AWS Secrets Manager - -### GCP GKE -- Use GKE Ingress for GCLB -- Configure Workload Identity -- Use Memorystore for Redis -- Store secrets in Google Secret Manager - -### Azure AKS -- Use Azure Application Gateway Ingress Controller -- Configure Azure AD Workload Identity -- Use Azure Cache for Redis -- Store secrets in Azure Key Vault - -## Troubleshooting - -### Common Issues - -**Pods not starting:** -```bash -kubectl describe pod -n llm-gateway -l app=llm-gateway -kubectl logs -n llm-gateway -l app=llm-gateway --previous -``` - -**Health check failures:** -```bash -kubectl port-forward -n llm-gateway deployment/llm-gateway 8080:8080 -curl http://localhost:8080/health -curl http://localhost:8080/ready -``` - -**Provider connection issues:** -- Verify API keys in secrets -- Check network policies allow egress -- Verify provider endpoints are accessible - -**Redis connection issues:** -```bash -kubectl exec -it -n llm-gateway redis-0 -- redis-cli ping +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Internet / Load Balancer β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β–Ό + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ Ingress Controller β”‚ + β”‚ (TLS/SSL) β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β–Ό + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ Gateway Service β”‚ + β”‚ (ClusterIP:80) β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β–Ό β–Ό β–Ό + β”Œβ”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β” + β”‚ Pod β”‚ β”‚ Pod β”‚ β”‚ Pod β”‚ + β”‚ 1 β”‚ β”‚ 2 β”‚ β”‚ 3 β”‚ + β””β”€β”€β”¬β”€β”€β”˜ β””β”€β”€β”¬β”€β”€β”˜ β””β”€β”€β”¬β”€β”€β”˜ + β”‚ β”‚ β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β–Ό β–Ό β–Ό + β”Œβ”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β” + β”‚Redis β”‚ β”‚Prom β”‚ β”‚Tempo β”‚ + β””β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”˜ ``` ## Additional Resources -- [Kubernetes Documentation](https://kubernetes.io/docs/) -- [Prometheus Operator](https://github.com/prometheus-operator/prometheus-operator) -- [cert-manager](https://cert-manager.io/) +- [Main Documentation](../README.md) +- [Docker Deployment](../docs/DOCKER_DEPLOYMENT.md) +- [Kubernetes Best Practices](https://kubernetes.io/docs/concepts/configuration/overview/) +- [Prometheus Operator](https://prometheus-operator.dev/) - [External Secrets Operator](https://external-secrets.io/) +- [cert-manager](https://cert-manager.io/)