relay

module
v0.20.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: Apache-2.0

README

Wyolet Relay

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.

CI Latest release Docker image Go Reference

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

  1. Start relay with its bundled Postgres and model catalog:

    docker run -p 8080:8080 -p 8081:8081 wyolet/relay:standalone
    

    Add -v relay-data:/var/lib/postgresql/data to keep data, credentials and the generated master key across restarts.

  2. Open http://localhost:8081 and sign in as admin with 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.

  3. 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_seconds histogram 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 Gemini generateContent. 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-robin or least-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, tokens or 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 with 503 (529 on Anthropic-shaped routes) and Retry-After before 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=rbac you 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 /metrics on the control listener. The Helm chart ships two Grafana dashboards. Metrics

Operations

  • GitOps. relay apply -f plans with --dry-run and deletes omitted rows with --prune --selector. relay export renders 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 secret rotates 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_VERSION to upgrade the catalog, keep local edits as overlays that survive upgrades, and serve releases from your own catalog-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 to oci://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 on main runs govulncheck and 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_VERSION is set. When it is set, relay downloads catalog releases from catalog.wyolet.com and checks their sha256; RELAY_CATALOG_URL and RELAY_CATALOG_INDEX_URL point it at your own catalog-server. A binary built with make build pins a catalog version by default when RELAY_CATALOG_DIR is 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/amd64 only.
  • 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 business@wyolet.com.

Community

Discord · X · LinkedIn · Bluesky · Reddit

License

Apache-2.0.

Directories

Path Synopsis
app
account
Package account is the domain layer for the Account entity: what policies bind to and usage is charged to.
Package account is the domain layer for the Account entity: what policies bind to and usage is charged to.
accountsync
Package accountsync writes the caller accounts the plans call for: it reads the pending account places off each published plan view and creates, closes or reopens their rows through the account store.
Package accountsync writes the caller accounts the plans call for: it reads the pending account places off each published plan view and creates, closes or reopens their rows through the account store.
actor
Package actor carries the identity of the caller making a request.
Package actor carries the identity of the caller making a request.
adapter
Package adapter provides the generic adapter framework: a Spec type that bundles wire-shape metadata (inbound URL paths, upstream URL path, auth strategy, canonical translator, token extractor), a generic pipeline.Adapter implementation parameterised by path and auth strategy, a Registry of Specs, and a generic route mounter that iterates registered specs.
Package adapter provides the generic adapter framework: a Spec type that bundles wire-shape metadata (inbound URL paths, upstream URL path, auth strategy, canonical translator, token extractor), a generic pipeline.Adapter implementation parameterised by path and auth strategy, a Registry of Specs, and a generic route mounter that iterates registered specs.
apply
Package apply is the single loader that turns manifest documents into Postgres rows.
Package apply is the single loader that turns manifest documents into Postgres rows.
audit
Package audit records who did what on the control plane: every mutating admin action, every denial, and every login/logout, as one row per HTTP request.
Package audit records who did what on the control plane: every mutating admin action, every denial, and every login/logout, as one row per HTTP request.
authz
Package authz answers "can this actor perform this action on this resource?" — a deliberate seam so the v1 always-allow implementation can later be swapped for Casbin / OpenFGA / Keto without touching call sites.
Package authz answers "can this actor perform this action on this resource?" — a deliberate seam so the v1 always-allow implementation can later be swapped for Casbin / OpenFGA / Keto without touching call sites.
batch
Package batch is the batch subsystem: it accepts bulk inference submissions, runs each item as a background job (via the jobq module), and exposes submit/poll/cancel/results over the customer-facing /v1 surface.
Package batch is the batch subsystem: it accepts bulk inference submissions, runs each item as a background job (via the jobq module), and exposes submit/poll/cancel/results over the customer-facing /v1 surface.
budget
Package budget is the domain layer for the Budget entity: a recurring spend cap in USD over a calendar period in UTC.
Package budget is the domain layer for the Budget entity: a recurring spend cap in USD over a calendar period in UTC.
catalog
Package catalog is the composition layer: it pulls the entity stores together into an atomic in-memory Snapshot the request path can read in O(1).
Package catalog is the composition layer: it pulls the entity stores together into an atomic in-memory Snapshot the request path can read in O(1).
catalog/catalogtest
Package catalogtest builds a catalog.Catalog or catalog.Snapshot from rows held in memory, for tests outside app/catalog.
Package catalogtest builds a catalog.Catalog or catalog.Snapshot from rows held in memory, for tests outside app/catalog.
catalogembed
Package catalogembed flattens relay's live catalog snapshot into the SDK catalog document.
Package catalogembed flattens relay's live catalog snapshot into the SDK catalog document.
cataloghook
Package cataloghook is the relay side of catalog release webhooks: the public endpoint the catalog server POSTs challenges and release nudges to, and the registration that subscribes this relay to them.
Package cataloghook is the relay side of catalog release webhooks: the public endpoint the catalog server POSTs challenges and release nudges to, and the registration that subscribes this relay to them.
catalogserver
Package catalogserver serves relay-catalog releases over plain HTTP from a git mirror of the catalog repository.
Package catalogserver serves relay-catalog releases over plain HTTP from a git mirror of the catalog repository.
catalogstore
Package catalogstore is the Postgres data-access layer for the catalog kinds (provider, host, model, pricing, binding, policy, ratelimit).
Package catalogstore is the Postgres data-access layer for the catalog kinds (provider, host, model, pricing, binding, policy, ratelimit).
catalogvalidate
Package catalogvalidate is the cross-entity graph linter for the catalog repo's `data/` tree.
Package catalogvalidate is the cross-entity graph linter for the catalog repo's `data/` tree.
catalogvalidate/curation
Package curation holds a catalog repo's data conventions, layered on catalogvalidate.ValidateGraph: the named Rules, the families.yaml family and product-line checks, and the featured.yaml index check.
Package curation holds a catalog repo's data conventions, layered on catalogvalidate.ValidateGraph: the named Rules, the families.yaml family and product-line checks, and the featured.yaml index check.
catalogview
Package catalogview builds consumer-facing read projections of catalog data for the admin/UX surface ("API UX"): a model's hosts, its pricing per host, the policies that grant it.
Package catalogview builds consumer-facing read projections of catalog data for the admin/UX surface ("API UX"): a model's hosts, its pricing per host, the policies that grant it.
group
Package group is the domain layer for the Group entity — a named set of users that role bindings can name as a subject.
Package group is the domain layer for the Group entity — a named set of users that role bindings can name as a subject.
hosthealth
Package hosthealth records and reads per-host runtime reachability — the observed-state counterpart to host.Spec.
Package hosthealth records and reads per-host runtime reachability — the observed-state counterpart to host.Spec.
hostkey
Package hostkey is the domain layer for the HostKey entity — a credential the relay uses to authenticate to a Host (a serving endpoint).
Package hostkey is the domain layer for the HostKey entity — a credential the relay uses to authenticate to a Host (a serving endpoint).
httpapi
Package httpapi holds the HTTP layer for both Relay planes.
Package httpapi holds the HTTP layer for both Relay planes.
httpapi/control
Package control is the admin-plane HTTP API: /auth/*, CRUD across the catalog and tenancy kinds, /version, /master-key/*, /secret-keys, /reload.
Package control is the admin-plane HTTP API: /auth/*, CRUD across the catalog and tenancy kinds, /version, /master-key/*, /secret-keys, /reload.
httpapi/inference
Package inference is the data-plane HTTP API: /v1/* and /healthz.
Package inference is the data-plane HTTP API: /v1/* and /healthz.
httpapi/openapitest
Package openapitest checks a published OpenAPI document for what clients generated from it need: every operation identified, summarised, described and tagged, and every parameter and schema property described.
Package openapitest checks a published OpenAPI document for what clients generated from it need: every operation identified, summarised, described and tagged, and every parameter and schema property described.
key
Package key is the domain layer for the Key entity — an inbound API key the relay issues to a client.
Package key is the domain layer for the Key entity — an inbound API key the relay issues to a client.
keypool
Package keypool implements per-key circuit-breaker state and configurable Pool selection over healthy keys.
Package keypool implements per-key circuit-breaker state and configurable Pool selection over healthy keys.
license
Package license is the license-gate seam app/ code depends on.
Package license is the license-gate seam app/ code depends on.
limits
Package limits declares what admission counts and the interface that counts it.
Package limits declares what admission counts and the interface that counts it.
limits/hybrid
Package hybrid implements limits.Limiter by counting in pod memory, synced with the shared store once per interval, and by counting through the Lua limiter (app/limits/lua) the counters a stale count could push past their cap.
Package hybrid implements limits.Limiter by counting in pod memory, synced with the shared store once per interval, and by counting through the Lua limiter (app/limits/lua) the counters a stale count could push past their cap.
limits/lua
Package lua implements limits.Limiter over the Lua rate limiter in pkg/ratelimit: each atomicity group of a request's counters is reserved by one script whose keys share the group's hash tag, and every group's script goes out in one pipelined round trip.
Package lua implements limits.Limiter over the Lua rate limiter in pkg/ratelimit: each atomicity group of a request's counters is reserved by one script whose keys share the group's hash tag, and every group's script goes out in one pipelined round trip.
manifest
Package manifest converts between the catalog's YAML/JSON wire format, which references entities by name, and the app/* domain structs, which reference them by id.
Package manifest converts between the catalog's YAML/JSON wire format, which references entities by name, and the app/* domain structs, which reference them by id.
metricslog
Package metricslog is the Prometheus observer on the lifecycle spine.
Package metricslog is the Prometheus observer on the lifecycle spine.
orgwatch
Package orgwatch remembers, per pod and in memory, the provider organization each credential's served responses name, and reports an account whose credentials name different ones: those keys are separate organizations with separate upstream limits, which the account counts as one.
Package orgwatch remembers, per pod and in memory, the provider organization each credential's served responses name, and reports an account whose credentials name different ones: those keys are separate organizations with separate upstream limits, which the account counts as one.
otlpreceiver
Package otlpreceiver records model calls that clients report over OpenTelemetry instead of sending through relay.
Package otlpreceiver records model calls that clients report over OpenTelemetry instead of sending through relay.
overlay
Package overlay is the domain layer for catalog overlays: user-owned sparse spec patches applied on top of pristine catalog TEMPLATE rows to produce the EFFECTIVE rows the snapshot serves.
Package overlay is the domain layer for catalog overlays: user-owned sparse spec patches applied on top of pristine catalog TEMPLATE rows to produce the EFFECTIVE rows the snapshot serves.
payloadlog
Package payloadlog is the second lifecycle observer (after app/usagelog): it captures the full request + response bodies of opted-in requests for audit, debug, and replay, and pushes them to a Sink (file today, S3 next) off the hot path.
Package payloadlog is the second lifecycle observer (after app/usagelog): it captures the full request + response bodies of opted-in requests for audit, debug, and replay, and pushes them to a Sink (file today, S3 next) off the hot path.
pipeline
Package pipeline orchestrates one inference request over a route the plans already resolved: hold the caller's counters, walk the route's hops in order, pick a credential inside a hop with the key pool's selection and breakers, hold that credential's upstream counters, call the adapter, stream back, and settle in post-flight.
Package pipeline orchestrates one inference request over a route the plans already resolved: hold the caller's counters, walk the route's hops in order, pick a credential inside a hop with the key pool's selection and breakers, hold that credential's upstream counters, call the adapter, stream back, and settle in post-flight.
plan
Package plan folds the policy ladder into the structs the request path reads, and registers the engine controllers that keep them current.
Package plan folds the policy ladder into the structs the request path reads, and registers the engine controllers that keep them current.
plan/plantest
Package plantest builds published plans from rows held in memory, for tests outside app/plan.
Package plantest builds published plans from rows held in memory, for tests outside app/plan.
policybinding
Package policybinding is the domain layer for the PolicyBinding entity: it applies one Policy to a set of accounts inside its owner's scope (the system, a team, a project or a user).
Package policybinding is the domain layer for the PolicyBinding entity: it applies one Policy to a set of accounts inside its owner's scope (the system, a team, a project or a user).
pool
Package pool is the domain layer for the Pool entity: an ordered set of one host's keys, listed one by one or as whole provider accounts, plus the selection algorithm that picks among them.
Package pool is the domain layer for the Pool entity: an ordered set of one host's keys, listed one by one or as whole provider accounts, plus the selection algorithm that picks among them.
project
Package project is the domain layer for the Project entity — the unit inside a Team that owns Policies, Keys, and user-created HostKeys.
Package project is the domain layer for the Project entity — the unit inside a Team that owns Policies, Keys, and user-created HostKeys.
proxy
Package proxy is the second inference flow: transparent forwarding of caller-supplied upstream credentials.
Package proxy is the second inference flow: transparent forwarding of caller-supplied upstream credentials.
refcheck
Package refcheck holds the cross-row write rules a row's own Validate cannot see: a referenced row must exist, be visible to the caller, and belong to a scope the referrer may draw on; owners that mirror a spec field are re-derived from it.
Package refcheck holds the cross-row write rules a row's own Validate cannot see: a referenced row must exist, be visible to the caller, and belong to a scope the referrer may draw on; owners that mirror a spec field are re-derived from it.
revocation
Package revocation keeps the set of revoked relay-minted tokens.
Package revocation keeps the set of revoked relay-minted tokens.
role
Package role is the domain layer for the Role entity — a named set of (kinds, verbs) rules.
Package role is the domain layer for the Role entity — a named set of (kinds, verbs) rules.
rolebinding
Package rolebinding is the domain layer for the RoleBinding entity — it grants one Role to a set of subjects at one scope (global, a Team, or a Project).
Package rolebinding is the domain layer for the RoleBinding entity — it grants one Role to a set of subjects at one scope (global, a Team, or a Project).
secret
Package secret wires relay's secret resolution (the registry over env, stored and external backends) and holds the key agent that heals failed upstream keys out of band.
Package secret wires relay's secret resolution (the registry over env, stored and external backends) and holds the key agent that heals failed upstream keys out of band.
secret/stored
Package stored is relay's "stored" secret backend over Postgres: values in secret_values, sealed under per-scope data keys from the secret module's key ring (data keys in secret_data_keys, target KEK in secret_keyring), the rewriter that moves stale rows under their scope's current key, and the operator status and downgrade paths.
Package stored is relay's "stored" secret backend over Postgres: values in secret_values, sealed under per-scope data keys from the secret module's key ring (data keys in secret_data_keys, target KEK in secret_keyring), the rewriter that moves stale rows under their scope's current key, and the operator status and downgrade paths.
seed
Package seed loads a directory of manifest YAMLs into Postgres at boot.
Package seed loads a directory of manifest YAMLs into Postgres at boot.
serviceaccount
Package serviceaccount is the domain layer for the ServiceAccount entity — a non-human principal that lives inside a Project and holds Keys.
Package serviceaccount is the domain layer for the ServiceAccount entity — a non-human principal that lives inside a Project and holds Keys.
session
Package session is relay's cookie session layer: the auth module's session manager over a kv.Store, so every pod sharing the store shares the sessions.
Package session is relay's cookie session layer: the auth module's session manager over a kv.Store, so every pod sharing the store shares the sessions.
settings
Package settings is the typed-sectioned config layer.
Package settings is the typed-sectioned config layer.
settings/settingstest
Package settingstest serves settings sections from memory for tests.
Package settingstest serves settings sections from memory for tests.
settingswatch
Package settingswatch applies a value-typed settings section to a live consumer, re-applying whenever the section changes.
Package settingswatch applies a value-typed settings section to a live consumer, re-applying whenever the section changes.
settle
Package settle coalesces the post-flight writes of many served requests into shared round trips on the post-flight store: a collector groups queued settles into batches, sent once full or a short delay after their first, and a few writers send each batch as one pipelined round trip.
Package settle coalesces the post-flight writes of many served requests into shared round trips on the post-flight store: a collector groups queued settles into batches, sent once full or a short delay after their first, and a few writers send each batch as one pipelined round trip.
share
Package share revokes a shared provider account.
Package share revokes a shared provider account.
team
Package team is the domain layer for the Team entity — the outer tenancy scope that owns Projects.
Package team is the domain layer for the Team entity — the outer tenancy scope that owns Projects.
tokencount
Package tokencount keeps the bytes-to-tokens ratio relay observed on real traffic, so a caller asking "how many input tokens is this prompt" can be answered from measurement when the upstream exposes no counting endpoint.
Package tokencount keeps the bytes-to-tokens ratio relay observed on real traffic, so a caller asking "how many input tokens is this prompt" can be answered from measurement when the upstream exposes no counting endpoint.
transport/ws
Package ws is a customer-facing WebSocket transport for the inference data plane.
Package ws is a customer-facing WebSocket transport for the inference data plane.
usagelog
Package usagelog is the first consumer of pkg/lifecycle's Hook + Collector surface.
Package usagelog is the first consumer of pkg/lifecycle's Hook + Collector surface.
user
Package user owns the DB-backed user account: the row behind a login session.
Package user owns the DB-backed user account: the row behind a login session.
auth module
cmd
api-drift command
Command api-drift reports request parameters that upstream models have stopped accepting, with the evidence for each finding.
Command api-drift reports request parameters that upstream models have stopped accepting, with the evidence for each finding.
auth-schemas command
Command auth-schemas writes one JSON Schema per auth-module manifest kind (Team, Project, ServiceAccount, Role, User, Group, RoleBinding) as relay registers them: relay's rule vocabulary and its own spec fields included.
Command auth-schemas writes one JSON Schema per auth-module manifest kind (Team, Project, ServiceAccount, Role, User, Group, RoleBinding) as relay registers them: relay's rule vocabulary and its own spec fields included.
catalog-embed command
Command catalog-embed generates the SDK's embedded default catalog from the public catalog tree.
Command catalog-embed generates the SDK's embedded default catalog from the public catalog tree.
catalog-schemas command
Command catalog-schemas writes one JSON Schema per catalog kind, derived from the manifest types.
Command catalog-schemas writes one JSON Schema per catalog kind, derived from the manifest types.
catalog-server command
Command catalog-server serves relay-catalog releases from a git mirror (serve) and builds one tag's release files (build).
Command catalog-server serves relay-catalog releases from a git mirror (serve) and builds one tag's release files (build).
catalog-validate command
Command catalog-validate checks a directory of catalog YAML manifests.
Command catalog-validate checks a directory of catalog YAML manifests.
icon-import command
Command icon-import downloads provider icons listed in an OpenRouter providers dump into a directory.
Command icon-import downloads provider icons listed in an OpenRouter providers dump into a directory.
modelsdev-import command
Command modelsdev-import converts the models.dev dataset into relay-catalog YAML.
Command modelsdev-import converts the models.dev dataset into relay-catalog YAML.
payload-migrate command
Command payload-migrate copies a JSONL payload-log dump into the ClickHouse payload store, skipping rows already present.
Command payload-migrate copies a JSONL payload-log dump into the ClickHouse payload store, skipping rows already present.
relay command
Command relay runs the relay server (data and control planes) and its operator subcommands.
Command relay runs the relay server (data and control planes) and its operator subcommands.
relay-stats command
Command relay-stats prints usage events and summaries from the relay control API.
Command relay-stats prints usage events and summaries from the relay control API.
relay/web
Package web embeds the relay-ui single-page app and serves it from the control plane.
Package web embeds the relay-ui single-page app and serves it from the control plane.
Package config embeds the relay-internal definitions the binary must carry, so a deployment without this directory on disk still gets them.
Package config embeds the relay-internal definitions the binary must carry, so a deployment without this directory on disk still gets them.
internal
config
Package config centralizes all RELAY_* env var parsing for the relay binary.
Package config centralizes all RELAY_* env var parsing for the relay binary.
identity
Package identity owns the User catalog kind and the SecretRef resolution machinery used to pull credential material out of the environment, files, or (discouraged) inline literals — pydantic-SecretStr style.
Package identity owns the User catalog kind and the SecretRef resolution machinery used to pull credential material out of the environment, files, or (discouraged) inline literals — pydantic-SecretStr style.
license
Package license verifies relay's offline license file.
Package license verifies relay's offline license file.
storage
Package storage owns the Postgres connection pool and runs migrations.
Package storage owns the Postgres connection pool and runs migrations.
jobq module
migrations
postgres
Package pgmigrations embeds the postgres migration SQL files.
Package pgmigrations embeds the postgres migration SQL files.
pkg
adapters
Package adapters names the wire protocol the relay speaks to an upstream.
Package adapters names the wire protocol the relay speaks to an upstream.
catalogkind/archive
Package archive extracts a catalog release's data tarball with the limits relay and the catalog server share.
Package archive extracts a catalog release's data tarball with the limits relay and the catalog server share.
catalogkind/binding
Package binding is the domain layer for the HostBinding entity — the first-class join that declares "Model M is served by Host H, via wire adapter A, under upstream name U, priced by Pricing P."
Package binding is the domain layer for the HostBinding entity — the first-class join that declares "Model M is served by Host H, via wire adapter A, under upstream name U, priced by Pricing P."
catalogkind/embed
Package embed flattens catalog kinds into the SDK catalog document (sdk/catalog): from a parsed catalog tree (Compose) or from any Source, such as relay's live snapshot (Flatten).
Package embed flattens catalog kinds into the SDK catalog document (sdk/catalog): from a parsed catalog tree (Compose) or from any Source, such as relay's live snapshot (Flatten).
catalogkind/families
Package families reads a catalog's families.yaml: the allowlist of Model spec.family values, each with the spec.productLine values valid under it.
Package families reads a catalog's families.yaml: the allowlist of Model spec.family values, each with the spec.productLine values valid under it.
catalogkind/host
Package host is the domain layer for the Host entity — a serving endpoint the relay forwards requests to.
Package host is the domain layer for the Host entity — a serving endpoint the relay forwards requests to.
catalogkind/manifest
Package manifest reads the catalog kinds (Provider, Host, Model, Pricing, HostBinding, Policy, RateLimit) from their YAML wire form, which references entities by name, and translates them to the pkg/catalogkind domain structs, which reference them by id.
Package manifest reads the catalog kinds (Provider, Host, Model, Pricing, HostBinding, Policy, RateLimit) from their YAML wire form, which references entities by name, and translates them to the pkg/catalogkind domain structs, which reference them by id.
catalogkind/model
Package model is the domain layer for the Model entity — a container for a family of dated checkpoints (Snapshots).
Package model is the domain layer for the Model entity — a container for a family of dated checkpoints (Snapshots).
catalogkind/policy
Package policy is the domain layer for the Policy entity: a reusable rule set a policy binding applies to accounts.
Package policy is the domain layer for the Policy entity: a reusable rule set a policy binding applies to accounts.
catalogkind/pricing
Package pricing is the domain layer for the Pricing entity — a named rate sheet owned by a Host and applied to one or more Models.
Package pricing is the domain layer for the Pricing entity — a named rate sheet owned by a Host and applied to one or more Models.
catalogkind/provider
Package provider is the domain layer for the Provider entity — the vendor / author of a Model.
Package provider is the domain layer for the Provider entity — the vendor / author of a Model.
catalogkind/ratelimit
Package ratelimit is the domain layer for the RateLimit entity — a named rule set (requests / tokens / concurrency caps) attachable to a Policy, ProviderKey, or Model.
Package ratelimit is the domain layer for the RateLimit entity — a named rule set (requests / tokens / concurrency caps) attachable to a Policy, ProviderKey, or Model.
chttl
Package chttl keeps a ClickHouse MergeTree table's row TTL equal to a retention setting.
Package chttl keeps a ClickHouse MergeTree table's row TTL equal to a retention setting.
clientprofile
Package clientprofile identifies which coding agent (Claude Code, Codex, OpenCode, …) is calling the relay, so the edge can serve each one the model-list shape, error wording and attribution it expects.
Package clientprofile identifies which coding agent (Claude Code, Codex, OpenCode, …) is calling the relay, so the edge can serve each one the model-list shape, error wording and attribution it expects.
connadmit
Package connadmit admits connections to an HTTP listener: up to a cap they are served, past it they wait in a bounded FIFO for a slot for at most a fixed time, and the rest are answered with a 503 and closed.
Package connadmit admits connections to an HTTP listener: up to a cap they are served, past it they wait in a bounded FIFO for a slot for at most a fixed time, and the rest are answered with a 503 and closed.
contentcoding
Package contentcoding decodes HTTP entity bodies by their Content-Encoding.
Package contentcoding decodes HTTP entity bodies by their Content-Encoding.
coord
Package coord is cross-pod coordination for app components over a shared store.
Package coord is cross-pod coordination for app components over a shared store.
crypto
Package crypto provides AES-GCM-256 encryption primitives and master-key helpers for Relay's stored-secret subsystem, plus the claim set inference tokens carry (token_claims.go; the token format itself is auth/token).
Package crypto provides AES-GCM-256 encryption primitives and master-key helpers for Relay's stored-secret subsystem, plus the claim set inference tokens carry (token_claims.go; the token format itself is auth/token).
engine
Package engine keeps derived state consistent with a set of input rows.
Package engine keeps derived state consistent with a set of input rows.
engine/cell
Package cell owns long-lived runtime state (counters, breaker copies, rotation state, shared caches) keyed by stable ids, so the state outlives the published generations that point at it.
Package cell owns long-lived runtime state (counters, breaker copies, rotation state, shared caches) keyed by stable ids, so the state outlives the published generations that point at it.
engine/internal/celllink
Package celllink carries the link changes of a published generation from package engine to package cell.
Package celllink carries the link changes of a published generation from package engine to package cell.
filter
Package filter is a declarative, allowlist-based query engine for list endpoints.
Package filter is a declarative, allowlist-based query engine for list endpoints.
httpheader
Package httpheader holds the header sets applied at relay's HTTP edges: what is stripped from inbound requests before forwarding, what is removed from upstream responses, and what an upstream failure may carry onto the error relay writes.
Package httpheader holds the header sets applied at relay's HTTP edges: what is stripped from inbound requests before forwarding, what is removed from upstream responses, and what an upstream failure may carry onto the error relay writes.
httpmw
Package httpmw holds net/http middleware and helpers shared by relay's listeners: request body size limits, client IP resolution behind trusted proxies, and browser security headers.
Package httpmw holds net/http middleware and helpers shared by relay's listeners: request body size limits, client IP resolution behind trusted proxies, and browser security headers.
ids
Package ids generates immutable resource identifiers.
Package ids generates immutable resource identifiers.
kv
Package kv is the key-value store for short-lived operational state (counters, breaker state, locks, sessions), with an in-memory backend and a Redis-protocol backend behind the same Store interface.
Package kv is the key-value store for short-lived operational state (counters, breaker state, locks, sessions), with an in-memory backend and a Redis-protocol backend behind the same Store interface.
kv/kvtest
Package kvtest holds kv fixtures for tests: a Recording store that pins the scripts a caller runs, and (integration builds) a Dragonfly keyspace of its own per test on the server named by RELAY_TEST_REDIS_ADDR, so test packages run in parallel against one server despite fixed key names and prefix scans.
Package kvtest holds kv fixtures for tests: a Recording store that pins the scripts a caller runs, and (integration builds) a Dragonfly keyspace of its own per test on the server named by RELAY_TEST_REDIS_ADDR, so test packages run in parallel against one server despite fixed key names and prefix scans.
lifecycle
Package lifecycle is the in-process hook registry every request-runner (pipeline, proxy, future ws/batch) fires events into.
Package lifecycle is the in-process hook registry every request-runner (pipeline, proxy, future ws/batch) fires events into.
meta
Package meta holds the identity primitives every domain entity carries: UUIDv7 id, DNS-1123 slug name, free-text display name, and provenance.
Package meta holds the identity primitives every domain entity carries: UUIDv7 id, DNS-1123 slug name, free-text display name, and provenance.
metrics
Package metrics owns the Prometheus registry and the /metrics HTTP handler.
Package metrics owns the Prometheus registry and the /metrics HTTP handler.
modelref
Package modelref parses the catalog reference DSL used by Policy grants and the /catalog/resolve admin endpoint.
Package modelref parses the catalog reference DSL used by Policy grants and the /catalog/resolve admin endpoint.
otlp
Package otlp is the wire side of an OpenTelemetry receiver over OTLP/HTTP for the traces and logs signals: it reads and decodes export requests (protobuf and JSON), exposes their spans and log records in a neutral shape, and encodes the export response.
Package otlp is the wire side of an OpenTelemetry receiver over OTLP/HTTP for the traces and logs signals: it reads and decodes export requests (protobuf and JSON), exposes their spans and log records in a neutral shape, and encodes the export response.
otlp/genai
Package genai maps spans and events that follow the OpenTelemetry GenAI semantic conventions to otlp.Inference records.
Package genai maps spans and events that follow the OpenTelemetry GenAI semantic conventions to otlp.Inference records.
payload
Package payload is the storage contract for request/response body capture: the Record shape and the Sink/Reader interfaces its backends satisfy.
Package payload is the storage contract for request/response body capture: the Record shape and the Sink/Reader interfaces its backends satisfy.
payload/clickhouse
Package clickhouse provides a ClickHouse-backed implementation of payload.Sink, payload.Reader, and payload.Closer — the "text bodies in ClickHouse" backend for the Logs view.
Package clickhouse provides a ClickHouse-backed implementation of payload.Sink, payload.Reader, and payload.Closer — the "text bodies in ClickHouse" backend for the Logs view.
payload/dedup
Package dedup splits a JSON request body into a skeleton and content-addressed pieces, and rebuilds the exact bytes from them.
Package dedup splits a JSON request body into a skeleton and content-addressed pieces, and rebuilds the exact bytes from them.
payload/file
Package file is the JSONL file backend for payload logging: one Record per line.
Package file is the JSONL file backend for payload logging: one Record per line.
payload/s3
Package s3 is the object-store backend for payload logging: one JSON object per Record.
Package s3 is the object-store backend for payload logging: one JSON object per Record.
ratelimit
Package ratelimit implements a sliding-window-counter rate limiter with a two-phase Reserve/Commit API.
Package ratelimit implements a sliding-window-counter rate limiter with a two-phase Reserve/Commit API.
reqbody
Package reqbody builds outbound HTTP request bodies over an in-memory buffer that stop referencing the buffer once the transport is done with it.
Package reqbody builds outbound HTTP request bodies over an in-memory buffer that stop referencing the buffer once the transport is done with it.
reqid
Package reqid gives each HTTP request a relay-minted ULID, echoes it as X-Relay-Request-ID, and carries it with a request-scoped logger in the context.
Package reqid gives each HTTP request a relay-minted ULID, echoes it as X-Relay-Request-ID, and carries it with a request-scoped logger in the context.
secret/oauth
Package oauth resolves OAuth credentials for the relay's secret layer.
Package oauth resolves OAuth credentials for the relay's secret layer.
secret/onepassword
Package onepassword resolves secret.KindOnePassword refs via the official 1Password Go SDK and a service-account token.
Package onepassword resolves secret.KindOnePassword refs via the official 1Password Go SDK and a service-account token.
slug
Package slug derives DNS-1123-compatible identifiers from free-text display names, with deterministic collision suffixes.
Package slug derives DNS-1123-compatible identifiers from free-text display names, with deterministic collision suffixes.
sse
Package sse holds server-sent-events helpers for the response path.
Package sse holds server-sent-events helpers for the response path.
transport
Package transport defines the transport-agnostic Message and Channel types that carry request and response payloads between a transport and a processing pipeline.
Package transport defines the transport-agnostic Message and Channel types that carry request and response payloads between a transport and a processing pipeline.
usage
Package usage defines the per-request usage Event, the Sink and Reader interfaces its storage backends implement, and the in-memory filtering and aggregation shared by scan-style backends.
Package usage defines the per-request usage Event, the Sink and Reader interfaces its storage backends implement, and the in-memory filtering and aggregation shared by scan-style backends.
usage/clickhouse
Package clickhouse provides a ClickHouse-backed implementation of usage.Sink, usage.Reader, and usage.Closer.
Package clickhouse provides a ClickHouse-backed implementation of usage.Sink, usage.Reader, and usage.Closer.
usage/file
Package file is the JSONL file backend for usage logging: a Sink that appends one event per line and a Reader that scans the same file.
Package file is the JSONL file backend for usage logging: a Sink that appends one event per line and a Reader that scans the same file.
usage/postgres
Package postgres implements usage.Sink, usage.Reader, and usage.Closer backed by PostgreSQL.
Package postgres implements usage.Sink, usage.Reader, and usage.Closer backed by PostgreSQL.
usage/usagetest
Package usagetest is the conformance suite every usage.Reader backend runs: one fixed event fixture, one table of queries per Reader method, and the results every backend must return for them.
Package usagetest is the conformance suite every usage.Reader backend runs: one fixed event fixture, one table of queries per Reader method, and the results every backend must return for them.
usage/valkey
Package valkey is a TTL-bounded usage Sink + Reader backed by pkg/kv.
Package valkey is a TTL-bounded usage Sink + Reader backed by pkg/kv.
wal
Package wal is a durable write-ahead log for asynchronous sinks.
Package wal is a durable write-ahead log for asynchronous sinks.
Package schemas embeds the generated JSON Schemas for the manifest kinds so the relay can serve them at /api/schemas/{version}/{kind}.
Package schemas embeds the generated JSON Schemas for the manifest kinds so the relay can serve them at /api/schemas/{version}/{kind}.
sdk module
secret module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL