wyolet/relay
소개
High-throughput, self-hostable LLM router in Go. BYO provider keys, k8s-native, key pooling + batch + usage observability.
시스템 및 인프라측정된 스타 증가
- in 24h
- 0
- in 7 days
- 0
- in 15 days
- 0
- in 1 month
- 기록 수집 중
서로 겹치는 기간의 순증가량이며 일별 합계가 아닙니다. 측정값이 없으면 비워 둡니다. 스타는 관심도를 나타내며 품질을 보장하지 않습니다.
README.md
Original
Wyolet Relay
Self-hosted LLM gateway: one OpenAI- and Anthropic-compatible endpoint in front of your provider keys, with key pooling, policies, rate limits and per-request cost.
Quickstart · Docs · Discord
Relay is a single Go binary with two listeners: the inference API on :8080 and the control plane (admin UI, control API under /api, Prometheus metrics) on :8081. Applications keep their OpenAI or Anthropic SDK and change the base URL. For each request, relay authenticates the relay key, applies the policy that governs it, reserves rate-limit capacity, picks a healthy host key from the pool and streams the response back. When the caller's wire shape and the upstream's differ, relay translates between them; when they match, it passes the bytes through. Relay is Apache-2.0, runs on your infrastructure with your own provider keys, and sends no telemetry.
Scope. Relay is infrastructure: routing, keys, limits and accounting. It does not resell tokens and does not pick models for you based on quality. Clients need no relay-specific protocol: OpenAI and Anthropic request shapes are accepted as they are.
Quickstart
Start relay with its bundled Postgres and model catalog:
docker run -p 8080:8080 -p 8081:8081 wyolet/relay:standaloneAdd
-v relay-data:/var/lib/postgresql/datato keep data, credentials and the generated master key across restarts.Open http://localhost:8081 and sign in as
adminwith the password printed in the container logs on first boot. The setup wizard adds a provider key (an OpenAI key for the examples below) and creates a relay key. The relay key is shown once, so copy it.Send an OpenAI Chat Completions request:
curl http://localhost:8080/openai/v1/chat/completions \ -H "Authorization: Bearer <your-relay-key>" \ -H "Content-Type: application/json" \ -d '{"model":"gpt-4o","messages":[{"role":"user","content":"hello"}]}'Send the same model an Anthropic Messages request. Relay translates the request for the OpenAI upstream and returns the answer in the Anthropic shape:
curl http://localhost:8080/anthropic/v1/messages \ -H "x-api-key: <your-relay-key>" \ -H "Content-Type: application/json" \ -d '{"model":"gpt-4o","max_tokens":256,"messages":[{"role":"user","content":"hello"}]}'
Other ways to run it:
- Docker Compose: the lean image with its own Postgres and Dragonfly (
docker-compose.yml, docs). - Kubernetes:
helm upgrade --install relay oci://ghcr.io/wyolet/charts/relay --version <version>(chart README, docs).
Already using an SDK?
Point it at relay and pass the relay key where it expects its API key.
| Client | Setting |
|---|---|
| OpenAI SDKs | base_url = "http://localhost:8080/openai/v1" |
| Anthropic SDKs | base_url = "http://localhost:8080/anthropic" |
| Claude Code | ANTHROPIC_BASE_URL=http://localhost:8080/claude-code |
| Codex CLI | base_url = "http://127.0.0.1:8080/codex/v1" |
| OpenCode | "baseURL": "http://localhost:8080/opencode/v1" |
| Go SDK | WR_BASE_URL=http://localhost:8080, WR_API_KEY=<relay key> |
How it works
flowchart LR
clients["Apps, SDKs, coding agents"]
subgraph pod["relay pod (stateless, run one or many)"]
inf["Inference API :8080"]
pipe["auth → policy → rate limits → key pool"]
snap[("in-memory catalog snapshot")]
post["post-flight: usage, cost, payloads, metrics"]
ctl["Control plane :8081<br/>admin UI · /api · /metrics"]
end
clients -->|"relay key or inference token"| inf --> pipe
pipe -->|"byte-pass or translated"| up["Upstream hosts<br/>OpenAI · Anthropic · Gemini · compatible endpoints"]
pipe <-->|"counters, key health"| kv[("Dragonfly")]
snap -.-> pipe
ctl -->|"writes"| pg[("Postgres")]
pg -.->|"NOTIFY"| snap
pipe -.->|"async"| post
post --> sinks[("ClickHouse · Postgres · file · Dragonfly")]
- The inference path makes no Postgres calls. Routing reads an in-memory snapshot of the catalog, keys and policies; every pod updates it from a Postgres NOTIFY within about a second of a control-plane write.
- Rate-limit counters and key health live in Dragonfly, shared by all pods. A single pod can keep them in memory instead.
- Failover runs across the host keys of the chosen host and only before the first byte. Once bytes reach the caller, relay does not retry.
- Usage, cost, payload and metric records are emitted after the response, on bounded queues that never block the caller. If a queue is full the record is dropped and counted in
relay_records_lost_total. - When the caller's shape matches the upstream's, the body is passed through unchanged. Otherwise relay translates it, one SSE event at a time for streams, through a vendor-neutral canonical protocol (
sdk/v1). - The
relay_overhead_secondshistogram measures relay's own time per request (total handler time minus the upstream call), so you can see what relay adds in your deployment.
More in Architecture.
Features
Routing and keys
- Wire shapes. Inbound: OpenAI Chat Completions, Responses and Embeddings; Anthropic Messages; relay's canonical
/v1/generate; a multiplexed WebSocket at/v1/ws. Upstream: OpenAI (Chat Completions, Responses, Embeddings), Anthropic Messages and GeminigenerateContent. Inference API - Hosts. The bundled catalog includes OpenAI, Anthropic, Google Gemini, Mistral, xAI, Alibaba, Moonshot AI, Z.ai, MiniMax and Ollama Cloud, among others. Any OpenAI- or Anthropic-compatible endpoint, including a self-hosted Ollama, can be added as a host. Catalog
- Key pools. A policy lists the host keys its traffic may use. Relay picks one with
prioritized,round-robinorleast-recently-used, keeps a circuit breaker per key, and moves to the next key when one fails. A rotated key starts with a fresh breaker. Key pooling - Recovery on auth failure. When a host key returns 401, relay re-reads its value from the env var or stored secret and either retries or fails over while it heals in the background. Key pooling
- Rate limits. Rules count
requests,concurrency,tokensor a single token class such as input, output, cache reads, cache writes or reasoning. Strategies are token bucket, sliding window, fixed window, leaky bucket and session window. Limits attach to a policy, shared by the credentials it governs within a team, and to host keys, to stay inside each upstream account's limits. Rate limits - Load shedding. A per-pod in-flight cap (
RELAY_MAX_INFLIGHT) answers overflow with503(529on Anthropic-shaped routes) andRetry-Afterbefore it reads the body. Configuration
Access and tenancy
- Relay keys and inference tokens. Relay keys are stored as hashes and shown once, and they support expiry, revocation and rotation with a grace period. Inference tokens are short-lived, Ed25519-signed and minted at
POST /api/auth/token. Callers never see the host keys. Authentication - Policies. A policy grants the models and hosts a credential may reach and names the host keys that serve it, how a key is picked and which rate limits apply. Policies
- Tenancy and RBAC. Teams, projects, service accounts, users and groups. With
RELAY_AUTHZ=rbacyou get seven built-in roles, bindings at system, team or project scope, and access review (relay auth can-i). Authentication - SSO and provisioning. OIDC login with any provider that publishes a discovery document, and SCIM 2.0 provisioning of users and groups. SSO · SCIM
- Audit log. Control-plane changes are recorded and can be read at
GET /api/audit. Audit
Observability and cost
- Usage and cost. Each request produces one usage record. Token counts come from the provider's response, and cost comes from the catalog pricing of the binding that served it. Records go to ClickHouse, Postgres, a JSONL file or the state store, and you query them at
/api/usage/*. Usage - Payload logging. Request and response bodies are captured only when enabled both globally and on the governing policy. They are stored in ClickHouse, S3 or a file, and the ClickHouse store has an erase API. Payload logging
- OTLP receiver. Applications that call providers directly can report those calls over OTLP/HTTP (
/otlp/v1/traces,/otlp/v1/logs) and get the same usage and cost records. Off by default. OTLP receiver - Metrics. Prometheus
/metricson the control listener. The Helm chart ships two Grafana dashboards. Metrics
Operations
- GitOps.
relay apply -fplans with--dry-runand deletes omitted rows with--prune --selector.relay exportrenders the current state, and every manifest kind has a published JSON Schema. GitOps - Secrets. A host key either references an env var or is stored sealed with XAES-256-GCM under a per-owner data key wrapped by
RELAY_MASTER_KEY.relay secretrotates data keys and re-wraps them under a new master key. Secret keys - Kubernetes. The Helm chart includes a pre-upgrade migration Job, HPA, PDB, NetworkPolicy, ServiceMonitor, Ingress or Gateway API route, and bundled Postgres, ClickHouse and Dragonfly, each of which can be replaced by an external store. Chart README · Kubernetes
- Catalog. Provider, model and pricing data come from the open relay-catalog repo and are bundled in the image. Pin
RELAY_CATALOG_VERSIONto upgrade the catalog, keep local edits as overlays that survive upgrades, and serve releases from your owncatalog-server. Catalog · Overlays · Catalog server
Also included
| Feature | Docs |
|---|---|
Async batch API /v1/batches: submit, poll, fetch results, cancel; items go through the same policy, rate-limit and key-pool path as realtime traffic |
Batch |
Claude Code gateway: /claude-code prefix, model discovery, token counting |
Claude Code |
Codex CLI gateway (/codex) and OpenCode gateway (/opencode) |
Codex · OpenCode |
| Go SDK with proxy, telemetry and direct modes | Go SDK |
| Proxy mode: the caller's own upstream key, body forwarded unchanged, usage and cost still recorded | Proxy mode |
| Model aliases and catalog version pinning | Catalog |
X-WR-* request and response headers |
Headers |
| Control API: CRUD for every kind, settings, usage, logs | Control API · Settings |
RELAY_* environment variables |
Configuration |
relay CLI: migrate, seed, apply, export, token, auth, secret |
CLI |
| Common errors and fixes | Troubleshooting |
Production readiness
- Releases. Releases are SemVer tags on
main. A release runs only after the full CI suite has passed on the tagged commit. It publishes the lean image (wyolet/relay, needs external Postgres) and the standalone image (wyolet/relay:standalone) to Docker Hub and GHCR, and the Helm chart tooci://ghcr.io/wyolet/charts/relay. - Supply chain. Each release image is scanned with Trivy, and the release fails on fixable HIGH or CRITICAL vulnerabilities. CycloneDX SBOMs are attached to the GitHub release. Every image carries a signed SLSA build provenance attestation and an SBOM attestation, which you can check with
gh attestation verify(SECURITY.md). CI onmainrunsgovulncheckand a Trivy scan of dependencies, configuration and secrets, and repeats both weekly. - Upgrades. The Helm chart runs migrations in a pre-upgrade Job; outside Kubernetes, relay migrates on boot. Procedures and rollback are in Upgrading.
- Network. Relay sends no telemetry. The images bundle the catalog and fetch nothing unless
RELAY_CATALOG_VERSIONis set. When it is set, relay downloads catalog releases fromcatalog.wyolet.comand checks their sha256;RELAY_CATALOG_URLandRELAY_CATALOG_INDEX_URLpoint it at your owncatalog-server. A binary built withmake buildpins a catalog version by default whenRELAY_CATALOG_DIRis unset. - Licensing. All code is Apache-2.0. One feature, authoring custom RBAC roles, needs a license file, which is verified offline against a key compiled into the binary. OIDC, SCIM, audit and everything else work without one. License
- Images. Published images are
linux/amd64only. - Security. Private reporting, response times, scope and the deployment trust model are in SECURITY.md.
Repository
| Module | Import path | Contents |
|---|---|---|
| server | github.com/wyolet/relay |
the relay binary and its tools |
| SDK | github.com/wyolet/relay/sdk |
Go client, canonical protocol, vendor translators, embedded catalog with cost lookup |
| jobq | github.com/wyolet/relay/jobq |
Postgres-backed durable job queue |
| auth | github.com/wyolet/relay/auth |
authentication and authorization primitives: OIDC, SCIM, RBAC, sessions, signed tokens |
| secret | github.com/wyolet/relay/secret |
secret references, sealed format, per-scope key ring |
The standalone modules import nothing from the server module. Build, test and PR workflow are in CONTRIBUTING.md.
Contributing
Issues and pull requests are welcome. See CONTRIBUTING.md.
Security
Report vulnerabilities privately, as described in SECURITY.md. Do not open a public issue.
Commercial support
For managed hosting, enterprise builds or priority support, contact [email protected].
Community
Discord · X · LinkedIn · Bluesky · Reddit
License
관련 프로젝트 살펴보기
불러오는 중…