# Overview **Last updated:** 2026-11-27T14:16:11-03:00 (UTC-3) ## The problem A company that adopts AI soon has several teams calling several providers: one uses OpenAI, another Anthropic, a third an open model in its own cloud. Each one has its own key, pasted into environment variables scattered everywhere. Nobody can say how much each team spent yesterday, which prompt went out with a customer's CPF, which model went down at 3 a.m., or whether that new app is still sending data to a provider the company stopped using. ## What m7gtw does **m7gtw** sits between your apps and the AI providers. Apps talk to **a single, OpenAI-compatible API**, using a gateway key. The gateway decides which provider and model each request goes to and applies the rules of the team that owns the key: allowed models, budget, guardrails. It also measures tokens, cost and latency and records the full journey of every call. It runs **on your infrastructure**, with your PostgreSQL, as a binary, a container, a Docker Compose setup or a Helm chart. Nothing passes through a third-party service you have not configured. ## The pillars | Pillar | What you get | |---|---| | **One API for every model** | Ready-made provider presets (OpenAI, Anthropic, Gemini and Vertex, Bedrock, Azure, Mistral, Groq, Cohere and dozens of others) and media (image, speech, transcription, video). The gateway translates Chat Completions into each one's format. | | **Reliability** | Fallback across providers, routing by weight, latency, cost or the meaning of the question, circuit breaker and emergency stop. | | **Cost under control** | Prices read automatically from public catalogs, estimated cost per call, budgets and token limits per key, team or end user. | | **Governance** | Virtual keys per team, organizations, SSO (OIDC), SCIM, role-based permissions and an audit trail of who changed what. | | **Content safety** | Input and output guardrails that mask or block sensitive data, with integrations such as Azure Content Safety, Presidio, Lakera and Bedrock Guardrails. | | **Visibility** | Request logs, analytics, OpenTelemetry traces, Prometheus metrics, alerts and log destinations (S3, Datadog, Langfuse...). | | **Quality** | Evals: datasets, experiments, LLM judges, rules on real traffic and annotation queues. | | **Tools and agents** | MCP servers and A2A agents behind the same access control. | ## How the pieces fit together ``` Your apps, SDKs and agents Operators and teams (OpenAI, Anthropic, Google SDK) (console /ui, admin API) │ │ ▼ ▼ ┌────────────────────────────── m7gtw ───────────────────────────────┐ │ key and team → guardrails → budget → cache → routing │ │ → provider ─────── usage metering, cost, logs, traces, evals │ └────────────────────────────────────────────────────────────────────┘ │ │ │ ▼ ▼ ▼ AI providers PostgreSQL (yours) OTLP · Prometheus · alerts ``` The detailed path of a request is in [How it works](/docs/start/how-it-works/). ## Who it is for - **Platform teams:** give each product team a key with the right models and a budget, and see everything in one place. - **Developers:** change the SDK's base URL and get fallback, caching and observability without changing their code. - **Security and compliance:** define what can go out to a provider, audit who did what and keep the data on their own infrastructure. - **Finance:** see cost per team, model and call, with budgets that stop overspending before it happens. ## Next steps 1. [Quickstart](/docs/start/quickstart/): bring up the gateway and make your first call in minutes. 2. [Concepts](/docs/start/concepts/): the vocabulary that appears in the console and the configuration. 3. [Features](/docs/features/feature-providers/): each area in detail. # Quickstart **Last updated:** 2026-11-27T14:53:32-03:00 (UTC-3) In about ten minutes you run m7gtw on your machine with Docker Compose, make a first call through it, sign in to the console, create a key for an app and find the API reference. At the end, [choose your deploy](#choose-your-deploy) for a real environment, and keep the [tips](#tips) at hand. Every command on this page runs from the root of the source tree, and continuous integration runs them, in this order, whenever this page, the Compose files or the image's build files change, and before every version. ## What you need - **Docker** with the Compose plugin (`docker compose version` answers): Docker Engine on Linux, or Docker Desktop or OrbStack on macOS and Windows. The gateway image is built for `linux/amd64` and `linux/arm64`. - **Git**, to get the files; a local build also records the commit it came from. - **Python 3** for the secrets script (standard library only). - **The deployment files**: the Compose file, the example configuration and the secrets script live at the root of the source tree. - **Port 8080 free on 127.0.0.1**, or another one through `GATEWAY_PORT` ([tips](#ports)). - **An OpenAI API key** for the example model. Without one the gateway still starts and everything but the call to OpenAI works; other providers come later, through the console. ## 1. Get the deployment files Check out the version you deploy, so that the Compose file and the configuration match the image: ```bash git clone https://github.com/m7gtw/gateway.git m7gtw cd m7gtw git checkout v # the release you deploy; skip it to follow the latest source ``` ## 2. Get the gateway image Compose runs the image that the variable **`GATEWAY_IMAGE`** names, `gateway:local` when it is unset. Set it once in the shell you run Compose from. **The published image.** Each release publishes the image to the GitHub Container Registry as `ghcr.io/m7gtw/gateway:`, for linux/amd64 and linux/arm64, under its own version tag only: there is no `latest`, and a version is never rebuilt in place. The release candidates published so far (`0.0.1-rc.N`) are **private**; the first public release is `0.0.1`. Once it is out: ```bash export GATEWAY_IMAGE=ghcr.io/m7gtw/gateway:0.0.1 docker pull "$GATEWAY_IMAGE" ``` Pulling first shows a sign-in or name error on its own, before anything starts. The start command below never builds: when the image is not on the machine, Compose pulls it (its default `pull_policy: missing`), and when it cannot, the start fails instead of building something you did not choose under that name. In production pin the digest that [RELEASED.md](https://github.com/m7gtw/gateway/blob/main/RELEASED.md) records for the version (`ghcr.io/m7gtw/gateway@sha256:...`). If you were given access to a private release candidate, sign in first with `docker login ghcr.io` and a GitHub token with the `read:packages` scope. **Build it locally.** Until the first public release, this is the way; it needs only Docker and the checkout: ```bash export GATEWAY_IMAGE=gateway:local scripts/build-image.sh "$GATEWAY_IMAGE" ``` The first build downloads the build images and the dependencies and takes a few minutes; later builds reuse the cache. If the machine already has a `gateway:local` image, the build moves that tag to the new image and the old one stays behind untagged (`` in `docker images`); to keep it, pick another name before building, such as `export GATEWAY_IMAGE=gateway:quickstart`. Either way, the image says what it is: ```bash docker run --rm "$GATEWAY_IMAGE" version ``` It prints one JSON line with the `version`, the source `revision`, whether the tree had uncommitted changes (`modified`), and the `platform`. More on the image's contents in [building the image](/docs/operate/deployment-modes/#building-the-image). ## 3. Generate the local secrets Put your OpenAI key in the environment first; the script copies it into an ignored local file, and nothing else keeps it: ```bash export OPENAI_API_KEY=sk-... ``` ```bash python3 scripts/bootstrap-local-secrets.py --target docker ``` The script creates `deploy/docker/.env.local` and three tokens in `deploy/docker/`, all with `0600` permissions and ignored by Git: - `admin-token.env.local`: the console administrator's sign-in; - `viewer-token.env.local`: a read-only sign-in; - `client-token.env.local`: a client key ready for the first call. The gateway stores only the SHA-256 of these tokens, never the value. `.env.local` also holds `GATEWAY_DATABASE_PASSWORD`, the password of the Compose PostgreSQL, the `GATEWAY_DATABASE_URL` that uses it, the console session and provider encryption keys, and `GATEWAY_ANALYTICS_STORE_PASSWORD`, used only by the optional analytics store. Without `OPENAI_API_KEY` in the environment it writes a placeholder. Running the script again keeps every value already there, so it never changes a password a volume was created with. A file written by 0.0.1-rc.2 or earlier has the passwords as `GATEWAY_POSTGRES_PASSWORD` and `GATEWAY_CLICKHOUSE_PASSWORD`: the script copies each to its new name with the same value, keeps the old key until you remove it, and warns if both names hold different values ([the renamed infrastructure names](/docs/operate/operations/#upgrading-from-001-rc2-infrastructure-names)). ## 4. Start the gateway ```bash docker compose --env-file deploy/docker/.env.local -f deploy/docker/compose.yaml up --no-build -d --wait ``` Three services start: the gateway, a PostgreSQL with its data in the `gateway_db` volume, and an OpenTelemetry Collector. `--wait` returns once the gateway's health check passes, which took about 40 seconds on the validation machine (the database migrations run on the first start). `--no-build` runs the image `GATEWAY_IMAGE` names, pulling it if it is not on the machine, and never builds one. Check that it is ready: ```bash curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/health/ready ``` It prints `200`. The bundled configuration also serves Prometheus metrics at `http://localhost:8080/metrics` ([observability](/docs/features/observability/#metrics-prometheus)). An optional analytics store (ClickHouse) for large deployments starts only when you add `--profile analytics-store` to the start command; you do not need it here ([analytics store](/docs/features/analytics-store/)). ## 5. Make your first call The example configuration (`config/gateway.yaml`) routes the model alias `chat-default` to `gpt-4o-mini` on OpenAI, and accepts the client key from step 3: ```bash export TOKEN=$(cut -d= -f2- deploy/docker/client-token.env.local) curl -s http://localhost:8080/v1/chat/completions \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"model":"chat-default","messages":[{"role":"user","content":"Hello!"}]}' ``` The answer is an OpenAI Chat Completions object. With the placeholder key, OpenAI refuses the call and the gateway answers with an error instead of a completion: put your key in `OPENAI_API_KEY` in `deploy/docker/.env.local` and run the start command again, which recreates the gateway with it. Any OpenAI-compatible SDK works by changing the base URL: ```python import os from openai import OpenAI client = OpenAI(base_url="http://localhost:8080/v1", api_key=os.environ["TOKEN"]) print(client.chat.completions.create(model="chat-default", messages=[{"role": "user", "content": "Hello!"}]).choices[0].message.content) ``` The Anthropic and Google SDKs work the same way; see [official SDKs](/docs/reference/sdk-compatibility/). ## 6. Open the console The console is served by the gateway itself: ```bash curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/ui/ ``` Open **http://localhost:8080/ui/** in a browser and sign in with the administrator token: ```bash cut -d= -f2- deploy/docker/admin-token.env.local ``` In the console you: - see the call you just made in **Logs → Requests**, with tokens, latency and the team; - connect other providers in **Providers** (the **Integrations** tab lists the ready-made presets), then route a model alias to them in **Model catalog**; - try models in the **Playground**; - follow usage and cost on the home page, **Usage**. The [console guide](/docs/features/console/) describes every page. ## 7. Create a key for an app In **Virtual keys**, create a key for the `platform` team, with the `chat-default` model and the chat route. The value is shown **only once**: store it in your vault or in the app's secret store. The call from step 5 works the same way with it, and **Logs → Requests** shows the app's name. Expiry is optional: the key never expires unless you choose a date or a duration ([key lifecycle](/docs/features/key-policy/)). ## 8. Explore the API reference The interactive API reference (Swagger UI) and the OpenAPI contract are served by the gateway too: ```bash curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/docs/swagger/ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/openapi.yaml ``` Open **http://localhost:8080/docs/swagger/**. This documentation site is published apart from the gateway; see [where the documentation site lives](/docs/operate/deployment-modes/#documentation-site). ## 9. Look after it The commands you will use day to day: ```bash docker compose --env-file deploy/docker/.env.local -f deploy/docker/compose.yaml ps ``` ```bash docker compose --env-file deploy/docker/.env.local -f deploy/docker/compose.yaml logs --tail 20 gateway ``` The gateway logs one JSON object per line and never logs prompts, responses or credentials; add `-f` to follow them. Check a configuration change before you restart with it (`configuration valid`, or the error and a non-zero exit code): ```bash docker compose --env-file deploy/docker/.env.local -f deploy/docker/compose.yaml exec gateway /gateway validate ``` Back up the database, above all before an upgrade: ```bash docker compose --env-file deploy/docker/.env.local -f deploy/docker/compose.yaml exec -T db pg_dump -U gateway gateway > gateway-backup.sql ``` Keep `deploy/docker/.env.local` with the backup: without its `GATEWAY_PROVIDER_ENCRYPTION_KEY`, the provider credentials stored in the database cannot be opened. ## 10. Shut it down ```bash docker compose --env-file deploy/docker/.env.local -f deploy/docker/compose.yaml down ``` `down` keeps the database volume: the next start finds your keys, providers and logs. To delete everything, data included: ```bash docker compose --env-file deploy/docker/.env.local -f deploy/docker/compose.yaml down -v ``` `down -v` cannot be undone; never use it as a rollback. ## Choose your deploy The same gateway, configuration format and console run in every mode; what changes is how the configuration, the secrets and PostgreSQL reach it. | Mode | When | Start here | | --- | --- | --- | | **Docker Compose** | one machine, evaluation, a small team | this page; [Docker Compose](/docs/operate/deployment-modes/#docker-compose) for the variables | | **Compose with your own infrastructure** | the gateway in a container, your PostgreSQL and Collector | [external infrastructure](/docs/operate/deployment-modes/#external-infrastructure) | | **Helm** | Kubernetes, with values, a bundled or external PostgreSQL, Ingress and ServiceMonitor | [installing with Helm](/docs/operate/operations/#installing-with-helm) | | **Kustomize** | Kubernetes from plain manifests and your overlays | [installing with Kustomize](/docs/operate/operations/#installing-with-kustomize) | | **Native binary** | a VM or a host without containers; no Node or Docker needed | [binary and NPX](/docs/operate/deployment-modes/#binary-and-npx), [CLI](/docs/reference/cli/) | | **NPX** | the same binary, launched through Node | [binary and NPX](/docs/operate/deployment-modes/#binary-and-npx) | | **Offline bundle** | an environment without internet access | [offline bundle](/docs/operate/offline-bundle/) | Every mode needs a PostgreSQL; Compose, the Helm chart, the Kustomization and the offline bundle bring one, and the binary and NPX use yours ([managed PostgreSQL](/docs/operate/managed-postgres/)). Before production, read [security and trust](/docs/security/trust/) and [operations](/docs/operate/operations/); on Kubernetes, then follow [run on Kubernetes in production](/docs/operate/kubernetes-production/), from several zones to several regions. ## Tips ### Ports - The gateway listens on `127.0.0.1:8080` only, so nothing outside your machine reaches it. `GATEWAY_PORT=9090` before the start command moves it to another port. - PostgreSQL and the Collector publish no port to the host. - Behind a reverse proxy or on another machine, serve HTTPS at the edge and set `admin.allow_insecure_http: false` ([hardening](/docs/security/hardening/)). ### Health checks - `GET /health/live` answers `200` while the process runs. `GET /health/ready` answers `200` once the configuration is loaded and the server is up (the port opens only after the database is reached and migrated), and `503` as soon as the replica starts shutting down. The Helm chart's probes use the same two paths. - The image's own health check is `/gateway healthcheck` (no shell in the image); Compose runs it every 10 seconds ([healthcheck](/docs/reference/cli/#healthcheck)). - `docker compose ... ps` shows `healthy` once the check passes. A gateway stuck in `starting` or restarting usually names its problem in the first lines of its logs, such as a missing variable. ### Logs and telemetry - Logs go to stdout as JSON, and to the bundled Collector over OTLP; traces go there too. Point the Collector at your backend in `deploy/base/collector.yaml` ([observability](/docs/features/observability/)). - Every answer carries `X-Request-Id`; give it to whoever reads the logs, and find the call in **Logs → Requests**. ### Your configuration - `config/gateway.yaml` is mounted read-only into the container. To use your own, copy it and point `GATEWAY_CONFIG_FILE` at the copy (an absolute path) before the start command; run the start command again to apply a change. - Many settings can also change from the console without a restart; [what to configure where](/docs/reference/configuration-parity/) says which, and which need one. - Secrets never go in the YAML: the YAML names the variable (`api_key_env: OPENAI_API_KEY`) and `.env.local` or your secret store holds the value. ### Upgrades 1. Read the [changelog](https://github.com/m7gtw/gateway/blob/main/CHANGELOG.md) of the new version. 2. Back up the database ([step 9](#9-look-after-it)). 3. Check out the new version's files, set `GATEWAY_IMAGE` to its image and pull it (or build it), then run the start command again: Compose recreates the gateway, which applies the new migrations on start. ```bash export GATEWAY_IMAGE=ghcr.io/m7gtw/gateway: docker pull "$GATEWAY_IMAGE" docker compose --env-file deploy/docker/.env.local -f deploy/docker/compose.yaml up --no-build -d --wait ``` A rollback does not undo migrations: going back means restoring the backup taken before the upgrade ([upgrading and rolling back](/docs/operate/operations/#upgrading-and-rolling-back)). ### Where the parameters are documented - [Parameter registry](/docs/reference/parameter-registry/): every setting, with its default, bounds, YAML key, environment variable and console place. - [What to configure where](/docs/reference/configuration-parity/): the YAML, the API and the console, and which one wins. - [Inference flags](/docs/reference/inference-flags/) and [edition defaults](/docs/operate/edition-defaults/): the feature flags and their defaults. - [CLI](/docs/reference/cli/): the commands and the process variables (`GATEWAY_CONFIG`, `GATEWAY_DATABASE_URL`, ...). - [Deployment modes](/docs/operate/deployment-modes/): the variables of each mode (`GATEWAY_IMAGE`, `GATEWAY_PORT`, `GATEWAY_CONFIG_FILE`, `GATEWAY_ENV_FILE`). ## Next steps - [Concepts](/docs/start/concepts/): providers, models, keys, teams and flags. - [Providers and models](/docs/features/feature-providers/): connect other providers and create aliases. - [Access and governance](/docs/features/feature-access/): teams, roles, SSO and budgets. - [Security and trust](/docs/security/trust/): before you go to production. # Concepts **Last updated:** 2026-10-28T13:54:53-03:00 (UTC-3) The vocabulary that appears in the console, the API and the configuration YAML. ## Provider A connection to an AI service: OpenAI, Anthropic, Bedrock, a vLLM on your network. It has a **protocol** (the format it speaks: `openai`, `anthropic`, `gemini`, `bedrock`...), a **base URL** and a **credential**. The credential can be an environment variable, a file, a vault or the cloud identity. There are 128 **presets**, prefilled connections for well-known providers. [Providers](/docs/features/providers/). ## Model (alias) The name apps use in the `model` field, such as `chat-default`. An alias points to one or more **targets**, each a provider + provider model pair (`openai` + `gpt-4o-mini`). With more than one target, fallback and routing come into play. The app never needs to know which provider served it. ## Capability What an alias can do: `chat`, `responses`, `messages`, `embeddings`, `images`, `audio_speech`, `audio_transcriptions`, `video`, `rerank` and others. A request for a capability the alias does not declare is rejected with 422. [Capabilities](/docs/features/capabilities/). ## Virtual key The credential an app uses to call the gateway, in place of the provider's key. It belongs to a **team** and defines which **models** and which **routes** (scopes such as `route:chat`) the app can use. It can also expire, be revoked or be rotated without downtime. The gateway stores only the hash; the value appears once, at creation. [Access control](/docs/features/access-control/). ## Team and organization The **team** is the unit of ownership and limits: keys, budgets, guardrail policies, eval datasets and captures belong to a team. The **team policy** is the ceiling on what any of its keys can do. **Organizations** group teams under a common model ceiling. [Organizations](/docs/features/organizations/). ## Console user and role Who signs in to the console: the bootstrap token, named users or SSO (OIDC). The **role** defines what each one can see and change: - global `admin` and `viewer`; - `team_admin` and `team_viewer`, limited to their own teams; - `operator` and `user`. [Permissions](/docs/features/access-control/). ## Flag Each feature has a flag under `features` in the YAML. Some can also be turned on from the console. A flag that is off makes the feature not exist: the route responds 404, and the menu disappears. **A flag never grants permission:** it enables the behavior, and who can use it is still decided by key, team and role. The [flag reference](/docs/reference/inference-flags/) has the list. ## Configuration: YAML and console The **YAML** (`config/gateway.yaml`) is the declarative base, versioned in your repository. The **console** and the admin API write **overrides** to PostgreSQL, with versioning and audit, and they can be reverted to the YAML. Secrets never live in the YAML: it only references the variable name. ## Request, `request_id` and trace Every call gets a `request_id`, returned in the `X-Request-Id` header, and a W3C `traceparent`. Both travel all the way to the provider and appear in the logs, the audit and the traces. With either of them, you can reconstruct the whole journey. [Observability](/docs/features/observability/). ## Usage, valuation and budget - **Usage:** the tokens and latency measured on each call. - **Valuation:** the call's estimated cost, at the catalog price. - **Budget and TPM:** limits in dollars and tokens that the gateway **reserves before** sending and settles afterwards, stopping the excess. [Costs and pricing](/docs/features/feature-costs/). # How it works **Last updated:** 2026-10-28T13:54:53-03:00 (UTC-3) What happens to a request, from the moment it arrives until the response goes back to the app. Each stage exists only if its flag is on. ## The path of a call 1. **Correlation.** The request gets a `request_id` and a `traceparent`, or inherits the ones the client sent. Both are carried through to the end. 2. **Authentication.** The client's key is checked by its hash, in PostgreSQL, on every request. A revoked or expired key gets 401; if the database is down, a managed key fails closed. JWTs from an IdP and ephemeral realtime tokens are also accepted. 3. **Authorization.** The gateway checks the route scope (`route:chat`...), the key's model allowlist, the team policy and the organization ceiling. Anything outside that: 403. 4. **Validation.** The body is read with a size limit and a deadline, and the JSON must be unambiguous. The alias must declare the requested capability. 5. **Input guardrails.** The team's policies mask or block sensitive data before anything is sent. 6. **Limits and budget.** RPM is checked, and budget and TPM are **reserved** atomically in PostgreSQL. No balance left: 429. 7. **Cache.** With the policy on, a hit in the exact or semantic cache returns the response without calling the provider. Authorization and limits have already been applied before the cache. 8. **Routing.** Among the alias's targets, the gateway chooses by weight, latency, cost, load, tags or the meaning of the question, respecting the circuit breaker and each target's concurrency ceiling. 9. **Translation and sending.** If the provider does not speak the OpenAI format, the protocol adapter translates the request, or refuses with 422 whatever has no equivalent. The provider credential is added here; the client's key never leaves the gateway. 10. **Fallback.** A transport error, 429 or 5xx before the first byte of the response makes the gateway try the next target. Once the response has started, there is no new attempt. 11. **Response.** The response comes back in the OpenAI format, streaming when requested. Output guardrails can mask or block non-streaming responses. 12. **Measurement.** The gateway records tokens, latency, status and estimated cost, settles the budget reservation, feeds analytics, metrics and traces and, if configured, sends the capture to evals and the record to log destinations. Prompts and responses do not go to logs or telemetry. ## Where each piece lives | Piece | Role | |---|---| | **Gateway** (Go binary) | Stateless; several replicas behind a load balancer | | **PostgreSQL** | Keys, managed configuration, usage, budgets, audit, evals. It is the system's only state | | **Redis or Memcached** (optional) | Exact cache shared between replicas | | **OTLP Collector, Prometheus, Grafana** (optional) | Telemetry outside the request path; the gateway works without them | | **Console** (`/ui`) and **documentation** (`/docs/`) | Served by the gateway itself | ## Failures - **Database down:** inference continues with the last configuration snapshot. Managed keys, RPM and budgets fail closed. - **Provider down:** fallback and circuit breaker. - **Cache down:** the gateway continues without a cache. - **Incident:** the emergency stop cuts all inference traffic at once. [Continuity](/docs/security/business-continuity/) · [Incident response](/docs/security/incident-response/). # Support and contact **Last updated:** 2026-11-27T14:29:02-03:00 (UTC-3) Where to look when something does not work, and how to reach the people behind m7gtw. ## Find the answer yourself first Most questions are answered faster by the gateway than by a person: 1. **Read the error.** Every response carries a `request_id` (the `X-Request-Id` header). Look it up in the console's request log to see the route chosen, each provider attempt and the reason for a refusal. [Observability](/docs/features/observability/) explains what is recorded. 2. **Check the configuration.** `gateway validate` checks the YAML and the secret references without starting the server ([CLI](/docs/reference/cli/)). 3. **Check the health of the installation.** [Operations](/docs/operate/operations/) lists the probes, the metrics and the alerts worth watching. 4. **Search this documentation.** The whole guide is also one file, `llms-full.txt`, served next to the site's `llms.txt` (at `/docs/llms-full.txt` on a gateway that serves the documentation), which an assistant can read. ## Contact Write to **`contact@m7gtw.com`** for questions about the product, licensing and editions, a problem you could not solve with the steps above, or a correction to this documentation. The product's site is [m7gtw.com](https://m7gtw.com). When you report a problem, include: - the gateway version (`gateway version` prints it as one line); - how it is deployed (Docker Compose, Kubernetes, the native binary or the NPX launcher); - the `request_id` of an affected request and the time it happened; - what you expected and what happened. Never send keys, tokens, prompts, responses or other customer data. If a log or a configuration file is needed, remove the secrets first. ## Security reports A suspected vulnerability follows the [disclosure policy](/docs/security/vulnerability-disclosure/), not a public issue or an ordinary support message. Its private channel is the same address, `contact@m7gtw.com`. ## Help for your own users The address above is for operators of the gateway. To point the people who use *your* console at your own help desk, set `support_url` in [console branding](/docs/features/console-branding/): the login page then shows a **Get help** link to it. # Providers and models **Last updated:** 2026-11-27T14:16:11-03:00 (UTC-3) Switching providers, or using several at once, shouldn't require changing your apps' code. In m7gtw, apps call an **alias** (`chat-default`, `summary`, `embeddings`), and the operator decides which provider and model serve it behind the scenes. For the OpenAI format, the response comes out the same no matter where it came from. ## What's available | Feature | What it does | Flag | Learn more | |---|---|---|---| | **Provider presets** | Ready-made connections for OpenAI, Anthropic, Gemini, Vertex AI, Bedrock, Azure, Mistral, Groq, Cohere, DeepSeek, xAI, OpenRouter, Together, Fireworks and dozens of others, created in **Providers → Add provider** | `provider_management` | [Providers](/docs/features/providers/) | | **Chat Completions translation** | A chat alias can point to Anthropic, Gemini or Vertex, Bedrock, Cohere, SageMaker or OCI, or to the OpenAI Responses API; the adapter translates the request and the response | (per protocol) | [Capabilities](/docs/features/capabilities/) | | **Any route to any provider** | Messages, Responses and GenerateContent clients reach OpenAI, Anthropic, Gemini, Cohere and Bedrock models through one canonical format, with what cannot cross refused or announced | `anthropic_messages`, `openai_responses`, `gemini_generate_content` | [Protocol translation](/docs/features/protocol-translation/) | | **Native APIs** | Anthropic Messages (`/v1/messages`), Gemini GenerateContent and OpenAI Responses in their original format, for SDKs that expect it, such as Claude Code | `anthropic_messages`, `gemini_generate_content`, `openai_responses` | [Capabilities](/docs/features/capabilities/) | | **Media** | Image, speech, transcription and video, with adapters for ElevenLabs, Deepgram, Stability, Replicate, Fal, Black Forest Labs and Runway | `image_generation`, `audio_speech`, `audio_transcriptions`, `video_generation` | [Capabilities](/docs/features/capabilities/) | | **Speech** | Clips streamed as they arrive, a cut clip told to the client and recorded as a failure, whole clips only per alias, voice discovery, and Amazon Polly, Azure AI Speech and Gemini text to speech | `audio_speech`; `speech_buffer`, `speech_voices`, `speech_polly`, `speech_azure`, `speech_gemini` (off by default) | [Speech](/docs/features/speech/) | | **Cloud identity** | Bedrock and SageMaker with an AWS profile, Vertex with Google ADC, OCI with an API key; the credential stays where it is. Bedrock can use a VPC endpoint or proxy declared in the YAML | (per provider) | [Providers](/docs/features/providers/#custom-endpoint) | | **Local inference** | Model servers you host as pools of replicas: llama.cpp with Metal, MLX and Ollama on a Mac, vLLM on NVIDIA through Docker or Kubernetes, or any of them on the CPU. The gateway health-checks each replica, routes by replica load, and can start, stop and restart them; each GPU capability has its own flag | `local_inference`, `local_inference_gpu`, `local_inference_metal`, `local_inference_nvidia`, `local_inference_mig` | [Local inference](/docs/features/local-inference/) | | **Model discovery** | Lists a connection's models and prepares disabled aliases for review; wildcard aliases | `provider_model_discovery`, `catalog_onboarding` | [Providers](/docs/features/providers/) | | **Model aliases** | Another client name for a canonical model (`alias_of`), with its targets, policies and access; granting the canonical model grants the alias, not the reverse | `model_aliases` | [Model aliases](/docs/features/model-aliases/) | | **Moving aliases** | A name such as `claude-sonnet-latest` that serves the newest declared version of a model family on one provider (`follows`), recording the resolved model on usage and reporting every change | `model_follows` | [Moving aliases](/docs/features/model-aliases/#moving-aliases-follows) | | **Codex model picker** | The Codex CLI's `/model` picker lists the Responses aliases the key may call, in the CLI's own catalog shape | `codex_model_catalog` | [Providers](/docs/features/providers/#codex-model-picker) | | **Model catalog** | Public metadata (context, parameters, price) from OpenRouter, DeepInfra, the community cost map and models.dev | `external_model_catalog` | [Automatic pricing](/docs/features/automatic-pricing/) | | **Account model discovery** | Lists the models your OpenAI, Anthropic, Gemini, Groq and xAI accounts can use, with the configured provider credentials; requires `external_model_catalog` | `authenticated_provider_catalog` | [Automatic pricing](/docs/features/automatic-pricing/) | | **Public model research** | Original licensed offers, same-offer filters, provider/selected/workload comparison, attributed coding/value and source lifecycle/history/RSS; no inference grant | `model_registry` and independently cataloged research flags | [Research registry](/docs/features/public-model-research/) | | **Public model Hub** | Explicit safe alias publication, anonymous metadata only and separate audited unpublish action; no inference authorization | `public_model_hub` | [Model registry](/docs/features/model-registry/) | | **Public hub listings** | Opt-in listing of published MCP servers, A2A agents and skills (published registry revision only) next to models; allowlisted fields, no URLs, credentials or grants | `public_hub_mcp_servers`, `public_hub_agents`, `public_hub_skills` | [Public hub](/docs/features/public-hub/) | | **Connection test** | A real call to a model from the console, before releasing the alias | (console, admin) | [Console](/docs/features/console/) | | **Decisions** | OpenAI Decisions and System One (TypeSafe, Cloudflare, vLLM Semantic Router) with explicit translation | `openai_decisions`, `systemone_decisions` | [Decisions](/docs/features/decisions/) | ## One alias with two providers ```yaml providers: - {id: openai, protocol: openai, base_url: https://api.openai.com/v1, api_key_env: OPENAI_API_KEY} - {id: anthropic, protocol: anthropic, base_url: https://api.anthropic.com/v1, api_version: "2023-06-01", api_key_env: ANTHROPIC_API_KEY} models: - id: chat-default targets: - {provider: openai, model: gpt-4o-mini} - {provider: anthropic, model: claude-haiku-4-5} ``` The app calls `chat-default`. If OpenAI fails before responding, the gateway tries Anthropic, and the app receives the response in the same format. Details in [routing and resilience](/docs/features/feature-routing/). # Model registry and public Hub **Last updated:** 2026-11-21T09:54:10-03:00 (UTC-3) The registry distinguishes published external facts from your installation's routable aliases. [Model catalog](/docs/features/automatic-pricing/#discover-metadata-in-the-console) is privileged advisory discovery; **Configured routes** is the operator's actual routing inventory. The public Hub is a separate, explicit publication boundary. A catalog entry or a public card never grants access to perform inference. ## Delivered research workflows The public external-model research portal at `/registry` has its own safe source projection, model detail pages, original provider offers, typed published facts/rates and source licensing/freshness. Enable it separately from the explicitly published local-alias Hub at `/hub`; neither grants inference. See [public research configuration and contracts](/docs/features/public-model-research/). The protected console also provides private discovery, an exact single-target estimator and a general ECI snapshot. Independent [public general quality](/docs/features/general-quality/) exposes the complete original point-scale snapshot without administrative login. Advanced same-offer research filters and exact sortable columns have a separate default-off switch. [Provider research](/docs/features/provider-research/) adds its own source-backed index/detail and explicit price-coverage methodology. [Selected-model comparison](/docs/features/model-comparison/) adds ordered source columns and optional exact general ECI. [Same-workload comparison](/docs/features/workload-comparison/) adds exact per-offer base planning and explicit coverage/bounds. [Coding and source-reported value](/docs/features/coding-value-benchmarks/) publish original model-agent runs under independent flags; [Lifecycle and source history](/docs/features/model-history/) add declared deprecations/replacements, exact original listing revision changes and RSS under separate controls. The registered T028 research workflows passed integrated source/API/browser and independent acceptance. This verifies the documented source profiles and boundaries, not provider equivalence or complete product/release qualification. The roadmap and acceptance matrix retain broader work. ## Research surfaces and controls | Function | Public surface | Independent publication control | | --- | --- | --- | | Original catalog/details | `/registry` | `model_registry` | | Advanced same-offer filters/sorts | Catalog controls | `model_registry_filters` | | Provider research | `/registry/providers` | `model_registry_providers` | | Selected source comparison | `/registry/compare` | `model_registry_compare` | | Exact same-workload base planning | `/registry/calculator` | `model_registry_cost_comparison` | | Full original general capability | `/registry/quality` | `model_registry_general_benchmarks` | | Coding/source-reported value | `/registry/benchmarks` | Independent coding/value flags | | Original history/new listings | `/registry/updates` | `model_registry_history` | | Declared deprecations/replacements | Updates lifecycle tabs | `model_registry_lifecycle` | | Filtered RSS | `/v1/registry/history.rss` | `model_registry_rss`, requiring history | | Explicit local alias cards | `/hub` | `public_model_hub` | | Published MCP servers, agents and skills | `/hub` tabs | `public_hub_mcp_servers`, `public_hub_agents`, `public_hub_skills` ([public hub](/docs/features/public-hub/)) | Research controls default off and remain separate from the protected console and inference credentials. The registry modules require its base flag/UI; the safe local Hub is independent. Safe availability fields control navigation, including product documentation. Original source/license/hash/time and coverage remain visible; some source facts can be missing or stale without becoming zero or unsupported. ## Publish a safe alias card The runtime flag `public_model_hub` defaults to false and requires `ui`. It is an operator control, not a tenant plan right: enabling it makes expressly published metadata readable by any visitor. Model calls still require their credentials, scopes, model allowlist, plan ceilings and all safety/budget policies. No commercial classification is selected by this feature. ```yaml features: ui: true public_model_hub: true models: - id: chat-default capabilities: [chat] targets: - {provider: openai, model: gpt-4o-mini} hub: published: true title: General assistant description: Approved chat endpoint for application developers. tags: [chat, general] ``` This is a fragment; supply the provider connection and all ordinary gateway configuration separately. Open `/hub` for the public page or read its versioned JSON: ```sh BASE_URL='http://localhost:8080' curl --fail-with-body -sS "$BASE_URL/v1/hub/models" ``` | Key | Default | What it does | | --- | --- | --- | | `models[].hub.published` | `false` | Lists the alias on `/hub` | | `models[].hub.title` | the alias ID | Card title, up to 128 Unicode code points | | `models[].hub.description` | empty | Card text, up to 1024 code points; line feed and tab allowed | | `models[].hub.tags` | `[]` | Up to 16 unique nonempty tags of 64 code points each | Only ID, title, description, tags and currently enabled declared capabilities are public. Provider IDs/URLs, upstream model names, credentials, private models and prices stay out of this projection. Cards are plain text, not executable HTML or a provider health report. Wildcard aliases cannot be published. Disabled/unpublished aliases and aliases without an active capability are omitted. Both flagoff and UI-off return404; public responses are no-store. ## Manage publication In Model catalog, an administrator with `models:manage` and `admin_model_editor` edits the existing alias and reviews its public fields. Title is limited to128 Unicode code points, description1024, and up to16 unique nonempty tags of64 code points. Unsafe control characters are rejected; description alone permits line feed and tab. Published IDs with more than128 code points need an explicit bounded title. Omitted YAML `hub` retains the older model shape; `published:false` unpublishes. Model API updates replace the full model: omission or `hub:null` clears its publication metadata, so clients must preserve unrelated saved fields when editing. The existing PUT `/api/v1/admin/models/{id}` accepts `model.hub` with the current control version. The complete candidate is validated; successful changes persist and audit with the request ID, while stale versions are409. Readers and team roles cannot publish. Unrelated model edits preserve dormant publication metadata even when the feature is off. Deleting an override restores its YAML definition, including publication. Review the warning before reverting a public alias. To revoke YAML publication, change the declaration or save an explicit unpublished override. Publication/revocation changes metadata visibility; it never rotates a key, migrates usage, retargets a provider or authorizes a request. **Unpublish** uses POST `/api/v1/admin/models/{id}/unpublish` with only the current `{version}`. This narrow, audited operation flips publication off without accepting a model patch, and remains available after a classified enterprise license expires. Ordinary model edits remain protected. Live model permission, CSRF, feature/editor flags and CAS still apply; extra mutation fields are refused. Disabling the public flag also hides the entire Hub. Revocation stops newly served publication; it cannot recall copies visitors already made. ## Registry capabilities - External discovery keeps source origin, successful timestamp, freshness, partial-source failures, published parameters, modalities and lifecycle; source facts never silently change routing or billing. - Local route publication uses only reviewed safe alias fields, independent of the private external catalog. - [Advisory cost calculation](/docs/features/cost-calculator/) has its own default-off flag, exact source/target quotes and per-request/day/30-day coverage; it does not publish private pricing on the anonymous Hub. - [Attributed rankings](/docs/features/model-rankings/) expose the licensed external Epoch general ECI profile with exact scores, source intervals, snapshot provenance and explicit coverage. They are separate from private gateway analytics, coding/value cohorts and actual inference access. See [automatic pricing](/docs/features/automatic-pricing/), [access control](/docs/features/access-control/), [feature plans](/docs/features/entitlements/), [console](/docs/features/console/) and [operations](/docs/operate/operations/). # Public hub: MCP servers, agents and skills **Last updated:** 2026-11-21T10:44:38-03:00 (UTC-3) The public hub at `/hub` lists what the operator explicitly shares: model aliases (see [publish a safe alias card](/docs/features/model-registry/#publish-a-safe-alias-card)) and, with this feature, MCP servers, A2A agents and skills. Each kind has its own tab on the page and its own JSON endpoint. A listing is discovery only: it never changes access. Tool calls, agent messages and skill bundles still need an authorized key or console session, scope, team grant and plan rights. ## Enable Every kind has its own operator flag, default `false`. Each needs `public_model_hub` (which needs `ui`) and the registry it lists from: | Flag | Lists | Also requires | | --- | --- | --- | | `public_hub_mcp_servers` | MCP registry servers (`mcp_servers`) | `public_model_hub`, `mcp_registry` | | `public_hub_agents` | A2A agents (`agents`) | `public_model_hub`, `a2a_agents` | | `public_hub_skills` | Skill registry entries | `public_model_hub`, `skill_registry` | With a flag off its endpoint answers `404 feature_disabled` and its tab is hidden. Flags are operator controls, not tenant plan rights. ## Publish in YAML Nothing is listed until it is named and published under `public_hub`. Every field other than `id` is optional: ```yaml features: ui: true public_model_hub: true mcp_registry: true a2a_agents: true skill_registry: true public_hub_mcp_servers: true public_hub_agents: true public_hub_skills: true public_hub: cache: # optional; existing defaults below ttl: 30s error_ttl: 5s read_timeout: 5s mcp_servers: - id: docs published: true title: Documentation search description: Search the product documentation. tags: [search, docs] agents: - id: helper published: true skills: - id: release-notes published: true tags: [writing] ``` | Field | Default | Bounds | | --- | --- | --- | | `id` | required | 1–128 characters `A-Za-z0-9._-`, starting with a letter or digit; unique per kind | | `published` | `false` | `true` lists the item; `false` keeps the text without listing it | | `title` | the registry name | 128 Unicode code points, no control characters | | `description` | the registry description (agents and skills) or empty | 1024 code points; line feed and tab allowed | | `tags` | none | up to 16 unique non-empty tags of 64 code points | Each kind holds at most 200 listings. Keys must be spelled exactly (no case variants or nulls); an unknown key fails startup. A listing may name an item that does not exist yet: it is kept but not listed. ## What is listed An item appears only while all of these hold: - its kind flag, `public_model_hub` and `ui` are on, and its registry flag is on; - its listing is `published: true`; - **MCP server:** the registry entry exists, is not disabled, `mcp_execution` is on and `mcp_execution.servers` has an entry with the same `id` (otherwise its tool paths would lead nowhere); - **Agent:** the agent exists, is not disabled and at least one team may invoke it; - **Skill:** the registry entry is enabled and not deleted, has a published revision, its owner team is active, the revision is granted to at least one active team and none to a deleted team and its YAML base has not changed since the revision was saved. A YAML-only skill must be declared `published: true` and enabled, with at least one allowed team and every referenced team active. Plan entitlements are not applied to the listing, exactly as for `/v1/hub/models`: an anonymous visitor has no team whose plan could be checked. They still apply to every authenticated read, call and bundle download. Title, description and file list come from the **published revision**, never from a later draft. A skill mutation handled by this replica invalidates its cache immediately, including a mutation that finishes while a read is in flight. Other replicas, direct database changes and team lifecycle changes become visible within the configured cache TTL. Model/MCP/agent configuration uses the existing control-snapshot refresh. None of these discovery caches can authorize a call or bundle download: live permissions still apply there. ## Public endpoints No credential is needed; responses are `Cache-Control: no-store` and `{"data":[...]}` sorted by `id`, like `/v1/hub/models`. ```sh BASE_URL='http://localhost:8080' curl --fail-with-body -sS "$BASE_URL/v1/hub/mcp-servers" curl --fail-with-body -sS "$BASE_URL/v1/hub/agents" curl --fail-with-body -sS "$BASE_URL/v1/hub/skills" ``` ```json {"data":[{"id":"docs","title":"Documentation search","description":"Search the product documentation.","tags":["search","docs"],"transport":"streamable_http","tools_path":"/v1/mcp/servers/docs/tools","call_path":"/v1/mcp/servers/docs/tools/call"}]} ``` | Kind | Fields | | --- | --- | | MCP server | `id`, `title`, `description`, `tags`, `transport`, `tools_path`, `call_path`; tool names are not listed, since each is visible only to callers granted it | | Agent | `id`, `title`, `description`, `tags`, `endpoint` (`/a2a/{id}`), `card_path` (`/a2a/{id}/.well-known/agent-card.json`) | | Skill | `id`, `title`, `description`, `tags`, `revision` (0 for a YAML skill), `files_sha256`, `files` (paths only), `bundle_path` (console path; needs a session with a grant) | Never listed: server, agent or card URLs, credentials and their environment variable names, headers, key scopes, team or key grants, tool approvals, owner teams, file contents, authors and timestamps. Paths are gateway-relative. The skill endpoint reads PostgreSQL when a skill is listed and answers `503 hub_unavailable` if storage is unavailable. Its answer is kept in memory for up to `cache.ttl` (default 30s); a completed service error (excluding request cancellation and an exhausted lookup deadline) can be reused for `cache.error_ttl` (default 5s). Replaying a cached failure logs the current request with `cache_replayed: true`; it does not repeat the database query. At most one skill fill runs per replica; concurrent callers wait with their own deadline and can cancel independently. A canceled caller's failure is never cached for another request. Equivalent control snapshots do not invalidate the cache merely because their memory addresses change. Local skill mutations fence old in-flight fills; other replicas and direct database/team changes retain the bounded TTL visibility described above. MCP and agent endpoints read the in-memory configuration. ### Cache policy The optional `public_hub.cache` block is part of the same complete versioned publication configuration. It can be set in YAML, **AI hub → Public skill cache**, or `PUT /api/v1/admin/hub/listings` under `listings.cache`; the existing global writer permission, CSRF, version conflict, audit and revert-to-YAML rules apply. An old body containing only the three listing arrays remains valid and uses defaults. Cache settings do not enable a disclosure flag or grant access. | Field | Default | Bounds | Behavior | | --- | --- | --- | --- | | `public_hub.cache.ttl` | `30s` | 1s–5m | Maximum lifetime of a successful skill projection | | `public_hub.cache.error_ttl` | `5s` | 0s–30s | Failure reuse; `0s` disables reuse of failures | | `public_hub.cache.read_timeout` | `5s` | 100ms–30s | Per-request budget covering cache waiting and database read | All values are Go duration strings. Omitted fields use the defaults; null, unknown fields, duplicate members and invalid values are rejected. `GET /api/v1/admin/hub/listings` includes `cache_defaults` and the existing effective `listings`/`source`. Changing policy through the writer applies to new requests; an admitted request retains its captured policy. The candidate limit 100 is the existing skill-inventory page maximum; a truncated candidate list is explicitly marked instead of silently advertised as complete. This internal cache is not a public per-IP rate limiter. The endpoints take no query parameters: any query string or header is ignored and cannot change the answer. Every response is `Content-Type: application/json`, `X-Content-Type-Options: nosniff` and `Cache-Control: no-store`; the `/hub` page is the embedded console bundle with the console's Content-Security-Policy. Titles, descriptions, tags and file names are bounded (title 128, description 1024 for listings and up to 2048 from the registry, 16 tags of 64, file paths 128) and the page renders them as plain text: no HTML or Markdown is interpreted and no listing value becomes a link. ## Trust Hub listings and skill contents are operator-published, **untrusted content** for every client and agent that consumes them. A description, tag or skill file is data, never instructions: a client must not follow text found there, must not send credentials to anything it names and should treat the paths as gateway-relative routes only. ## Manage from the console **AI hub** (group Gateway, shown to global admin, viewer and operator roles while `public_model_hub` is on) has tabs Models, MCP servers, Agents and Skills, a **Copy URL** button and **Open public hub**: - Models: the published aliases exactly as `/v1/hub/models` returns them. Publish aliases from the Model catalog editor. - MCP servers, Agents, Skills: every registry item with its registry status, why it is or is not public, and a **Publish** toggle; below, the public preview, rendered with the same cards as `/hub`. The flag state is shown; choices made while a flag is off are kept. Toggling needs `models:manage`. A save replaces the complete listings as a console override (source **Console override**); **Revert to YAML** removes it. Both refresh replicas without a restart. ## Admin API `GET /api/v1/admin/hub/listings` (`config:read`, global admin, viewer or operator) returns `version`, `source` (`default`, `yaml` or `console`), `listings`, `declared` (YAML), `features` (per kind, whether it is publicly on), `candidates` (registry items with `active`, `disabled`, `not_executable` for an MCP server without execution trust, `published` or `unpublished`), `candidate_notes` (per kind: `reason`, `total`, `truncated`) and `preview` (the same public projection/cache for each enabled kind; disabled kinds have empty previews). Skill candidates are read under the caller's skill registry rights and capped at 100: a role the registry refuses (operator) gets `reason: "skills_unreadable_for_role"`, a storage failure `skills_unavailable`, and more than 100 skills `truncated: true` with the `total`; the console shows each of these. A PUT body that repeats a top-level member is refused with 400. `PUT` with `{"version":N,"listings":{"mcp_servers":[...],"agents":[...],"skills":[...]}}` replaces all three arrays; `DELETE` with `{"version":N}` reverts to YAML (404 `not_found` without an override). Both need `models:manage`, CSRF and the current version (409 on a stale one), and commit an audit event (`public_hub.set` or `public_hub.revert`, target `public_hub`) with the request ID. ```sh curl --fail-with-body -sS -X PUT -b "$COOKIE_FILE" -H "X-CSRF-Token: $CSRF_TOKEN" -H 'Content-Type: application/json' \ --data '{"version":42,"listings":{"mcp_servers":[{"id":"docs","published":true}],"agents":[],"skills":[]}}' \ "$BASE_URL/api/v1/admin/hub/listings" ``` ## Upgrade notes Migration 114 adds the override table. The optional cache policy uses that same JSONB override, so it needs no new migration. Existing three-array overrides remain valid. Before rolling back to a binary that predates the cache field, revert or remove its console override and remove `public_hub.cache` from YAML; that older strict decoder does not understand the new member. With no override and no `public_hub` in YAML nothing new is listed, and `/v1/hub/models` is unchanged byte for byte. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `DELETE /api/v1/admin/hub/listings` | Removes the console override and restores the YAML `public_hub` declaration | # Model aliases **Last updated:** 2026-11-21T10:44:38-03:00 (UTC-3) Clients keep the model names they were written with. When the operator renames a model, standardizes names (for example `anthropic-claude-sonnet-4-6`) or moves a team to a new deployment, the old names (`claude-sonnet-4-6`) must keep working. Without aliases, the operator declares a second model with a copy of the same targets and policies, and every key, team policy and organization must list both names. The copies drift apart: a retry, cache, guardrail or budget changed on one name silently does not apply to the other. A model alias is a `models[]` entry with `alias_of`: another client name for one canonical model. It owns nothing of its own, so the two names cannot drift. Flag: `model_aliases` (off by default, operator control). An [organization alias](#organization-aliases) is a client name owned by one [organization](/docs/features/organizations/) for one canonical model, resolved only for that organization's keys. Flag: `organization_model_aliases` (off by default, operator control, requires `organizations` and `model_aliases`). A [moving alias](#moving-aliases-follows) is the same kind of entry with `follows` instead of `alias_of`: a name such as `claude-sonnet-latest` that serves the newest version of a model family you declared, and moves when you declare or enable a newer one. Flag: `model_follows` (off by default, operator control, requires `model_aliases`). ## How to enable it ```yaml features: model_aliases: true models: - id: anthropic-claude-sonnet-4-6 # the canonical model capabilities: [messages] targets: - provider: anthropic model: claude-sonnet-4-6 - id: claude-sonnet-4-6 # what existing clients send alias_of: anthropic-claude-sonnet-4-6 keys: - id: checkout allowed_models: [anthropic-claude-sonnet-4-6] # may call both names - id: legacy-app allowed_models: [claude-sonnet-4-6] # may call only the alias ``` The same entry can be created in the console (**Models → Edit routing → Alias of**) or with the model API (`PUT /api/v1/admin/models/{id}` with `{"id": "claude-sonnet-4-6", "alias_of": "anthropic-claude-sonnet-4-6", "targets": []}`). Choosing **Alias of** hides the targets and policy fields, because an alias has none. The flag is a runtime flag (**Settings → Features**): turning it on or off applies to the next request. With the flag off, alias entries stay stored and validated, but they serve nothing: a request for the alias answers `404 model_not_found` (or `403 model_forbidden` for a key that names only the canonical model), and the alias is not listed in `/v1/models`. ## Fields An alias entry declares only these fields. Any other field (`targets`, `capabilities`, `retry`, `cache`, `semantic_cache`, `latency_routing`, `auto_route`, `routing_strategy`, fallbacks, `request_timeout`, `stream_timeouts`, `unsupported_parameters`, `stream_usage`, `hub`) is refused at load and on the model API, because the alias takes them from its canonical model. | Field | Default | Values | | --- | --- | --- | | `models[].id` | required | The client name. Unique across all models and aliases; not a wildcard (`prefix/*`), not `*`, not `group:…`. When the canonical model serves `generate_content`, letters, digits, dot, dash or underscore only (the name travels in the URL path). | | `models[].alias_of` | none | The canonical model's `id`. It must exist, must not be an alias itself and must not be a wildcard model. | | `models[].disabled` | `false` | Disables this name only. Disabling the canonical model disables its aliases too. | Validation, at load and on every model API write: - **No chains, no cycles.** `alias_of` must name a model with targets. An alias of an alias is refused with the name of the model to point to instead, so `a → b → a` cannot exist. - **No collisions.** An alias ID cannot repeat any other model or alias ID. - **The canonical model cannot disappear under its alias.** Deleting a model that an alias names is refused (`422 model_in_use`); delete or repoint the alias first. ## What the alias inherits A request for the alias is served exactly as a request for the canonical model. Once the key passes the access check with the name it sent, the gateway continues under the canonical name, so everything keyed by model name applies unchanged: - targets, weights and routing strategy, capabilities and protocol translation, retries, fallbacks (context window, content policy, target order), latency routing, request timeout and stream clocks, request parameter policy; - the exact and semantic cache policies (semantic cache entries are shared with the canonical model; exact cache entries are not, because the exact key covers the request body, which carries the model name the client sent); - guardrails and guardrail policies that name the canonical model; - budgets and TPM/TPD quota policies on the canonical model (`subject: model`), and prices for usage valuation; - evaluation capture and the analytics totals of the canonical model. Because of this, policies name canonical models. A guardrail, a guardrail policy or a model quota policy that names an alias is refused at load and on its API, with the canonical name to use: such a policy would never match, since no request is evaluated under the alias name. Configuration references that the gateway follows on the client's behalf (fallbacks, auto-routing defaults, routes, tiers and embeddings, semantic cache embeddings, vector store OCR and embedding models, moderation guardrail models, evaluation judges and evaluation experiment models) also name canonical models. ## Access: one direction Granting the canonical model grants its aliases; granting an alias grants only the alias. | Granted | May call the canonical model | May call the alias | | --- | --- | --- | | Canonical model | yes | yes | | Alias only | no (`403 model_forbidden`) | yes | | `*` | yes | yes | The rule holds at every layer, and the layers still intersect as ceilings: - **Keys.** `allowed_models: [anthropic-claude-sonnet-4-6]` covers `claude-sonnet-4-6`. A key whose list covers the canonical model through a wildcard entry (`prefix/*`) covers its aliases too. A `prefix/*` entry grants an alias by the alias's own ID too, whatever its canonical model: an alias `openai/legacy` of an Anthropic model is reachable through `openai/*`, exactly like a model declared with that ID. Choose alias IDs outside wildcard prefixes the ceiling should not cover; with `model_aliases` off, such an ID also stops resolving through the wildcard model (it answers 404). - **Team policies.** A team allowed the canonical model lets its keys call the alias. A team allowed only the alias removes the canonical model from every key of the team, even a key that lists it, and a new key under that team cannot ask for the canonical model (`403 outside_team_policy`). - **Organization ceilings.** The same: an organization allowed the canonical model covers the alias; one allowed only the alias keeps its teams on the alias. - **Access groups.** A group that lists the canonical model grants its aliases to every key that references the group. So a legacy application can be moved onto a key that names only the old client name, without that key ever reaching the canonical name, while every new key names the canonical model and reaches both. ## What clients see - `GET /v1/models` lists the alias as its own model (`{"id": "claude-sonnet-4-6", "object": "model", …}`) when the key may use that name, with the canonical model's capabilities deciding whether it appears. `GET /v1/models/{id}` answers the same way; a name the key cannot use is `404`, never `403`. - `GET /v1/model/info` (model information, `model_info`) shows the alias with the canonical model's mode, capabilities and prices. - Answers the provider writes itself (an OpenAI-protocol target answering Chat Completions or embeddings natively) carry the provider's own `model` field, as for any model. Answers the gateway builds (translated routes: Anthropic, Gemini, Bedrock, Cohere, OCI and SageMaker targets, the Responses API target, translated Messages, Responses and GenerateContent, Bedrock and Cohere embeddings, and semantic cache hits, whose stored entry the model and its aliases share) carry the name the client sent, so a key allowed only the alias never sees the canonical name. ## What is recorded Usage keeps both names: | Where | `model` | Name the client sent | | --- | --- | --- | | Usage events, request log API (`GET /api/v1/admin/logs`, `/requests/{id}`) | canonical model | `requested_model` (omitted when the client named the canonical model) | | Console request log | canonical model | shown as `… via ` in the Model column | | Request log CSV export (`/api/v1/admin/logs/export`) | canonical model | `requested_model` column, present while `model_aliases` is on | | Log destinations | canonical model | `requested_model` | | Stdout `request` line | canonical model | `requested_model` attribute, only on alias requests | | Analytics totals, budgets, valuation | canonical model | — | Analytics and budgets aggregate by the canonical model on purpose: the alias is the same model and the same spend. The request log filter by model uses the canonical name. ## Moving aliases (follows) Some clients want "the newest Sonnet" rather than a dated model ID. A moving alias gives them one stable name while the operator keeps control of what it reaches: it resolves **only among the models you declared**, never to a model the configuration does not contain, and every change of what it serves is logged and can be delivered as an alert. Nothing is rewritten silently. ```yaml features: model_aliases: true model_follows: true models: - id: sonnet-4-5 targets: - provider: anthropic model: claude-sonnet-4-5-20250929 - id: sonnet-5-5 # prepared, not yet serving disabled: true targets: - provider: anthropic model: claude-sonnet-5-5 - id: claude-sonnet-latest # what clients send follows: family: claude-sonnet provider: anthropic keys: - id: assistant allowed_models: [claude-sonnet-latest] ``` Here `claude-sonnet-latest` serves `sonnet-4-5`. Enabling `sonnet-5-5` (in YAML, in the console, or with the model API) moves it to `sonnet-5-5` on the next published configuration, and the gateway reports the change. The same entry can be created in the console (**Models → Edit routing → Moving alias**) or with the model API (`PUT /api/v1/admin/models/{id}` with `{"id": "claude-sonnet-latest", "follows": {"family": "claude-sonnet", "provider": "anthropic"}, "targets": []}`). The editor shows the current resolution and every candidate it considered. ### Fields A moving alias declares only `id`, `follows` and `disabled`; every other field is refused, as for `alias_of`. `follows` and `alias_of` cannot be combined. | Field | Default | Values | | --- | --- | --- | | `models[].id` | required | The client name: letters, digits, dot, dash or underscore, 1–128 characters. Unique across all models and aliases; not a wildcard. | | `models[].follows.family` | required | The upstream model ID pattern of the family, 1–200 characters. One `*` marks where the version goes (`gemini-*-flash`); it stands alone between separators (`-`, `.`, `_`, `@`, `:`), so `gpt-4*` is refused. Without it the version follows the family after a dash (`claude-sonnet` means `claude-sonnet-*`). The family is a stem, not a pinned version: `claude-sonnet-4` also covers `claude-sonnet-4-5`, as version `5`. | | `models[].follows.provider` | required | A `providers[]` ID. Every target of a candidate must use it. | | `models[].disabled` | `false` | Disables this name only. | ### How it resolves When a configuration is loaded or published (boot, a YAML reload, any console or API change), the gateway computes each moving alias once and serves that answer until the next publication; the request path never consults a remote catalog. A declared model is a **candidate** when one of its targets is on `follows.provider` with an upstream model of the family. It is **eligible** when, in addition: - every target is on `follows.provider` and names the same upstream model, so no fallback target or retry can leave the provider or the version; - it is enabled, is not an auto-routing model or a passthrough model, and declares no `context_window_fallback` or `content_policy_fallback` (a semantic fallback sends a refused request to another model, possibly on another provider); - it is an exact model (not a wildcard `prefix/*`, not another alias). The **version** is the part of the upstream model ID that the `*` covers. It must be up to six numbers of one to three digits, optionally followed by a date stamp (`20YYMMDD` or `20YY-MM-DD`, a real month and day) and a revision: `4-5`, `2.5`, `4-5-20250929`, `2024-07-18`, `4-5-20250929-v1:0`, `4-5@20250929`. Anything with words (`latest`, `preview`, `exp`, `mini`) is not a version, so a provider's own moving name and a preview never qualify. Among eligible models the newest wins, deterministically: 1. higher version numbers, compared number by number (`5` after `4-5`, `4-5` after `4`, `10` after `9`); 2. then the later date stamp (a dated snapshot after the undated name of the same version); 3. then the higher revision; 4. then, for identical versions, the lowest model `id`. When no model is eligible the alias serves nothing: a request answers `404 model_not_found`, and the resolution says `no_eligible_model`. A catalog update reaches a moving alias through your declared models, never directly. [Catalog onboarding](/docs/features/providers/) (`catalog_onboarding`) prepares new models disabled: enabling one, or declaring a model yourself, is what moves the alias. This keeps every model the alias can reach priced, policed and reviewed. ### Access and policies A moving alias is an alias: once the key passes the access check with the moving name, the request continues as the resolved canonical model, with its targets, guardrails, budgets, quotas, caches and prices (see [What the alias inherits](#what-the-alias-inherits)). Two differences from `alias_of`: - **Access is by name only.** Granting `claude-sonnet-latest` (or `*`, or a `prefix/*` entry covering its ID) grants it. Granting the model it currently resolves to does **not** grant the moving name, and granting the moving name does not grant the canonical model, so a change of resolution never changes who may call what. - **Policies cannot name it.** Guardrails, guardrail policies, model quota policies, rate policies and configuration references (fallbacks, auto-routing targets) name canonical models; naming a moving alias is refused at load and on the API, because what it reaches changes. ### What is recorded and reported | Where | What | | --- | --- | | Usage events, request log API, CSV export, log destinations, stdout `request` line | `model` is the resolved canonical model, `requested_model` the moving name, exactly as for `alias_of` (see [What is recorded](#what-is-recorded)) | | Console request log | ` via ` in the Model column | | `GET /api/v1/admin/config`, model entry | `follows` and the read-only `follow_resolution`: `model`, `upstream_model`, `version`, `reason` when unresolved, `enabled`, `serving` and the `candidates` with `skipped` reasons (`disabled`, `auto_route`, `passthrough`, `semantic_fallback`, `targets_outside_provider_or_version`) | | Console models page | `Follows on · serves ` on the card; the editor lists the candidates | | Logs, at boot and for a new alias | `model_follow_resolved` (info) or `model_follow_unresolved` (warning), once; with PostgreSQL, the first configuration read after boot logs the effective answer the same way when console changes make it differ from the YAML, without an alert | | Logs, on every change | `model_follow_resolution_changed` (warning) with `alias`, `previous_model`, `model`, both upstream models and `control_version`, on each replica | | Alert event `model_follow_changed` | On a change while the alias is enabled and both flags are on, for every [alert channel](/docs/features/alerting/) that subscribes to it; one event per change and control version across replicas | `GET /v1/models` and `/v1/model/info` list the moving alias by its own name with the shape of the model it resolves to, and gateway-built answers carry the moving name, as for `alias_of`. ### Turning it on and off `model_follows` is a runtime flag. Off, moving aliases stay stored, validated and resolved (the admin view still shows what they would serve) but serve nothing (`404`). A resolution change made while the flag is off is logged but not alerted. Turning `model_aliases` off while `model_follows` is on is refused. ## Organization aliases In a multi-tenant gateway each organization can give its own names to the gateway's models: `fast` for one organization, `cheap` for another, without a gateway-wide name that every organization sees. An organization alias is managed by that organization's [organization admin](/docs/features/organization-admins/) and by the global administrator, or declared in YAML. ```yaml features: organizations: true model_aliases: true organization_model_aliases: true # operator control, default false; requires PostgreSQL organizations: - id: acme name: Acme teams: [team-acme] model_aliases: # read-only in the console and the API - id: fast alias_of: anthropic-claude-sonnet-4-6 ``` The console has the same editor in **My organization → Model aliases** (organization admin) and **Organizations → Model aliases of** (global administrator). The API: ```http PUT /api/v1/admin/organizations/acme/model-aliases/fast Content-Type: application/json X-CSRF-Token: {"alias_of": "anthropic-claude-sonnet-4-6"} ``` Without `version` it creates the alias (`201`); with the current `version` it replaces it (`200`). `DELETE` takes `{"version": N}`, and `GET /api/v1/admin/organizations/{id}/model-aliases` lists them. An organization admin reaches only its own organization's (another answers `404`). Every write is audited with the organization, so it appears in that organization admin's audit view. | Field | Default | Values | | --- | --- | --- | | `id` | required | 1–128 letters, digits, dot, dash, underscore, colon or `@`; no `/` or `*`, so no `prefix/*` entry of a key or a ceiling ever grants it by name. Not the ID of a gateway model. Unique in its organization; at most 200 per organization. | | `alias_of` | required | An exact, enabled canonical gateway model: not an alias, a moving alias, a wildcard or an auto-routing model. When the organization has a [model ceiling](/docs/features/organizations/#model-ceiling), the ceiling must allow it. | | `disabled` | `false` | Disables this name only. | **Resolution.** For a key whose team belongs to organization O, a model name resolves to O's alias first, then to the gateway-wide alias or model of that name; a gateway model with targets always keeps its own name. An organization alias with the name of a gateway-wide alias **shadows** that alias for O's keys only: the editor and the API show `shadows` with the canonical model the gateway-wide alias served. Keys of other organizations, and keys with no team, never resolve O's aliases, on any route (chat completions, Messages, Responses, model listing and the rest). **Access.** An organization alias grants nothing. A key may call it only when it may call `alias_of` (through its own list, its team policy and the organization ceiling, as for any alias); a key that names the shadowed gateway-wide alias literally, without being allowed the organization alias's target, loses that name. It introduces no target, credential or provider: once resolved, the request is the canonical model's, with everything listed in [What the alias inherits](#what-the-alias-inherits), and usage records `requested_model` as for any alias. **Freshness.** The aliases are read with the organization ceiling on every request, in the same query, so a change on any replica applies to the next request on every replica, with no cache to invalidate. An alias whose target was later removed, disabled or made an alias serves nothing (`404`); the list shows `serving: false` and the reason. **Turning it off.** `organization_model_aliases` is a runtime flag. Off, organization aliases stay stored but are ignored on the request path (the gateway-wide names apply again) and the API answers `404 feature_disabled`. **Limits.** A batch runs later, outside the key's request, where only gateway-wide names resolve: a batch line that names an organization alias is refused when the batch is created; name the model it points to. Policies (guardrails, budgets, rate policies) name canonical models, never an organization alias. ## Upgrade notes - Migration 178 adds the organization model aliases table; it is additive. Before rolling back to a binary without organization aliases, remove `organizations[].model_aliases` from YAML: older binaries refuse the unknown field. - Moving aliases (`follows`, flag `model_follows`) need no migration: usage already stores `requested_model`. Before rolling back to a binary without them, remove `follows` entries: older binaries refuse the unknown field. - Migration 109 adds the nullable `requested_model` column to `gateway_usage_events`. It is additive; existing rows stay `NULL` and their fingerprints do not change. Older binaries refuse a schema at 109, as with every migration; roll out compatible binaries before enabling the flag. - Before rolling back to a binary without model aliases, remove `alias_of` entries from the YAML and the console: older binaries refuse the unknown field. # Public model research catalog **Last updated:** 2026-11-21T08:59:43-03:00 (UTC-3) Open `/registry` to research original public model listings and their provider offers. It is part of the same gateway binary. It is separate from `/hub`, which publishes approved local aliases, and `/ui`, which manages private configuration. A public listing is neither a routable gateway alias nor evidence of adapter support, availability or permission to make a paid request. ## Enable and configure Both operator flags default to false. `model_registry` requires `ui`; it is independent of the protected `external_model_catalog`. `model_registry_management` additionally requires the registry and PostgreSQL for versioned policy changes. Anonymous disclosure is an instance decision, not a tenant plan entitlement. Flags never grant administrative permissions. ```yaml features: ui: true model_registry: true model_registry_management: true model_registry: fetch_timeout: 30s cache_ttl: 15m sources: cost_map: true modelsdev: false ``` | Key | Default | What it does | | --- | --- | --- | | `model_registry.fetch_timeout` | `30s` | Deadline of one fetch of a public source, 1s–2m | | `model_registry.cache_ttl` | `15m` | How long a fetched snapshot is reused, 1m–24h | | `model_registry.sources.cost_map` | `true` | The public cost map, the registry's required base source; it must stay `true` | | `model_registry.sources.modelsdev` | `false` | Adds the optional models.dev metadata, matched exactly, to the catalog | This fragment supplements ordinary installation configuration; it does not provision infrastructure or configure a provider. Fetch timeout defaults to 30s (inclusive 1s–2m); cache TTL defaults to 15m (1m–24h). The original public cost map is required. Optional exact metadata enrichment defaults off. Source URLs are fixed protocol boundaries; the settings do not accept arbitrary URLs, credentials, scripts or account catalogs. In Model catalog, the dedicated public research policy editor shows effective values, default/YAML/console provenance, version and the optional override. Global administrators/operators with `models:manage` may save or revert; global readers with `config:read` may inspect. Team-scoped roles cannot read this instance policy. Writes require CSRF, the management flag, current control version, full typed policy and atomic audit. A stale version is 409. Saving affects new fetches and cache lookups after replica refresh; it does not cancel an in-flight operation. YAML changes require a restart. Deleting the override restores YAML/defaults. Feature-off leaves stored policy dormant; re-enable restores it. The versioned settings API is GET/PUT/DELETE `/api/v1/admin/model-registry/settings`. GET returns `version`, nullable `override`, `effective`, per-field `sources`, `restart_required:false` and `applies_to:new_fetches_and_cache_lookups`. PUT accepts `{version,model_registry:{fetch_timeout,cache_ttl,sources:{cost_map:true,modelsdev:false}}}`. DELETE accepts `{version}` only. Unknown, duplicate, null or incomplete fields are refused. See [OpenAPI](/docs/api/) for the contract and [access control](/docs/features/access-control/) for session permissions. ## Public read API ```sh BASE_URL='http://localhost:8080' curl --fail-with-body -sS --get "$BASE_URL/v1/registry/models" --data-urlencode 'q=assistant' --data-urlencode 'limit=50' --data-urlencode 'offset=0' ``` The list returns source provenance, method, warnings, total, limit, offset and models. Search is bounded to 256 UTF-8 bytes with no control characters. Limit defaults to 50 and accepts 1–200; offset accepts 0–10000. Integers must use canonical decimal syntax. Unknown or repeated query parameters are 400. Follow a returned `id` with GET `/v1/registry/models/{id}` for one model's offers; that route accepts no query fields. Flag-off, UI-off and unknown IDs return 404. All responses are no-store. Request and trace IDs are returned and source fetches propagate them into linked client spans. Anonymous pages fetch only the safe public API, with no session, administrative or inference request. Public source DTOs never include configured aliases, provider connections, account inventories, manual prices, teams, keys or credentials. Source strings are rendered as text; source URLs are validated HTTPS links. The portal preserves loading, unavailable, stale, empty and unknown states instead of turning a source failure into zero results. ## Model identity and offers A group is an exact `(mode, source model label)` pair after removing at most one exact declared provider prefix. Its stable opaque `m_` ID is the SHA256 of those components. Dates, versions, region, quantization and remaining namespaces are preserved. Grouping is a label convenience, **not proof of equivalent weights, deployments or behavior**. Each offer retains its exact original source key, provider, model label, features, limits, modalities and rates. Conflicting offers stay visible individually; a missing fact is unknown, and a published false feature is explicitly false. The required feed is the [original community cost map](https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json). Optional [models.dev](https://models.dev/api.json) enrichment fills only missing display names/release dates on exact provider/model matches. It never replaces rates, features or limits. Enrichment is separately attributed, including its own successful timestamp/hash/freshness. Disabling enrichment removes enriched facts instead of retaining a previous policy's view. Source specification/fallback control rows and unusable identities are excluded with coverage warnings. Safely identified model/service records retain their declared modes, including decision/evaluation and other service listings; discovery does not infer an inference capability. Named integer limits remain distinct: `max_input_tokens`, `max_output_tokens` and `max_tokens` are not interchangeable. Published input/output modalities are kept separately; no modality or capability is inferred from a model name. The allowlisted `supports_*` booleans are facts about a source listing, not a promise about your configured route. ## Rates and source coverage Rates are exact decimal strings with the original parameter, currency, unit and optional published condition. USD and DBU are distinct. Token, audio/image/video token, second, image, character, pixel, query, request, page, credit, session and other published units are never mixed. Cache, context, batch and service variants retain their parameter names. A zero published rate is distinct from a missing rate; neither certifies a free successful call. No floating-point amount, billing adjustment, ledger reservation or invoice is generated by browsing. Every source preserves its original URL, SHA256, successful capture time, explicit stale status and license/attribution/full notice. Capture time is not model release or price-effective time. Bounded fetches reject redirects, credentials, oversized/ambiguous JSON and unsafe fields. The source budget includes admission waiting. If refresh fails, a previously successful snapshot may be served explicitly stale with its original timestamp/hash; without a valid required cost-map snapshot, the API is 503. If optional enrichment has no valid snapshot, the primary catalog remains available with `modelsdev_unavailable` and no enriched facts or claimed successful optional-source capture. Caller cancellation is never converted into stale success. A failed optional source does not silently inherit the primary source's success. See [third-party notices](/docs/security/third-party/). ## Filter and sort research offers Enable the default-off operator flag `model_registry_filters` together with `model_registry`. It adds the filter form and sortable research table to the same public portal. The ordinary catalog remains available when the advanced flag is off; advanced query fields then return 400. The list includes safe `filters_enabled` and full-snapshot `facets` metadata, so the anonymous browser never queries administration to discover these controls. Facets are sorted unique source values before filtering; their arrays are empty when advanced controls are disabled. All filters, including provider/source-ID search, must match **the same original offer**. A provider advertising image input and a different provider advertising tool support do not jointly satisfy both constraints. The group retains all its original offers, with `matching_offer_ids` identifying the eligible subset. Missing modality, named limit or feature never becomes unsupported, false or zero. | Query | Meaning | | --- | --- | | `provider`, `mode` | Exact published offer label, at most 4096 UTF-8 bytes | | `input_modalities` | Comma-separated 1–8 distinct nonempty labels, each at most 64 UTF-8 bytes; all must be explicitly published | | `output_modality` | One exact published output label, at most 64 UTF-8 bytes | | `min_input_tokens`, `min_output_tokens` | Canonical nonnegative decimal, at most 9007199254740991, compared only with the corresponding named source limit | | `tools`, `json`, `reasoning`, `cache` | Exact lowercase `true` or `false` for `supports_function_calling`, `supports_response_schema`, `supports_reasoning`, `supports_prompt_caching`, respectively; unknown matches neither | | `zero_listed_price` | `true`: some published USD rate is explicitly zero; `false`: at least one USD rate is known and none is zero. Missing/DBU-only rates match neither | | `deprecation` | `published` or `unknown`: presence of an explicit deprecation date, not a claim that it has taken effect | | `sort` | `model` (default), `release`, `input_limit`, `output_limit`, `input_price`, `output_price`, `cache_read_price`, `cache_write_price` | | `direction` | `asc` (default) or `desc`; unknown values stay last in either direction | Whitespace is not silently trimmed from published labels. Unknown query fields/enums, repeated fields, empty advanced selectors and malformed/noncanonical values are refused. A syntactically valid provider/mode/modality label absent from the snapshot returns an empty matching result, not a validation error. The existing search/pagination bounds still apply; filtering and sorting cover the full snapshot **before** pagination. Apply/reset and page navigation preserve a validated shareable URL; changing a filter starts at the first page. ```sh BASE_URL='http://localhost:8080' curl --fail-with-body -sS --get "$BASE_URL/v1/registry/models" --data-urlencode 'input_modalities=text,image' --data-urlencode 'tools=true' --data-urlencode 'min_input_tokens=32000' --data-urlencode 'sort=input_price' --data-urlencode 'direction=asc' ``` Each returned research `columns` metric has an exact string `value`, original `offer_id`, `provider`, `parameter`, `unit` and `source`; price columns also carry `currency:USD`. A missing column is unknown. Named input/output columns select the largest published corresponding limit among matching offers; release selects the latest exact published enrichment date. Neither a dated model name nor `max_tokens` substitutes for those fields. Price columns select the lowest exact **base USD per text token** among matching offers: `input_cost_per_token`, `output_cost_per_token`, `cache_read_input_token_cost`, `cache_creation_input_token_cost`. DBU, audio/image/video token rates, batch/context/service tiers and conditional prices remain visible in offer details but do not enter these incomparable columns. Comparisons use exact server arithmetic; zero is ordered numerically and unknown remains last. Original source identity breaks ties deterministically. The UI keeps unit and provider attribution visible rather than rounding a value into a different order. Columns may select **different offers**. A row with the largest input limit and cheapest output rate does not promise one provider supplies both. A zero cache or other USD rate does not mean the complete request is free. These columns are list-price research, not a workload estimate, invoice, inference guarantee or private routing recommendation. ## Research providers The independently flagged [provider directory](/docs/features/provider-research/) adds exact provider pages, published model endpoint filtering, original native rate disclosures and per-column comparable-listing coverage. It uses the same safe captured public sources; private provider settings remain separate. ## Compare selected models The independently flagged [side-by-side comparison](/docs/features/model-comparison/) preserves selected source order, original provider facts, mixed/unknown features and optional attributed general ECI with exact source identity. It never combines different column extrema into one real provider offer or invokes a model. ## Plan one workload across offers The independently flagged [workload calculator](/docs/features/workload-comparison/) compares exact public base-unit costs across the admitted source catalog or chosen models, with source/rate basis, request/day/30day projections and explicit unranked/partial/unknown states. It does not expose private manual prices or authorize a paid call. ## Connect a researched model First configure a compatible provider and an explicit alias in the protected console/YAML/API, with capabilities, authentication and model access. Then use **your alias**, not a registry source ID, in the applicable [inference endpoint](/docs/features/capabilities/). The detail page offers Chat curl/SDK examples and an operator YAML setup template. Executable examples require `GATEWAY_MODEL_ALIAS` and a locally supplied gateway API key; setup placeholders must be replaced with verified provider/model configuration. They never embed a provider credential or invoke a provider on page load. A listing without a matching gateway protocol has setup guidance rather than a fabricated executable request. ## Upgrade and recovery Back up PostgreSQL before migration 106 and roll out compatible replicas before activating management. New flags and the typed YAML root require supporting binaries; older binaries reject newer schema history. Override revert is a policy operation, not schema downgrade or cross-engine migration. To hide anonymous research, first disable its enabled dependent research switches, then disable `model_registry`; retained visitor copies cannot be recalled. This does not unpublish `/hub`, alter routing or stop inference. Source outage affects research only; it does not replace the operator's approved configuration or prices. Separate coding/value benchmarks and historical change feeds are delivered under their own roadmap tasks. This base catalog alone does not certify whole registry parity. ## Coding and reported value [Original coding/value research](/docs/features/coding-value-benchmarks/) has independent default-off public controls, exact source model identifiers, preserved agent/settings, same-run cost ratios and explicit unknown measurement coverage. It never substitutes token list prices or private usage. ## Lifecycle and original changes [Lifecycle/history and RSS](/docs/features/model-history/) separate current source-declared dates/replacements from immutable revision edits. Bounded older source pages, exact original listing before/after facts and independent publication flags preserve provenance without inventing launch dates or provider shutdowns. ## Public general capability and navigation [General quality](/docs/features/general-quality/) has its own default-off operator flag and original full-source point ranks/intervals/facets, separate from coding/value and private administration. Public availability fields expose only safe publication state. Hub, general and documentation navigation is hidden when disabled or unknown; flags grant neither inference nor private data access. # Public provider research **Last updated:** 2026-11-06T13:33:57-03:00 (UTC-3) Use `/registry/providers` to browse original public providers, published model endpoints and their model/service rate listings. Open a provider for its original offers, limits, features and native cache/batch/context/service-rate parameters. This is source-backed research, separate from [configuring provider connections](/docs/features/providers/). A listing, endpoint or documentation link is not proof of adapter support, credentials, account availability, health or permission to run inference. ## Enable and navigate ```yaml features: ui: true model_registry: true model_registry_providers: true ``` `model_registry_providers` is a default-off operator disclosure control, requiring `model_registry`; advanced research filters are independent. Normal YAML/API/console feature management applies. No new persistence migration or parameter root is introduced. Public model list/detail metadata exposes only `providers_enabled`, allowing navigation without administration/session requests. Flag-off returns404 for provider pages/APIs; ordinary model research and the private provider editor retain their own flags/contracts. The directory supports public text search, an exact published-endpoint selector, sortable provider/model/offer/price-coverage counts and bounded pagination. Provider detail supports offer search and endpoint filtering, paging, links to original model details, published documentation/API metadata and expandable native rate details. Apply/reset and back/forward preserve shareable validated URLs. Endpoint metadata is displayed literally; there is no network probe or provider call. ## Read the versioned API ```sh BASE_URL='http://localhost:8080' curl --fail-with-body -sS --get "$BASE_URL/v1/registry/providers" --data-urlencode 'endpoint=/v1/chat/completions' --data-urlencode 'sort=input_lowest' --data-urlencode 'direction=desc' --data-urlencode 'limit=50' --data-urlencode 'offset=0' ``` A provider has a stable opaque `p_` plus64-hex identifier derived from its exact source provider ID. Case, region and protocol variants remain separate; names are not normalized into one presumed account. GET `/v1/registry/providers/{id}` returns the selected provider and its flat original offer rows, each with `model_group_id`, source `model_id`, optional published `mode` and the complete safe `offer`. | Query | Directory | Provider detail | | --- | --- | --- | | `q` | Case-insensitive provider ID/name search, at most256 UTF-8 bytes | Source offer/model search with the same bound | | `endpoint` | Exact published path; matches providers with an original listing for that path | Same-offer path match | | `limit`, `offset` | Canonical integers:1–200 (default50),0–10000 (default0) | Same bounds | | `sort` | `provider` (default), `models`, `offers`, `input_lowest`, `output_lowest`, `cache_read_lowest`, `cache_write_lowest` | Not accepted | | `direction` | `asc` (default), `desc` | Not accepted | Endpoint selectors are at most2048 ASCII bytes, start with `/`, use the published path character profile and reject double slashes, dot segments, query strings and fragments. They are endpoint identifiers, not arbitrary URLs. Valid absent labels/paths return an empty result; unknown query fields, duplicates, malformed or noncanonical selectors are400. Invalid or unknown provider IDs are404. See [OpenAPI](/docs/api/) for exact schemas. Both responses preserve original `sources`, `method`, `warnings`, `providers_enabled:true` and filtered/page `total`, `limit`, `offset`. Directory `facets.supported_endpoints` is the full-source set before filtering. Provider counts/coverage always describe its full captured source inventory, not only the search page. Search/pagination never silently changes a comparison denominator. Public requests carry request/trace IDs and no-store responses; they do not authenticate a gateway model call. ## Published facts and unknowns The primary original cost map supplies exact provider IDs, model/service offers, declared modes, `supported_endpoints` and allowlisted native rate parameters. Empty endpoint arrays mean not published, not unsupported. Paths are publisher model metadata, not our adapter coverage or a protocol translation promise. Safely identified decision/evaluation, search, guardrail and vector-store listings retain their published mode; only specification/fallback control records or invalid identities are excluded. The catalog does not classify an unfamiliar mode as a non-model and silently discard it. Unknown limits, features and rates remain unknown. Each native rate keeps its original amount, currency, unit, parameter and condition, including the explicitly published guardrail per-unit condition profile; cache/batch/context/service variants are not silently converted into standard rates or totals. If exact public metadata enrichment is enabled in [source policy](/docs/features/public-model-research/#enable-and-configure), an exact models.dev provider match may supply a display name, documentation URL and published API base URL. Each is captured with the same immutable source snapshot/hash/freshness as the response. No cross-provider alias mapping, configured account URL, environment variable list, SDK execution, secret or credential is projected. URLs require the safe HTTPS profile; unsafe or absent facts stay unknown. URLs with template placeholders are omitted as unknown. A published ordinary API base URL still needs operator configuration and compatible protocol/capabilities before use. The optional source failure/disable policy remains the [catalog contract](/docs/features/public-model-research/#rates-and-source-coverage): a valid previous optional snapshot remains available only with its original hash/time and explicit stale status after refresh failure. With no valid optional snapshot or enrichment disabled, no enriched fields or successful optional-source claim is retained; a valid primary catalog can remain available with an explicit warning. Sources retain full original licensing notices. No new external source or arbitrary egress selection is added. ## Understand lowest-listed-price coverage Each of the four price columns is independent: base input, output, cache read and cache creation. Comparisons use only the exact corresponding **USD per-token base parameter**, with no condition. DBU, media-token, batch, long-context, service-tier and other native dimensions are retained in details but excluded from these incomparable summaries. For each exact nonempty published mode and source model-label group, take each provider's minimum eligible original offer rate once. A group is comparable only if at least two distinct providers have that column's known rate. Duplicate offers from one provider do not create competitors. Label grouping is not proof of equivalent weights/deployments. | Coverage field | Meaning | | --- | --- | | `priced_models` | Distinct label/mode groups where this provider publishes a comparable-unit base rate, including single-seller or mode-unknown groups | | `eligible_models` | Groups with a nonempty published mode, this provider's rate and at least one other distinct priced provider | | `lowest_models` | Eligible groups where this provider ties or achieves the minimum published rate | | `tied_models` | Subset of lowest groups where at least one other provider has that same minimum | The `*_lowest` sorts order the **raw lowest-model count**, not a percentage, average request cost or universal cheapest-provider score. The eligible denominator stays visible. No eligible groups means unknown comparative coverage and stays last in either direction; a known eligible provider with zero wins is a real zero count. Stable original provider identity breaks ties. Each column can select a different offer; combining its minima does not produce a valid request price. This methodology describes source listing coverage, not model quality, availability, measured spend, free requests, discounts, invoices or routing recommendations. Use explicit original offers and the applicable workload estimator for planning; configure [routes and access](/docs/features/model-registry/) separately. # Compare public model listings **Last updated:** 2026-11-06T14:08:27-03:00 (UTC-3) Open `/registry/compare` to select up to six original public model/service groups and inspect their offers side by side. Selection order is preserved in a shareable URL. Named limits, native base/cache prices, source modalities/features and lifecycle facts retain unknowns and provider variation. This is research, not a gateway model call, private account inventory, combined provider deployment, workload price or quality guarantee. ## Enable and select ```yaml features: ui: true model_registry: true model_registry_compare: true ``` `model_registry_compare` defaults to false and is an operator disclosure control. It requires the public registry only; private catalog/rankings, provider research and advanced filter flags are independent. Normal YAML/API/console feature management applies. There is no new migration or Config parameter root. Source model/provider list/detail responses include only safe `compare_enabled` navigation availability; anonymous pages never query sessions or administration. Search the public source catalog, add one to six models, remove or reorder them, and copy the resulting URL. Exact opaque model-group IDs are used, never private aliases or arbitrary endpoint URLs. Duplicate/malformed selections are rejected; a valid ID missing from the current source returns404 without silently dropping a column. The empty page offers selection controls and makes no comparison or benchmark request until a model is chosen. No provider invocation occurs on page load or selection. ## Read the API GET `/v1/registry/compare` accepts required `models`, a comma-separated ordered list of1–6 unique `m_` plus64-hex IDs, and optional exact lowercase `include_general_eci=true|false` (defaultfalse). IDs/commas are at most401 ASCII bytes. Repeated or unknown query fields are400. Discover actual IDs from the public model list, rather than constructing them from a model name. ```sh BASE_URL='http://localhost:8080' MODELS="$(curl --fail-with-body -sS "$BASE_URL/v1/registry/models?limit=2" | jq -er '[.models[].id] | select(length > 0) | join(",")')" curl --fail-with-body -sS --get "$BASE_URL/v1/registry/compare" --data-urlencode "models=$MODELS" --data-urlencode 'include_general_eci=false' ``` The response has `sources`, `method`, `warnings`, `compare_enabled:true`, `general_eci_requested`, optional shared `general_eci_source` and ordered `models`. Each item contains the complete safe original `model` (all offers, all matching offer IDs and independently attributed columns) and `general_eci` status/result. Responses are no-store and return request/trace IDs. Flag-off is404; no valid required source snapshot is503. See [OpenAPI](/docs/api/). ## Read comparisons correctly A price column uses only its exact comparable base USD/text-token parameter; each selected minimum identifies its original offer/provider. Named input/output limit columns select their corresponding largest published value, with no `max_tokens` fallback. Release dates require an exact published source fact. Column extrema may come from different offers: they cannot be combined into one real deployment or request price. Feature cells preserve published yes/no/unknown counts and source-offer identities. A feature present on one provider is not automatically true for every offer. Modalities and lifecycle also retain per-offer differences. Native media/DBU/batch/context/service/guardrail rates remain original offer details and do not silently enter base USD/token columns. A zero listed rate is not a complete free-call promise. Mixed modes/units/profiles are not an apples-to-apples quality or workload comparison. See [research columns](/docs/features/public-model-research/#filter-and-sort-research-offers) and [provider rate coverage](/docs/features/provider-research/). ## Optional original general ECI General ECI is **off by default per request**. Select the explicit checkbox or set `include_general_eci=true` to request the original [Epoch Capabilities Index](https://epoch.ai/eci) profile. The public comparison flag itself authorizes this public-source publication. It does not require or bypass the private rankings API, roles or flags; those interfaces keep their own authorization. No private usage, model alias or credential is sent to Epoch. Only an exact literal source model ID in published `chat`/`completion` mode can match. Similar names, reasoning settings, dates, provider prefixes and casing are not guessed or fuzzily joined. A matching label is not proof of identical deployed weights/settings. The result preserves original source identity/name, exact decimal ECI points, published interval/date and its position in the full captured profile's deterministic score-descending/source-ID order. It is not re-ranked within your selection. ECI is neither a percentage nor a scale capped at100. | Status | Meaning | | --- | --- | | `not_requested` | Include is false; no Epoch request was made | | `not_applicable` | Published mode is not eligible; an all-ineligible selection does not fetch Epoch | | `unavailable` | No valid optional source capture can be served; the model comparison remains available with a warning | | `unmatched` | Valid optional capture, no exact eligible source ID match; not a low-quality verdict | | `matched` | Original result preserved with the shared source metadata | A successfully served shared `general_eci_source` preserves original source/data URL, CC BY4.0 license and attribution, method/window/unit, archive SHA256, successful capture time, explicit stale state and warnings. Capture time is not evaluation recency. Source interval/sample/coverage limitations and benchmark selection/reporting/training bias remain relevant; no unknown trial count, confidence level or model quality is invented. Unmatched rows do not inherit another model's score. The source is fetched only once for the selection, not once per column. Separate coding and same-run cost/value profiles are delivered by their own roadmap task. This general profile does not claim those dimensions, combine unrelated scales or derive value from a token list price. See [source methodology](/docs/features/model-rankings/#provenance-method-and-coverage). ## Source policy, deadlines and failure Public model capture uses the existing typed `model_registry` source policy. Optional ECI reuses the existing typed `model_rankings` fetch/cache policy (defaults30s/15m); YAML and the explicitly flagged global [rankings settings editor/API](/docs/features/model-rankings/#configure-fetch-policy) remain its management boundary. Enabling private management prerequisites is needed only to use that writer, not to read public comparison. One outer registry operation budget covers required primary, optional metadata and ECI lookup; Epoch is additionally capped by its own fetch policy. Lookup/admission waiting consumes this common budget, rather than resetting the clock for another source. Internal budget expiry may serve a retained valid original source only as marked stale, preserving its original hash/time. Original caller cancellation always wins, including warm-cache and admission paths. Missing optional ECI is explicit partial coverage; it never becomes zero or erases valid model facts. A required-source outage with no accepted snapshot remains503. Existing source licensing, fixed origins, bounded parsers, ID propagation and telemetry privacy apply. Disable the comparison switch to stop new public comparison reads. This does not unpublish local aliases, mutate provider routing/prices, change budgets or stop inference. Copies visitors already made cannot be recalled. The whole registry's remaining workload/coding/value/change workflows and final integration acceptance remain separate deliveries. # Compare workload base costs **Last updated:** 2026-11-06T15:00:28-03:00 (UTC-3) Use `/registry/calculator` to compare the same billable-unit workload across original public offers. Choose the complete applicable source catalog or one to six model/service groups; inspect exact per-request, daily and thirty-day base costs, source/rate identity and qualification. This does not run a model, tokenize a prompt, reserve budget, change prices or produce an invoice. ## Enable and enter a workload ```yaml features: ui: true model_registry: true model_registry_cost_comparison: true ``` The operator flag defaults to false, requires the public registry and is independent of the private calculator, comparison, provider-directory and advanced-filter switches. Normal YAML/API/console flag management applies. There is no new migration/Config root. Safe `cost_comparison_enabled` public navigation metadata avoids administration/session requests. Enter either text input/output counts or a scalar-media quantity/unit, plus requests per day. Use text strings with at most18 integer digits; media quantity allows up to9 fractional digits. No exponent, sign, leading zero, whitespace, JSON numeric quantity or null is accepted. An omitted text side becomes zero; requests per day defaults to1. Media units are `per_image`, `per_character`, `per_audio_second`, `per_video_second`. These are hypothetical billable-unit profiles, not provider request bodies or an inference-support guarantee. The browser submits a read-only POST and renders server amounts/order without financial floating arithmetic. It supports profile/scope/selection changes, pagination, shareable workload URLs, source details and explicit review when a held rate basis changes. Shared URLs contain your selected public IDs and entered planning quantities, not keys, prompts or observed private usage. ## Versioned read-only API ```sh BASE_URL='http://localhost:8080' curl --fail-with-body -sS -X POST "$BASE_URL/v1/registry/cost-comparison" -H 'Content-Type: application/json' --data-raw '{"all_models":true,"input_tokens":"1000","output_tokens":"500","requests_per_day":"10000","limit":50,"offset":0}' ``` The strict body is at most16KiB. Select `models:[returned-source-ids]` with1–6 unique ordered opaque IDs, or `all_models:true`. `all_models:false` may accompany selected models; true cannot. Text counts and media quantity/unit are mutually exclusive. `limit` is a canonical JSON integer1–200 (default50), `offset`0–10000 (default0). Optional `expected_basis_id` is a64-hex current rate/scope basis. Unknown/duplicate/malformed fields are400; a missing selected source ID is404. The request never accepts client rates, source URLs, private aliases, configured/manual sources or credentials. See [OpenAPI](/docs/api/). The response includes original `sources`, `method`, `warnings`, `cost_comparison_enabled:true`, global `basis_id`, applied `scope`, full-source `coverage`, normalized `workload`, page metadata and per-offer `rows`. Each row identifies `model_group_id`, original `model_id`, `offer_id`, `provider`, declared mode, compatibility/reasons and an exact advisory quote. Source/profile coverage counters are independent of your quantities/page; they are not competitive-rank counts. All-source scope includes applicable declared profiles with at least one actual native USD base rate, retaining incomplete/uncorroborated-zero rows and explicitly counting excluded models/offers. Selected scope retains all selected offers, including unknown or non-applicable ones. The original public listing identity and declared mode are preserved; decision/evaluation/rerank services are not blanket-excluded when they publish applicable base-token fields. ## Arithmetic and coverage Text uses exact corresponding input/output base USD token rates from the **same original offer**. Scalar media uses the supported flat base profile for that native unit; ambiguous/conflicting rates are not chosen opportunistically. Daily amount is exact per-request base amount × entered daily count; thirty-day projection is daily ×30, not a calendar-month invoice. Canonical decimal strings and server rational arithmetic preserve tiny rates and large quantities without rounding or overflow into a browser float. No input minimum from provider A is combined with an output minimum from provider B. No DBU conversion, guessed cache/context/service tier, image-token formula, hosted tool fee, discount/margin/tax/minimum/rounding or other unimplemented dimension is added. Those exclusions stay explicit. Existing protected [single-target configured/manual estimates](/docs/features/cost-calculator/) retain their own permissions/provenance; private values never enter this anonymous table. Literal zero rates remain visible source facts, but an uncorroborated all-known-zero community text rate set is an **unknown quote**, including a one-sided zero with the other rate unpublished. A synthetic embedding output zero is not rate evidence. Even a zero requested workload needs a valid actual rate/profile before it can become a known base amount. A supported zero arithmetic result still does not imply a complete free request or fixed-fee waiver. ## Qualification and ordering | Row state | Meaning | | --- | --- | | Complete base quote + `compatible` | Declared base profile and requested published numeric bounds qualify; receives competitive rank by exact per-request amount | | Complete base quote + `unknown` | Known base amount, but relevant requested bounds are not published; shown unranked, after qualified rows, in exact price order | | Partial/unknown/conflict quote | Missing or ambiguous requested rate dimensions; known subtotal is explicitly incomplete, never a cheaper complete price | | `incompatible` | Known requested input/output limits exceeded or an input-only profile is asked for output; no complete total/rank | | `not_applicable` | Selected source offer does not implement this declared base-unit profile; no complete total/rank | Named token limits are compared only with their corresponding positive requested count; `max_tokens` is not a substitute. Embedding/rerank positive output is incompatible. Positive scalar-media quantity has no typed media-quantity bounds in this base profile and therefore remains unknown/unranked, even when its native base amount is known; token limits are never converted into characters, images or seconds. Compatibility describes this published profile/bounds check, not provider health, availability, full request semantics or routing authorization. Qualified complete amounts sort cheapest first, with stable source group/offer identity ties. Unranked complete unknown-bound rows remain a separate group; partial/unknown/incompatible/non-applicable rows never win by being treated as zero. The server calculates the whole admitted scope before pagination. `rank` is omitted for every row that does not meet the complete/compatible rule. ## Rate basis and changed prices Global basis identifies the source content hash, finite pricing profile/unit and selected/all-source scope; per-offer quote basis additionally preserves original rate/limit identity. Quantities, daily count, page and capture time do not pretend the rate changed. A new source/profile/scope basis causes409 **before totals** when `expected_basis_id` is supplied. The UI retains the held basis while quantities/period/pages change and requires explicit review/fresh calculation after409; changing profile/selection starts a new basis. Basis IDs are content fingerprints, not signatures, payment authority or reservations. A quote cannot authorize a later paid call or freeze a provider's future prices. Sources preserve successful hash/time and explicit stale state. The public source policy remains the existing typed [registry policy](/docs/features/public-model-research/#enable-and-configure). ## Bounds, privacy and failure Planning admission uses the existing shared heavy-operation bound (four active heavy operations per process), before source projection/cloning/math. It is shared with existing heavy operations, not four dedicated planner workers. Saturation returns503 without fetching sources. One existing registry operation budget covers admission, source lookup and computation; original caller cancellation takes precedence and every success/failure/drift/cancel path releases its slot. Budget/source failures return503 instead of a falsely complete truncated ranking. No new arbitrary timer or concurrent background worker is introduced. All responses are no-store and carry request/trace IDs. Source spans retain existing privacy/OTLP rules; planned quantities are not reported as model usage, and no identity, ledger, budget or billing event is created. No prompt/provider request, cookie, key or private configured price is sent to public feeds. A flag-disabled endpoint is404; existing stale-source fallback remains explicit. Final load/distribution qualification is separate from this focused source/math/native/browser acceptance. # Public general capability research **Last updated:** 2026-11-06T16:47:43-03:00 (UTC-3) `/registry/quality` presents the complete original general Epoch Capabilities Index (ECI) snapshot without an administrative login. It is a separately authorized public-source projection, independent of private catalog/rankings roles and the selected-model comparison. Source model names are original research identities, never private gateway aliases or an inference grant. ## Enable and query ```yaml features: ui: true model_registry: true model_registry_general_benchmarks: true model_registry: fetch_timeout: 30s cache_ttl: 15m ``` The new operator flag defaults to false and requires `model_registry`/`ui`. It does not enable private rankings, coding/value, publication of local aliases or actual model calls. The public registry's existing typed fetch/cache policy supplies YAML/API/console provenance and versioned management; no new policy parameter or database migration is introduced. ```sh BASE_URL='http://localhost:8080' curl --fail-with-body -sS --get "$BASE_URL/v1/registry/quality" \ --data-urlencode 'limit=50' \ --data-urlencode 'offset=0' ``` `q` searches original source names/identifiers/organizations and is bounded to256 UTF-8 bytes. Optional `organization` is an exact nonempty published source label, bounded to4096 UTF-8 bytes. It does not select a private tenant. `limit` defaults to50 (1–200); `offset` defaults to0 (0–10000). Integers are canonical and unknown/duplicate/malformed fields return400. Disabled publication is404; absent required source or unavailable bounded capacity is503. Full-source sorted organization facets remain independent of the current filter/page. Returned rows keep their **original full-source positions**; filtering does not create a new first-place score. URLs preserve the research filters and pagination. Public responses are no-store, carry request/trace IDs and never fetch an administrative session. ## Scores, dates and uncertainty ECI is the original general-capability **point scale**, with no percentage denominator or fixed100 ceiling. Exact decimal scores, including negative values, and published paired source intervals survive unchanged. A missing interval/organization stays unknown. Published interval overlap limits rank interpretations; a small difference is not proof a model will outperform another on your tasks. The row's source date is retained as reported; it is not the gateway capture time or independently verified evaluation recency. The source is a cumulative snapshot with source-selected coverage and reporting/training bias. Trial/sample counts are not supplied by this profile and are not invented. No popularity, local quality, success-rate or composite dollar score is calculated. [Separate coding and reported value](/docs/features/coding-value-benchmarks/) preserve task-run agents/settings, successes and same-run aggregate cost with their own coverage limitations. Those units never normalize or substitute for ECI points. [Selected comparison](/docs/features/model-comparison/) can retain exact source joins where supported; general browsing does not infer that a provider deployment or private alias matches a benchmarked model. ## Provenance and failure behavior The gateway reuses its existing fixed original Epoch archive parser, safe member selection and source bounds. Source/data/license URLs, attribution, textual method/transformation statement, original score/date/interval and successful capture hash/time remain visible. Data is attributed to Epoch AI under [CC BY4.0](https://creativecommons.org/licenses/by/4.0/); no authorship or endorsement is claimed. The public route uses registry fetch/cache policy, while the private rankings and optional selected-comparison consumers retain their own documented policy. They may reuse the same successful original source cache; each caller keeps its admitted operation budget. A refresh failure can serve a retained source snapshot explicitly marked stale with its original timestamp/hash. Actual caller cancellation wins over a cached success. Heavy-operation admission precedes source cloning/fetch/projection; overload fails promptly. No provider evaluation, inference, usage, ledger or price mutation occurs. Navigation advertises Hub, general benchmarks and product documentation only when their safe publication metadata says they are enabled. Missing metadata is conservative, not a grant. Public metadata never exposes private configuration values. Disable the general flag to hide this surface without changing the other research or inference controls. Remove unsupported new flag keys before a compatible older-binary rollback; setting an unknown key to false is insufficient. See [public research](/docs/features/public-model-research/), [model registry](/docs/features/model-registry/), [private original rankings](/docs/features/model-rankings/), [source notices](/docs/security/third-party/) and [OpenAPI](/docs/api/). # Coding and reported value benchmarks **Last updated:** 2026-11-06T15:44:32-03:00 (UTC-3) The public research registry distinguishes general capability, task resolution and source-reported value. General ECI remains in its original points scale. Coding resolution compares successful trials with attempted trials. Source-reported value compares successes with the aggregate cost published for those same trials; it never combines a quality score with an unrelated catalog price. ## Enable and query `model_registry_coding_benchmarks` and `model_registry_value_benchmarks` are independent operator controls, each defaulting to false and requiring `model_registry` and `ui`. Either can be published without the private external catalog, private rankings or workload calculator. ```yaml features: ui: true model_registry: true model_registry_coding_benchmarks: true model_registry_value_benchmarks: true model_registry: fetch_timeout: 30s cache_ttl: 15m ``` This fragment does not provision services or model connections. Open `/registry/benchmarks` or query its anonymous API: ```sh BASE_URL='http://localhost:8080' curl --fail-with-body -sS --get "$BASE_URL/v1/registry/benchmarks" \ --data-urlencode 'profile=coding' \ --data-urlencode 'cohort=terminal_bench_4' \ --data-urlencode 'limit=50' ``` Use `profile=value` for the separate source-reported value view. The `profile` and `cohort` fields are required; the supported cohort is `terminal_bench_4`. `model_id` selects an exact original model identifier; `q` is bounded to256 UTF-8 bytes. `limit` defaults to50 (1–200) and `offset` to0 (0–10000). Unknown/duplicate/malformed queries are400, a disabled requested profile is404 and an unavailable initial source is503. See [OpenAPI](/docs/api/) for the exact response. The server sorts coding by the exact successes/trials ratio and reported value by successes per100USD from the same positive reported aggregate. Unknown value sorts last; original run identity breaks ties. The response includes exact numerator/denominator plus a six-decimal half-up display. Only the requested computed metric is published: coding responses do not expose computed value ratios, and value responses omit the computed coding fraction while retaining original counts/accuracy as source evidence. A disabled profile cannot be obtained through the other profile. The browser does not calculate or combine costs. Zero successes with known positive cost is a valid zero ratio; zero or missing cost leaves value unknown. ## Read a benchmark row A result belongs to a model **and an agent configuration**, not to a model name alone. Review the dataset and immutable version, agent/version, reasoning setting, successes and attempted trials, published model release date, reported API cost and duration coverage before comparing results. `source_date` preserves the publisher’s model release date; the summary does not provide an evaluation date. Source capture time is when the gateway obtained the data, not when the evaluation ran. Filename prefixes do not establish evaluation recency. A missing cost or timing field stays unknown. Different agents, settings, datasets or trial selections can change results substantially. The interface keeps original runs rather than silently selecting a best configuration for each model. Its cohort selector makes these differences visible. Ordering within a published cohort describes that dataset and its reported, potentially different agent/settings only; it does not predict your application's success rate or invoice. Exact source model identifiers support research links. An exact label match is neither proof that providers serve equivalent deployments nor permission to invoke a model. No private aliases, keys, provider connections, usage or approved financial prices appear in public research responses. ## Original source and limitations The supported source profile reads the original Terminal-Bench 4.0 public leaderboard submissions. The official source pins the dataset version and specifies the accepted run settings and trial coverage. Agent tooling, task mix, sampling, provider variability and possible training contamination limit generalization. These are external published results; the gateway does not execute or certify the benchmark itself. The current original aggregation rounds new total costs to cents and treats absent per-trial cost as zero; older published submissions can retain more decimal places. The gateway preserves the actual published decimal, rather than applying new rounding to historical rows. The source generator averages duration only over trials with timestamps and does not publish the coverage counts in the submission summary. Consequently cost and timing completeness remain unknown: a positive published total supports a clearly labeled source-reported ratio, not a verified complete expense or per-trial timing claim. No private provider bill or bulk-trial verification is performed. Coding resolution and value preserve separate units. Zero reported cost does not imply unlimited free work or a meaningful infinite value. Missing or invalid same-run cost cannot be substituted with a token list price. Repeated trials are attempts, so “successful trials per USD” must not be read as distinct business tasks completed. Source identity, revision, original links, license, capture hash/time, stale state and method remain visible. See [third-party notices](/docs/security/third-party/) and [public research](/docs/features/public-model-research/). Source outages affect research only; they do not change inference, routing, billing or budgets. ## Operations The public benchmark controls are separate operator disclosure flags, disabled by default, and depend on the public registry. Existing typed registry source policy supplies the shared refresh budget and cache lifetime; policy changes use the same YAML, administrative API and console provenance rules. Flags never grant a user's administrative permission or model-call scope. Publication requires outbound HTTPS to the fixed original source. Each refresh resolves the original repository’s current immutable commit, validates the expected dataset declarations, supported generator hash and license at that commit, then reads every bounded submission from that same revision. It never trusts client URLs or mutable per-file download hints. The gateway uses bounded parsing and an atomic complete source capture; a failed file does not publish a truncated leaderboard. A successful retained snapshot may be marked stale after a refresh failure; its original successful hash and timestamp are preserved. Caller cancellation never becomes a successful cached response. No arbitrary source URL or user-supplied benchmark executable is accepted. Disable the dependent benchmark flags to hide publication. Visitor copies cannot be recalled. Keep configuration keys compatible when rolling back a binary: an older flag catalog rejects keys it does not know, including keys set to false. Broader release/upgrade qualification remains part of the distribution workflow. # Model lifecycle, source history and RSS **Last updated:** 2026-11-06T16:05:49-03:00 (UTC-3) The public registry can show source-declared deprecations/replacements and changes between original catalog revisions. A catalog edit can be a correction, a newly indexed listing or a changed claim. It does not prove a model launch, effective provider price change or service shutdown. Research never changes private routing, keys, approved prices, budgets or billing. ## Enable the independent views ```yaml features: ui: true model_registry: true model_registry_lifecycle: true model_registry_history: true model_registry_rss: true model_registry: fetch_timeout: 30s cache_ttl: 15m ``` Each new operator disclosure flag defaults to false. Lifecycle and history independently require the registry; RSS additionally requires history. Private catalog, rankings, workload planning and benchmark flags are independent. Existing typed registry policy provides YAML/API/console management with provenance, versioning, permissions and audit; no new database or runtime executable is required. Open `/registry/updates` for the research views. Canonical `view=history` shows catalog history, `view=new` selects actual listing additions, `view=declared` shows published deprecations, and `view=replacement` shows published successors. Public navigation uses safe availability metadata, never an administrative session. The same-origin RSS link subscribes to a read-only feed; the gateway sends no email, webhook or other proactive message. ## Declared lifecycle GET `/v1/registry/lifecycle` accepts `state=all` (default), `declared` or `replacement`. `declared` selects a published deprecation date or reference; `replacement` requires a published successor. `all` is their union. Missing replacement or date remains unpublished; a model name or listing removal cannot supply it. Each row retains the exact original offer and source. `as_of` is the original catalog capture timestamp. A declared date after that UTC day is `scheduled`; one on or before that day is `effective_date_passed`; an absent date is `date_unpublished`. These describe the source's date relative to its capture, **not verified provider availability**. A stale capture keeps its original date and explicit stale state. Current lifecycle viewing does not fetch repository history, and it is not a lifetime archive of removed listings. ## Historical revision changes GET `/v1/registry/history` reads the original public cost-map repository's file commits. `page` defaults to1 (1–1000). Each source page contains up to8 commits, each compared to its **declared first parent**, not the preceding item in a path-filtered result list. Use older/newer source-page navigation separately from the event pagination inside a source page. The window lists captured commits, oldest/newest committer timestamps, source page, count, `has_more` and `complete:false`. This is bounded revision coverage, not complete lifetime history or a promise that every change over a date interval is present. An exhausted page returns200 with no commits/events and no fabricated timestamp. The first appearance in a captured diff is a **listing addition within that transition**, not proof of the model's first publication anywhere. Events identify the original offer key, exact commit/parent, original source link/date, changed typed fields and safe before/after facts. The same admitted parser processes both revisions, including canonical exact decimal/unit values; a numeric spelling change alone does not invent a price change. Model grouping IDs can change after metadata edits, so historical event identity uses original listing keys instead. Filter categories are `listing_added`, `listing_removed`, `provider_added`, `provider_changed`, `price_changed`, `capability_changed`, `lifecycle_changed`, `metadata_changed` or `all`. One event can have multiple kinds. New provider appearance describes catalog coverage, not a company's founding or an available configured connection. Listing removal alone is not deprecation. Only the admitted safe published fields participate: unsupported/raw source fields are not secretly exported or claimed as covered history. Source rates retain their original native currency/unit/conditions; before/after values are not a combined quote, provider invoice or announcement of an effective rate change. ## Filters, pagination and examples Both JSON APIs accept exact `provider`, original `offer_id`, normalized published `model_id`, bounded `q` (256 UTF-8 bytes), `limit` (default50,1–200) and `offset` (default0,0–10000). Exact identity filters are bounded to4096 UTF-8 bytes. Historical identity filters match either before or after so an identity change remains discoverable; the displayed event uses after, or before for a removed listing. Source `page` applies only to history/RSS. Unknown, duplicate and malformed parameters are refused with400. ```sh BASE_URL='http://localhost:8080' curl --fail-with-body -sS --get "$BASE_URL/v1/registry/history" \ --data-urlencode 'page=1' \ --data-urlencode 'kind=price_changed' \ --data-urlencode 'limit=50' curl --fail-with-body -sS --get "$BASE_URL/v1/registry/lifecycle" \ --data-urlencode 'state=declared' \ --data-urlencode 'limit=50' ``` Filtering and counts precede result pagination. Empty selection is not a source failure. Disabled required flags return404; unavailable required initial data or a failed bounded operation returns503. See [OpenAPI](/docs/api/) for exact shapes and defaults. ## RSS subscription and source integrity GET `/v1/registry/history.rss` accepts the same history filters and source/event pagination. Copy its URL into your RSS reader. The UI retains source filters/page and starts the feed at result offset0. For ongoing new changes use source page1; older source pages are browsing windows whose membership can shift when new commits arrive. Feed items retain deterministic opaque GUIDs and original source commit dates. Channel/item links are fixed absolute original source URLs; request `Host` or proxy headers never invent a publication authority. Source text is XML-escaped and descriptions contain trusted fixed prose, not active upstream HTML. This feed grants no access to private administrative audit or tenant usage. Source attribution, full MIT notice, original license link, aggregate capture hash/time, captured revisions and stale/coverage warnings remain visible. The accepted MIT notice is checked for every distinct referenced commit and first parent, not inferred from the newest revision. A required immutable blob/license or parse failure prevents publishing a truncated window. The process retains only a bounded projected window keyed to its source page; a different page is never served as that page's stale fallback. The shared operation budget covers admission and required fetches; caller cancellation wins over cached success. Restart clears process-local research caches. Disable the dependent RSS flag before history; lifecycle can remain independent. Visitor copies cannot be recalled. An older binary does not understand new flag keys even when false: remove unsupported YAML/managed keys as part of a compatible rollback. No schema downgrade, infrastructure provisioning or provider data migration is performed. See [public research](/docs/features/public-model-research/), [provider research](/docs/features/provider-research/), [third-party notices](/docs/security/third-party/), [model registry](/docs/features/model-registry/) and [operations](/docs/operate/operations/). # Attributed model rankings **Last updated:** 2026-11-21T09:54:10-03:00 (UTC-3) The **Model catalog** contains a separate external benchmark view. Its implemented source profile is the [Epoch Capabilities Index (ECI)](https://epoch.ai/eci), a composite general-capability scale. It is not a percentage, a usage/popularity chart, a local gateway experiment or a guarantee that a model fits your workload. Published names are source identities, not routable gateway aliases. ## Enable and read The operator flag `model_rankings` defaults to false and requires `external_model_catalog` (and its `ui` prerequisite). Global `catalog:read` permission is required. Tenant roles and inference credentials cannot read this administrative catalog. Flags never grant permissions or change a model's actual availability. ```yaml features: ui: true external_model_catalog: true model_rankings: true model_rankings: fetch_timeout: 30s cache_ttl: 15m ``` Supply ordinary installation configuration separately. With an authenticated same-origin admin cookie jar: ```sh BASE_URL='http://localhost:8080' COOKIE_JAR='./gateway-session.cookies' curl --fail-with-body -sS --cookie "$COOKIE_JAR" \ "$BASE_URL/api/v1/admin/model-rankings?source=epoch_eci" ``` The source selector is optional and only `epoch_eci` is supported. Unknown, duplicate or malformed parameters are refused. The API returns the bounded complete source snapshot; the console provides search, organization filtering and pagination while retaining original source ranks. ## Provenance, method and coverage The gateway fetches the fixed original [Epoch download](https://epoch.ai/data/benchmark_data.zip) and reads only `epoch_capabilities_index/eci_scores.csv`. It does not scrape a competitor, send your provider credentials, query your private usage, map names to aliases or run evaluations. Source links and [ECI methodology](https://epoch.ai/data/eci-documentation) remain visible. Each result includes the exact source model identity, display name, decimal ECI score, source date and published interval where available. An absent organization or interval remains unknown. `source_date` is the source row's date, not the gateway fetch time or proof of a recent evaluation. Scores are ordered numerically descending, with exact source identity breaking ties. ECI has no percentage denominator or maximum of100. Interval overlap prevents interpreting a small rank difference as a proven superiority claim. This is a cumulative source snapshot, with **no local usage window or local sample count**. The gateway does not invent trial counts, recency, statistical confidence levels or a combined intelligence/coding/value score. Coverage is selected by the source and inherits benchmark selection, reporting/training bias and uneven model coverage. Read the source methodology before drawing conclusions; a missing model does not mean a low score. Separate coding or value-for-money cohorts are not part of this profile. API/UI provenance includes creator, original source/data URLs, license, attribution, transformation/method statement, content SHA-256, successful capture timestamp, freshness and limitations. Data is attributed to Epoch AI under [CC BY4.0](https://creativecommons.org/licenses/by/4.0/); the gateway parses, sorts and presents it without claiming authorship or endorsement. Local request analytics and your private evaluation datasets remain distinct. ## Refresh and failure behavior The successful snapshot is cached only in the responding process. After its TTL, one bounded refresh is admitted for this source. A failed refresh serves the last successful snapshot with `stale:true`, `Warning:110` and its original capture timestamp/hash. An unavailable initial feed returns503 instead of fabricated results. Fetch freshness is not evaluation recency; different replicas may hold different successful snapshots. Restart clears this cache. Redirects are refused. No client URL or uploaded archive is accepted. The parser bounds the compressed download to16MiB, the exact CSV to2MiB and rows to5000; it does not extract files to disk. Ambiguous members, duplicate identities or invalid scores/dates/intervals fail the refresh without publishing a truncated leaderboard. ## Configure fetch policy `model_rankings.fetch_timeout` defaults to30s (1s–2m inclusive) and `model_rankings.cache_ttl` to15m (1m–24h inclusive). The typed API and console show the effective policy, source and version. A separate default-off `model_rankings_management` switch enables management with the required global permissions and PostgreSQL; the viewing flag alone never permits writes. GET `/api/v1/admin/model-rankings/settings` requires global `config:read`; PUT and DELETE require global `models:manage`. PUT sends `{version,model_rankings:{fetch_timeout,cache_ttl}}`; DELETE sends only `{version}`. Saves and revert use the current version, CSRF and audit, returning204 on success. A stale version is409. New operations use the refreshed policy; an in-flight fetch keeps its captured budget. Reverting removes the override and restores the YAML/default policy. Disabling only management makes a saved override dormant and restores the baseline; re-enabling restores the saved policy. YAML file changes still require the normal rollout. The global `boot_settings_view` infrastructure summary also exposes these safe effective/default/source/bounds fields; it is metadata, not a generic writer. Source fetches propagate the request and W3C trace context and export a correlated non-model HTTP client span when tracing is configured. No ranking changes routing, inference authorization, budgets, billing, prices or public Hub publication. Disable `model_rankings` to hide its read surface. Operational feature controls, RBAC and any applicable license controls remain independent. See [Model registry](/docs/features/model-registry/), [calculator](/docs/features/cost-calculator/), [analytics](/docs/features/analytics-experience/), [configuration parity](/docs/reference/configuration-parity/) and the [OpenAPI](/docs/api/). ## Public comparison reuse The independent public [model comparison](/docs/features/model-comparison/) can explicitly opt into this original general ECI profile under `model_registry_compare`. It shares typed fetch/cache policy and original parser/provenance, but is separately authorized public-source publication: private catalog/rankings flags and roles remain prerequisites only for their private interfaces. Comparison matches literal eligible source IDs, retains full-snapshot position and original point/interval/date values, and has explicit unavailable/unmatched/not-applicable states. It never queries local quality or usage. Internal budget/admission expiry may use retained marked-stale data for a live caller; actual caller cancellation wins. ## Separate original coding and value profiles The public [coding and reported value](/docs/features/coding-value-benchmarks/) views preserve original model-agent-setting runs and same-run successes/costs under their own operator flags. They do not normalize ECI points into success percentages, map private aliases or infer value from token list prices. Cost/time completeness stays unknown when the original summary does not report it. ## Complete anonymous general snapshot The independent default-off [public general research](/docs/features/general-quality/) surface publishes the complete original ECI snapshot with filters, full-source facets/ranks and explicit source uncertainty. It uses public registry policy and never grants private catalog access. Its disclosure flag, private rankings and optional selected comparison remain separate consumers; none infers a private alias mapping. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `GET /api/v1/admin/model-rankings` | The read-only external capability index snapshot, for global catalog readers | | `PUT /api/v1/admin/model-rankings/settings` | Saves a versioned override of the rankings fetch and cache settings | | `DELETE /api/v1/admin/model-rankings/settings` | Removes that override and restores the YAML or default settings | # Providers **Last updated:** 2026-11-27T02:00:32-03:00 (UTC-3) A **provider** is a connection to an AI service: OpenAI, Anthropic, Bedrock in your AWS account, a vLLM on your network. The gateway ships **129 presets**, connections already filled in with protocol, URL and authentication method, so you only supply the credential. This guide shows how to connect, authenticate and use each provider family. ## Add a provider **From the console:** in **Providers → Add provider**, choose the preset, enter the credential and save. The credential is stored encrypted in PostgreSQL and never comes back in listings. Then create a model (alias) that points to it and use **Test** to make a real call before releasing it. **From the YAML:** a provider can name a preset and inherit the protocol, URL, authentication and the name of the key variable. Whatever you declare on top of it wins: | Key | What it does | | --- | --- | | `providers[].id` | The connection's ID, which model targets name | | `providers[].protocol` | The wire protocol the gateway speaks to it: `openai`, `anthropic`, `gemini`, `bedrock` and the others below; a preset fills it in | | `providers[].preset` | Names one of the shipped presets (listed in **Providers → Add provider** and `GET /api/v1/admin/provider-presets`); the provider inherits its protocol, base URL, authentication and key variable, and any key declared next to it wins | ```yaml providers: - id: groq preset: groq # https://api.groq.com/openai/v1, key in GROQ_API_KEY - id: mistral preset: mistral api_key_env: MISTRAL_KEY_PROD # overrides the default variable models: - id: chat-rapido targets: [{provider: groq, model: llama-3.3-70b-versatile}] ``` `GET /api/v1/admin/provider-presets` lists every preset. ## Editing a connection Protocol, authentication choices and HTTP mode use the shared [parameter schemas](/docs/reference/parameter-registry/). Their compiled context matrix describes supported options, not the validity of a particular destination or credential. The backend still validates the complete effective configuration and cloud-host trust. A required protocol has no universal default; a selected preset can supply its protocol and authentication before validation. The HTTP selector distinguishes omitted automatic behavior from explicit `auto`, while both retain the existing host-specific transport selection. Explicit `http1` or `http2` remains an operator choice. No provider call is made just to select or save these schema values. With `provider_management` and permission to manage providers, **Providers → Edit** uses the same versioned `PUT /api/v1/admin/providers/{id}` operation as the API. The YAML is the base; a validated PostgreSQL override wins until explicitly reverted. A save validates the complete snapshot and records the actor and request ID. It does not test the credential or make a model call. For keyless or cloud-identity modes, `credential_configured: true` means no stored static credential is required; it does not prove a stored key exists or that a cloud identity is currently valid. The form keeps the configuration revision you reviewed when opening it. A later refresh does not silently rebase that draft; an HTTP 409 keeps the draft/revision, and closing/reopening explicitly reviews the newer configuration. The editor retains every supported authentication option when you save without changing it. Controls depend on the authentication type: - **Bearer or none:** no additional authentication options. - **Custom header:** `header`. - **Azure Entra:** `credential` and `scope`. - **Google ADC:** `credential` and `scope`. - **AWS SigV4:** `credential`, `region`, `service` and `profile`. - **OCI API key:** `region`, `profile` and `compartment`. Nonempty options belonging to another type are rejected; an empty optional field keeps its existing unset/default meaning. An official AWS endpoint can supply its region, so a valid omitted region does not become a required form input. A YAML-only custom Bedrock endpoint still needs an explicit signing region and retains its existing trust restriction. The YAML, API contract and selector cover the same 16 existing wire protocols, including SageMaker and OCI; a listed protocol does not prove that a particular model or cloud credential works. A preset can define its own authentication. Choosing protocol-default API-key authentication overrides that default explicitly; API callers use `auth: {type: bearer}`. Omitting `auth` lets the preset choose its authentication. The console preserves the mode you selected, including a bearer override of a cloud preset. **Keeping or replacing a key:** when both the current and saved authentication types use a static key (`bearer` or `header`), an empty key field retains the opaque current credential. Enter a new key to replace it. No read returns that key. Static credentials must be valid HTTP header values: ASCII controls `0x00–0x1F` other than horizontal tab, and `0x7F` (DEL), are refused. The API accepts at most2048 bytes for its write-only `secret`; blank retains the current static credential as above. YAML references are checked at startup, and the resolved value is captured and checked again before every operation, so an invalid or missing rotated credential fails closed with503 before any provider send or durable attempt. Correct the external value to recover; no database cleanup or key disclosure is required. Existing scalar environment/file credentials retain their historical length and non-ASCII-byte compatibility; pool entries retain their separately documented2048-byte/UTF-8 bounds. Cloud/no-auth connections do not read inactive scalar material. **Switching to identity or no authentication:** the form warns before saving. A successful save removes the connection's stored ciphertext and stops inheriting its YAML key reference. That mode refuses a supplied static key. Returning to bearer/header requires a fresh key; the previous key is not silently restored. Changing the form's type/protocol clears typed secrets and incompatible option drafts. A rejected request or stale version preserves the existing metadata, credential and audit state. **Revert to YAML** is a separate explicit action. It restores the declared connection, including its operator-owned credential reference when one exists. Removing local ciphertext does not revoke the key at its provider or delete the external secret. Older versions may have left an unused encrypted key on a connection already in identity/no-auth mode. Startup and reads preserve those bytes but never consume them; a blank static edit cannot resurrect them. To remove them, review that connection and explicitly **Edit → Save** in its existing nonstatic mode, or issue the equivalent authorized versioned PUT without a static secret. The save clears the ciphertext and records an audit event. There is no automatic upgrade sweep or schema migration for this repair. See [upgrade preparation](/docs/operate/operations/#provider-authentication-upgrades). Unknown or unsupported authentication snapshots are read-only in the editor rather than reconstructed into a lossy save. Before upgrading, validate the YAML and use the compatible version's API to remove previously ignored misplaced fields in stored overrides (for example, `credential`/`scope` on header auth or `scope` on AWS auth). Do not remove consumed options or replace a key just to edit unrelated metadata. See [upgrade preparation](/docs/operate/operations/#provider-authentication-upgrades). ## What the presets include - **OpenAI-compatible:** - OpenAI, Groq, Together, Fireworks, DeepSeek, Mistral, xAI, Perplexity, OpenRouter; - Cerebras, DeepInfra, SambaNova, Nebius, Hyperbolic, Novita, Moonshot; - Alibaba (Qwen), Z.ai, NVIDIA NIM, Hugging Face, Cohere, GitHub Models; - DigitalOcean Gradient, Maritaca (Sabiá), Heroku and others. - **Native, with translation:** Anthropic, Gemini, Vertex AI, Bedrock (Converse), Cohere v2, SageMaker and OCI. - **Clouds:** Azure OpenAI, Azure AI Foundry, Vertex AI, Bedrock, Databricks and Snowflake Cortex. - **Local runtimes:** Ollama, vLLM, LM Studio, llama.cpp, llamafile, SGLang, Xinference, TGI, Docker Model Runner, Lemonade, text-generation-webui and Infinity. - **Embeddings only:** Jina AI and Voyage AI. - **Media:** ElevenLabs, Amazon Polly and Azure AI Speech (speech), Deepgram (transcription), Stability AI, Replicate, Fal, Black Forest Labs and Recraft (image) and Runway (video). - **Generated from the community cost map:** Poe, Meta, Helicone, Vercel v0, Crusoe, GMI, Tencent and others. They carry only the URL and the variable name; they have not been tested with a real key. ## Authentication | `auth.type` | When to use | |---|---| | absent or `bearer` | API key, in the protocol's standard header | | `header` | Key in a header with a different name: `{type: header, header: api-key}` | | `none` | Local runtimes without authentication | | `azure_entra` | Entra ID. `credential: auto` tries client secret, workload identity and the Azure CLI; `managed_identity` is explicit | | `gcp_adc` | Google Application Default Credentials | | `aws_sigv4` | AWS IAM. `credential: auto` tries environment variables, IRSA, Pod Identity, ECS and the AWS CLI; `credential: instance` uses the EC2 instance role through IMDSv2, without the CLI; `region` must match the endpoint | | `oci_api_key` | OCI CLI profile (`~/.oci/config`) | The other `auth` keys depend on the type; a nonempty key that belongs to another type is rejected. | Key | What it does | |---|---| | `providers[].auth.header` | The header that carries the key, for type `header` (for example `api-key` on Azure) | | `providers[].auth.credential` | The identity source for a cloud type: `auto`, `cli`, `client_secret`, `workload_identity` or `managed_identity` on `azure_entra`; `auto`, `env`, `web_identity`, `container`, `instance` or `process` (also `cli`) on `aws_sigv4`; `auto` on `gcp_adc` | | `providers[].auth.scope` | Overrides the OAuth scope the token is requested for, on `azure_entra` (`https://cognitiveservices.azure.com/.default` or `https://ai.azure.com/.default`) and `gcp_adc` (`https://www.googleapis.com/auth/cloud-platform`); empty keeps the cloud's default | | `providers[].auth.region` | The region that signs `aws_sigv4` calls and that `oci_api_key` calls go to; an official AWS endpoint supplies it, a custom Bedrock endpoint needs it | | `providers[].auth.service` | The SigV4 service name for `aws_sigv4`; empty means `bedrock`, or `sagemaker` on a `sagemaker` connection and `polly` on a `polly` connection | | `providers[].auth.profile` | The AWS CLI profile (`aws_sigv4`, local development) or the OCI config profile (`oci_api_key`) to read; a profile name, never a secret | | `providers[].auth.compartment` | The OCI compartment the calls run in, for `oci_api_key`; empty uses the tenancy (the root compartment) | Cloud identities obtain their credential from the configured identity/profile and only work with that cloud's official URL. New successful nonstatic saves store no static API key; older unused encrypted keys follow the [explicit cleanup rule](#editing-a-connection). On Kubernetes, prefer workload identity (workload identity on AKS and GKE, IRSA or Pod Identity on EKS); each cloud's CLI is for local development. ```yaml providers: - id: azure preset: azure_openai_entra base_url: https://contoso.openai.azure.com/openai/v1 - id: bedrock preset: bedrock base_url: https://bedrock-runtime.us-east-1.amazonaws.com models: - id: chat targets: [{provider: azure, model: gpt-4.1-nano}] # on Azure, model is the deployment name ``` ## Coding tools behind the gateway ### Claude Code ```bash ANTHROPIC_BASE_URL=https://gateway.example.com \ ANTHROPIC_AUTH_TOKEN= \ ANTHROPIC_MODEL=claude-haiku-4-5 \ ANTHROPIC_SMALL_FAST_MODEL=claude-haiku-4-5 \ claude ``` - The alias needs the `messages` capability, on an `anthropic` provider, and **with the model's real name** (`claude-haiku-4-5`, not `claude`). Claude Code uses the name to decide which features to request. - A `messages` alias on another provider (OpenAI, Gemini, Bedrock, Cohere) also works, through [protocol translation](/docs/features/protocol-translation/); signed thinking is then left out, prompt cache marks reach Claude on Bedrock (and are left out elsewhere, see [prompt caching](/docs/features/prompt-caching/)), and Anthropic's own tools (web search, computer use) are refused. - The gateway forwards the `anthropic-beta` header that Claude Code sends to `anthropic` connections, when it is a well-formed list of feature names (up to 1,024 characters; anything else is dropped), and serves `/v1/messages/count_tokens`. Other client headers reach a provider only when its [`forward_client_headers`](#forwarded-client-headers) lists them. - Anthropic bills Claude Code requests against the account's purchased balance. Promotional credit that does not include Claude Code does not cover them, with or without the gateway. ### Codex CLI In `~/.codex/config.toml`: ```toml model = "gpt-4.1-mini" model_provider = "gw" [model_providers.gw] name = "ai-gateway" base_url = "https://gateway.example.com/v1" env_key = "GW_KEY" # the variable holding the gateway key wire_api = "responses" ``` The alias needs the `responses` capability and the model's real name. In non-interactive mode, close stdin (`< /dev/null`). On a non-OpenAI target the alias is translated ([protocol translation](/docs/features/protocol-translation/)): the CLI's `store: false` stateless mode works, and its encrypted reasoning items are left out. ### Codex model picker Without help, the Codex CLI's model picker (`/model`) lists only the models bundled with the CLI. With the flag `codex_model_catalog` on (operator control, off by default, applies without restart), the gateway answers the CLI's own catalog request, so the picker lists the gateway's aliases instead. ```yaml features: openai_responses: true codex_model_catalog: true ``` In `~/.codex/config.toml`, point the provider's `model_catalog_url` at the gateway's `/v1/models`. Without it the CLI never asks the provider for a catalog: ```toml model = "coder" # an alias with the responses capability model_provider = "gw" [model_providers.gw] name = "ai-gateway" base_url = "https://gateway.example.com/v1" env_key = "GW_KEY" # the variable holding the gateway key, for example gw_live_... wire_api = "responses" model_catalog_url = "https://gateway.example.com/v1/models" ``` **What the CLI sends.** `GET /v1/models?client_version=0.163.0` with the gateway key as `Authorization: Bearer`, `originator: codex_cli_rs` (interactive) or `codex_exec` (`codex exec`), and a matching `User-Agent`. The gateway selects the catalog by the `client_version` query parameter alone (`x.y.z`, optionally followed by a pre-release or build suffix): every front end of the CLI sends it, and the headers vary. Any other request, or the flag off, gets the standard OpenAI list, byte for byte as before. Sending `client_version` from another client changes only the shape of the same authorized list. **What is listed.** Exactly the aliases the standard list shows the key, narrowed to the ones the CLI can call: the alias has the `responses` capability, `openai_responses` is on, the key (after its team policy) may use `route:responses`, and, with [feature plan entitlements](/docs/features/entitlements/) on, the team's plan grants `openai_responses` for that model. A wildcard alias's own pattern (`openai/*`) is not listed; the names discovered behind it are. Otherwise the list is empty (`{"models":[]}`), never a model the key cannot call. Aliases keep their declaration order. The answer has `Cache-Control: no-store`. **Each entry.** The gateway ships a copy of the CLI's own model catalog and generic base prompt, taken unchanged from the open-source Codex repository (Apache-2.0, tag `rust-v0.163.0`; source, commit and hashes in [third parties](/docs/security/third-party/#codex-cli-model-catalog)). Nothing is fetched at run time. An alias gets one of two entries. A known entry tells the CLI user which model family serves the alias (its description, reasoning levels and the CLI's own prompt name it); an override of the base prompt does not hide the rest of the entry, so leave such aliases on the translated entry (different target models) if that must stay private. - **A model the CLI knows.** When every target of the alias names the same model of that catalog (a provider prefix such as `openai/` is ignored; a name discovered behind a wildcard alias is its own upstream model), the entry is the CLI's own entry for that model under the alias name: its reasoning levels, service tiers, tools, truncation policy and the `model_messages` from which the CLI builds that model's own base prompt. The gateway rewrites only `slug` and `display_name` (the alias ID), `priority`, `visibility: list`, `supported_in_api: true`, and sets `upgrade` and `availability_nux` to `null` (no nudge toward a model under another name). `context_window` stays the CLI's unless every target declares `targets[].max_input_tokens`; then it is the smallest of them, capped at the entry's `max_context_window`. The alias's own ID is not evidence: an alias named like a known model but served by another one gets the translated entry. A CLI older than the entry's `minimal_client_version` also gets the translated entry, which it can decode. - **Any other model.** A translated entry with the fields the CLI requires (checked against codex-cli 0.163.0; one missing field makes it reject the whole catalog), filled from what the gateway knows, and otherwise with the value the CLI uses for a model it has no metadata for, so no entry claims a reasoning level, tool or verbosity the alias may lack: | Field | Value | Source | |---|---|---| | `slug`, `display_name` | the alias ID | gateway alias | | `priority` | position in the answer (0, 1, ...) | gateway declaration order; the picker sorts by it | | `visibility` | `list` | shown in the picker | | `supported_in_api` | `true` | the alias is called with a gateway key | | `context_window` | the smallest `targets[].max_input_tokens`, only when every target declares one; omitted otherwise | operator ([context window check](/docs/features/context-window-check/)) | | `base_instructions` | the CLI's generic base prompt (`prompt.md` of the vendored tag), or `models[].codex.base_instructions` | vendored copy or operator | | `description`, `default_reasoning_level` | `null` | client default for an unknown model | | `supported_reasoning_levels`, `experimental_supported_tools` | `[]` | client default | | `shell_type` | `default` | client default | | `support_verbosity` | `false` | client default | | `truncation_policy` | `{"mode": "bytes", "limit": 10000}` | client default | Optional fields (service tiers, input modalities, compaction limits) are left out of a translated entry and take the CLI's own defaults. A known model's service tiers (the CLI's `/fast`) send `service_tier` upstream; a request for a tier the price set does not approve is refused with `service_tier_not_approved` ([service-tier pricing](/docs/features/service-tier-pricing/)). The CLI drops a catalog larger than 1 MiB; a known entry is 20-65 KB (about 16 of the largest fit), so aliases that do not fit are left out (in declaration order, a warning is logged with the count). **Base instructions per alias.** `models[].codex.base_instructions` replaces the base prompt the CLI uses with that alias, for both kinds of entry (on a known model it also removes the entry's `model_messages.instructions_template`, which the CLI would otherwise prefer). Non-empty UTF-8 text without NUL, at most 65536 bytes; omitted keeps the CLI's own prompt. Not allowed on an `alias_of` entry, which uses its canonical model's value. Set it in YAML or with the admin model API (`PUT /api/v1/admin/models/{id}`, field `codex`); the console model editor has a **Codex base instructions** field for it (shown while `codex_model_catalog` is on, not on an alias; empty removes the block). Applies on the next catalog request; the CLI caches its catalog (see below). ```yaml models: - id: team-coder capabilities: [responses] targets: - {provider: openai, model: gpt-5.5} codex: base_instructions: | You are a coding agent for the platform team. Follow the repository's AGENTS.md. ``` A user-level `model_instructions_file = "/path/to/instructions.md"` in `config.toml` still replaces whatever the catalog says. **Keys and team policies.** The catalog and the CLI's calls both need `route:responses` in the key's scopes after its team policy. The bundled `config/gateway.yaml` (and the Helm chart's copy) lists it in the example team policy, beside `route:models` and `route:chat`; a policy without it gets an empty catalog and 403 on `/v1/responses`. **Check it.** `codex debug models` prints the catalog the CLI loaded (it caches it in `models_cache.json` under the CLI's home directory; delete that file to fetch again). ## Per-provider notes ### OpenAI Responses API as an upstream An `openai` target takes `api: chat_completions`, `api: responses` or `api: auto`. With `api: responses`, Chat Completions (and the Messages and GenerateContent routes) are sent to `/responses`, for models that only exist there; with `api: chat_completions`, a `responses` alias is served by a server that only has `/chat/completions`. `stop`, `n`, `logprobs`, `seed` and the penalties have no Responses equivalent and are refused with 422; the request goes with `store: false` unless the client asked to store. Details in [protocol translation](/docs/features/protocol-translation/#openai-targets-chat-completions-or-responses). `api: auto` picks the API per request: Responses when Chat Completions would refuse the request (`reasoning_effort: max` or in its object form, function tools with a reasoning effort other than `none`) and the translation carries every field, Chat Completions otherwise. It suits current reasoning models, which accept those requests only on Responses, without moving every request there ([the rules](/docs/features/protocol-translation/#api-auto-the-api-chosen-per-request)). The server must have both APIs: an OpenAI-compatible server without `/responses` (many self-hosted ones) should keep `api: chat_completions`. ### Anthropic A `chat` alias with an `anthropic` target is translated to the Messages API, and the response comes back in Chat Completions format. | Chat Completions | At Anthropic | Note | |---|---|---| | `system`, `developer` | `system` | | | text and image | `text` and `image` blocks | image only as a data URL; a remote URL gives 422 | | `tool_calls` and `tool` | `tool_use` and `tool_result` | `arguments` must be a JSON object | | `max_tokens` | `max_tokens` | default 4096 | | `tools`, `tool_choice` | `tools`, `auto`/`any`/`none`/`tool` | | | `reasoning_effort` | `thinking` with a budget of 1024, 2048 or 4096; with `thinking_mode: adaptive` on the target, adaptive thinking with that effort ([Claude thinking mode](/docs/features/protocol-translation/#claude-thinking-mode)) | returned in `reasoning_content` | | `cache_control` on a part, a message or a tool | `cache_control` on the matching block or tool | `{"type": "ephemeral"}` with `ttl` `5m` or `1h`; at most four ([prompt caching](/docs/features/prompt-caching/)) | | `n`, `logprobs`, `seed`, penalties, `response_format` | — | rejected with 422 before the call | - **Cache tokens:** appear in `prompt_tokens_details.cached_tokens` (reads) and `cache_creation_tokens` (writes). With `prompt_cache: {mode: auto}` on the target the gateway marks the cache points when the client marks none ([prompt caching](/docs/features/prompt-caching/)). - **Truncated stream:** a stream that ends without `message_stop` is cut off without `[DONE]`, so the client does not take the truncated response for a complete one. - **Route choice:** an alias serves `chat` or `messages`, never both. - **Limit:** the signature of reasoning blocks does not fit in the Chat format. In a round that continues a tool call, Anthropic responds without reasoning. ### Gemini and Vertex AI - **Gemini:** an alias with a `gemini` provider serves Chat Completions translated to `generateContent`. The translation covers tools (with the Gemini 3 reasoning signature preserved across rounds; the signature rides inside the tool call ID, and the gateway removes it when the same conversation goes to another provider, through a fallback or a model switch, since OpenAI accepts IDs of at most 64 characters and Anthropic refuses `~`), `json_schema`, `reasoning_effort`, images as data URLs and streaming with usage. A stream that carries an error event, or ends without a finish reason, is cut off without `[DONE]`, so neither the client nor the semantic cache takes it for a complete response. The same provider serves the native route `/v1beta/models/{alias}:generateContent`. - **Vertex AI** (preset `vertex_ai`): the same, with a Google token instead of a key, plus embeddings. ```yaml providers: - id: vertex preset: vertex_ai base_url: https://aiplatform.googleapis.com/v1/projects/my-project/locations/global/publishers/google models: - id: chat targets: [{provider: vertex, model: gemini-3.5-flash-lite}] ``` - **Vertex URL:** - the `global` location uses `aiplatform.googleapis.com`; a regional one uses `-aiplatform.googleapis.com`; - a mismatched host and location are rejected in the configuration; - model availability varies by location. - **Vertex embeddings:** - up to 2048 texts, `dimensions` and `input_type` (`RETRIEVAL_QUERY`, `RETRIEVAL_DOCUMENT`...); - text above the model's limit is rejected, not silently truncated. - **Listing:** Vertex does not list models, so discovery responds 422. - **Request labels:** with `provider_request_labels`, generateContent calls to Vertex AI carry the caller's organization, team and key ID as labels for the Google Cloud bill; see [provider request labels](/docs/features/provider-request-labels/). ### Amazon Bedrock The `bedrock` protocol translates Chat Completions to the Converse API and gives access to all of Bedrock's chat models (Claude, Llama, Mistral, Nova and others). The target's model is the Bedrock ID, such as `anthropic.claude-haiku-4-5:0` or a `us.…` inference profile. - **Chat:** - stream, tools, `stop`, `max_tokens`, `temperature` and `top_p`; - images only as data URLs; - fields that Converse does not honor are rejected with 422. - **Reasoning:** `reasoning_effort` becomes *thinking* on Claude and the model's own control on gpt-oss; it is returned in `reasoning_content`. In a family without that control, the response is 422. - **Embeddings:** Titan Text (v1 and v2) and Cohere (v3 and v4), up to 512 texts per request, as `float` or `base64`. If part of the batch fails, the client receives the error, never an incomplete list. - **Guardrails:** Bedrock Guardrails plugs in as an external guardrail ([guardrails](/docs/features/guardrails/)). - **Messages, Responses and GenerateContent:** the same Converse adapter serves those routes through [protocol translation](/docs/features/protocol-translation/). - **Usage:** prompt-cache reads and writes (`cacheReadInputTokens`, `cacheWriteInputTokens`) count in `prompt_tokens`, with `cached_tokens` for the reads and `cache_creation_tokens` for the writes. - **Prompt caching:** on a Claude model, `cache_control` marks become `cachePoint` blocks, and `prompt_cache: {mode: auto}` places them when the client marks none; other models do not receive them ([prompt caching](/docs/features/prompt-caching/)). #### Custom endpoint By default a `bedrock` connection only accepts `https://bedrock-runtime..amazonaws.com`, so a configuration typo can never send an AWS credential elsewhere. To use a VPC interface endpoint, a corporate proxy or a test mock, state it explicitly in the YAML: ```yaml providers: - id: bedrock-private protocol: bedrock base_url: https://vpce-0abc123-xyz.bedrock-runtime.us-east-1.vpce.amazonaws.com custom_endpoint: true auth: {type: aws_sigv4, region: us-east-1} ``` - **YAML only.** The admin API and the console cannot set `custom_endpoint`; a console edit of this connection (a rotated key, for example) keeps it only while the `base_url` stays the one in the YAML. The console shows the flag read only. - **https is required.** `allow_insecure_http: true` accepts `http://` for local tests and mocks, and only on `localhost`, `127.0.0.1` or `host.docker.internal`. - **The signing region is required** with `aws_sigv4`, since a custom host carries none. A Bedrock API key (`api_key_env`) also works. - The URL may carry a path prefix, never a query, a fragment, user info, or a link-local or cloud metadata address. Redirects are never followed. - **SigV4 signs the custom host and the full path.** The endpoint must accept the request as signed: a VPC interface endpoint does, and so does a proxy that verifies or re-signs it. A proxy that forwards to AWS unchanged, or strips a path prefix, breaks the signature. For an egress proxy that only relays traffic, keep the official `base_url` and set the HTTP proxy instead (`network.proxy_url_env`). - Model discovery is not available on a custom endpoint, and the automatic price of the official host is not inherited. - **Know the risk:** the host receives the signed request, which AWS accepts for several minutes, plus the session token; with an API key, it receives the key. Point it only at a host you control ([security](/docs/security/security/#cloud-credentials-and-custom-endpoints)). ### Cohere v2 The `cohere_v2` preset uses Cohere's native API: - **chat** with stream, tools, `json_schema`, `reasoning_effort`, `documents` and citations; - **embeddings** in batches of 96; - **rerank.** The `cohere` preset uses the OpenAI-compatible endpoint. ### SageMaker The `sagemaker` protocol calls endpoints whose container speaks the OpenAI messages API (LMI, TGI, vLLM, llama.cpp). The target's model is the endpoint name, and authentication is IAM, with no static key. Chat only, with streaming. ```yaml providers: - id: sagemaker protocol: sagemaker base_url: https://runtime.sagemaker.us-east-1.amazonaws.com auth: {type: aws_sigv4, region: us-east-1, credential: auto} models: - id: chat-sagemaker targets: [{provider: sagemaker, model: meu-endpoint}] ``` ### OCI Generative AI The `oci` protocol calls Oracle Cloud's GENERIC models (Meta, OpenAI gpt-oss, Google, xAI), signing each request with an OCI CLI profile. The private key stays in the file. Chat only, without tools; OCI's Cohere models are rejected. ```yaml providers: - id: oci protocol: oci base_url: https://inference.generativeai.sa-saopaulo-1.oci.oraclecloud.com auth: {type: oci_api_key, profile: DEFAULT} models: - id: chat-oci targets: [{provider: oci, model: meta.llama-3.3-70b-instruct}] ``` ### Media: image, speech, transcription and video ElevenLabs (speech), Deepgram (transcription) and Stability, Replicate, Fal and Black Forest Labs (image) have adapters that translate the OpenAI routes (`/v1/audio/speech`, `/v1/audio/transcriptions`, `/v1/images/generations`). Whatever the provider does not accept is rejected before the call. Recraft already speaks the OpenAI format. The price per image, character or second comes from the catalog ([automatic pricing](/docs/features/automatic-pricing/)). Speech has its own page: how a clip is streamed, cut and charged, voice discovery, and the Amazon Polly, Azure AI Speech and Gemini text to speech targets, each behind its own flag ([speech](/docs/features/speech/)). Once Stability, Replicate, Fal or Black Forest Labs accepts an image (a task ID or an answer with the image), it is billed: if polling or reading the answer fails afterwards, the client gets an error and the request is **not** sent to the alias's next target. A refusal before acceptance (429, 5xx) still falls back. Replicate is asked to wait for the prediction (`Prefer: wait`) only as long as fits inside `network.response_header_timeout`, at most 60 seconds; with the default of 30 seconds the wait is 25. Runway generates video as an asynchronous job: the gateway records the intent, returns the job, and the client follows it at `/v1/video-jobs`. See [asynchronous video](/docs/features/quota-video/). ```yaml providers: - id: runway protocol: runway base_url: https://api.dev.runwayml.com/v1 api_version: "2024-11-06" api_key_env: RUNWAY_API_KEY models: - id: video-runway capabilities: [video] targets: [{provider: runway, model: gen4.5, paths: {video: /text_to_video}}] ``` ## Advanced features ### All of a provider's models (wildcards) An alias ending in `/*` exposes all of a provider's models without registering them one by one: ```yaml models: - id: local/* targets: [{provider: local, model: "*"}] ``` With this, `local/Qwen/Qwen2.5-7B-Instruct` goes to the provider with the model `Qwen/Qwen2.5-7B-Instruct`. - **Precedence:** an exact alias beats the wildcard, and among wildcards the longest prefix wins. - **In the allowlist:** of a key or a team, `local/*` allows the whole prefix, and `local/modelo-x` allows a single model. - **Pricing, fallback and quotas:** apply per concrete model. ### Discover a connection's models With `provider_model_discovery`, the console catalog lists what each connection serves, using the connection's own authentication: - OpenAI-compatible: `{base_url}/models`; - Anthropic and Gemini: each one's listing; - Azure: the deployments; - Bedrock: `ListFoundationModels`. The `/v1/models` of a key with a wildcard also lists the concrete models. ### Fixed headers `headers` sends non-secret headers on every call to the provider. Examples: - `anthropic-workspace-id`, for Anthropic user keys; - `OpenAI-Organization` and `OpenAI-Project`; - the routing of a corporate gateway in front of the provider. ```yaml providers: - id: anthropic preset: anthropic headers: anthropic-workspace-id: wrkspc_01ABC ``` Up to 16 headers. Credentials, tracing and AWS signing headers are rejected, and the values are visible to administrators: do not use them for secrets. ### Forwarded client headers By default the gateway sends a provider only the headers it builds itself: the connection's credential, the content type, the trace context and `X-Request-Id`, the fixed `headers` above, and two protocol headers on `anthropic` connections (`anthropic-version` from `api_version`, and the client's `anthropic-beta` when it is a well-formed list of feature names). Nothing else the client sends reaches the provider, with one exception: the [realtime](/docs/features/realtime/) WebSocket handshake relays the client's headers (feature headers such as `OpenAI-Beta` travel with the upgrade), minus hop-by-hop and WebSocket extension headers, `X-Forwarded-For`, and every credential, cookie, `X-Gateway-*`, `Proxy-*` and `x-amz-*` header, plus the connection's own `auth.header`. `forward_client_headers` names the client headers to copy, as the client sent them, to a given provider: ```yaml providers: - id: openai preset: openai forward_client_headers: [OpenAI-Beta, Idempotency-Key] - id: internal-router protocol: openai base_url: https://llm-router.example.com/v1 forward_client_headers: [x-tenant-route] ``` | Field | Default | Contract | | --- | --- | --- | | `providers[].forward_client_headers` | empty: nothing forwarded | Up to 16 distinct header names (letters, digits and `-`, 1–64 characters, case-insensitive), each copied with all its values when the client sent it; a header the client did not send is not added | Why an allowlist per provider: a header the client chooses can turn on provider features (`OpenAI-Beta`), select a tenant or route behind a corporate router, or attribute usage (`anthropic-workspace-id`). Each is a decision for one connection, not a default for every provider an alias may fall back to, so each provider lists only what it should receive. What is forwarded and when: - On every call to that provider made while serving the client's request on `/v1/...` or the native `/v1beta/...` routes: each attempt, retries and fallbacks included (a fallback to another provider sends that provider's own list), realtime connections, and the calls the gateway makes for that same request, such as a [provider guardrail](/docs/features/guardrails/) check, a semantic fallback or an automatic routing classifier, when their connection lists the header. Work the gateway runs on its own (model discovery, catalog refreshes, evaluations, batch items) carries no client headers. - A value above 8 KiB (all values of the header together) is not forwarded, and the forwarded headers of one request stay under 8 KiB together: past that, further listed headers are left out. Load balancers in front of providers commonly refuse larger header blocks, and their refusal would trigger retries and fallbacks. - Model discovery and catalog listings are shared by every caller, so they never carry a client's headers, even when a `/v1/models` request triggers the refresh. - The exact and semantic answer caches include the forwarded values in their keys, so an answer produced for one value is never served for another; requests without forwarded headers keep their keys. - The header is set before the connection's credential, so the credential always wins. Names that are refused, at load time in the YAML and with 422 in the provider API and console, because forwarding them would let a client replace the gateway's credential, corrupt the request the gateway rebuilt, or break tracing and signing: - credentials: `Authorization`, `Proxy-Authorization`, `x-api-key`, `api-key`, `x-goog-api-key`, `x-key`, `Ocp-Apim-Subscription-Key`, `X-Forwarded-Authorization`, and this connection's own `auth.header`; - cookies: `Cookie`, `Set-Cookie`; - hop-by-hop and proxy headers: `Connection`, `Keep-Alive`, `TE`, `Trailer`, `Transfer-Encoding`, `Upgrade`, `Expect`, `Host` and every `Proxy-*`; - framing and encoding: every `Content-*` and `Accept-Encoding` (the gateway rewrites the body and decodes compressed answers itself); - tracing: `traceparent`, `tracestate`, `baggage`, `X-Request-Id`, `X-Correlation-Id`, `X-Idempotency-Key`; - the gateway's own `X-Gateway-*` headers, `Sec-WebSocket-*`, every AWS signing header (`x-amz-*`) and `anthropic-version` (set from `api_version`); - a name listed twice, a name that is also a fixed header (keep one source), and `anthropic-beta` on an `anthropic` connection: the gateway forwards it there after validation on the Messages and token-count routes, and only there (a Chat Completions or Responses request translated to Anthropic does not carry it). Values are not inspected beyond size: whatever the client sends in a forwarded header reaches the provider, so list only headers the provider treats as preferences or routing, never as authority. Some allowed names select whose account or project is billed or attributed (`OpenAI-Organization`, `OpenAI-Project`, `anthropic-workspace-id`, `x-goog-user-project`): forwarding one lets every client of the alias choose it among those the connection's credential can reach. Prefer a fixed `headers` entry for those, and forward them only when every client may make that choice. Changes apply on the next request, with no restart; the console's provider form has a **Forwarded client headers** field (one name per line) and the provider API takes `forward_client_headers`. ### HTTP version `providers[].http_version` is `auto` (the default), `http1` or `http2`. With `auto` it is HTTP/2, except for the Google API, which goes over HTTP/1.1 because it responds faster that way under concurrency. ### Model server metrics For a self-hosted model server (vLLM, llama.cpp), `providers[].metrics_path` opts the connection into the scrape of the server's own Prometheus metrics, which then appear in the gateway's `/metrics` and OTLP export with the connection ID as the `provider` label. It needs the `provider_metrics_scrape` flag (off by default). `providers[].metrics_credential: true` also sends the connection's bearer secret with the scrape, for a server that protects its metrics with its key. The path is read on the host of `base_url` and never on another one. Setup, bounds and the series are in [Model server metrics](/docs/features/observability/#model-server-metrics). ### Model servers you host To put llama.cpp, MLX, Ollama or vLLM replicas behind the gateway with health checks, routing by replica load and optional supervision, declare a [local inference](/docs/features/local-inference/) pool instead of one connection per replica. The connections such a pool derives (`-r`) appear in this list and are changed through the pool, not here. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `POST /api/v1/admin/models/{id}/test` | Sends one minimal request through the gateway to the alias (a five-token chat or one embedding) and returns latency and result | ## See also - [Capabilities](/docs/features/capabilities/): what each alias can serve. - [Routing and resilience](/docs/features/feature-routing/): several providers on the same alias. - [Automatic pricing](/docs/features/automatic-pricing/): each model's price, without a manual table. ## Multiple credentials on one connection An optional [credential pool](/docs/features/provider-credentials/) names an explicit stable primary and statically authenticated alternatives. Separate runtime flags enable relative weights and response-signal cooldown only for qualified basic-text Chat execution; native/account-bound/unclassified paths retain primary. Pool metadata and write-only per-ID secrets use the existing provider API/console CAS and encrypted PostgreSQL persistence. Legacy single-secret providers remain unchanged. Primary changes are account-identity changes, not automatic resource migration; configured presence is not health. # Local inference **Last updated:** 2026-11-24T13:28:29-03:00 (UTC-3) Local inference puts model servers you host behind the gateway as **pools of replicas**. You say where the replicas are, or let the gateway start them, and it does the rest: it health-checks every replica, sends traffic only to the ones that are ready, spreads requests by how busy each replica is, restarts a replica that dies and tells you why it died. | You run | Backend | Page | | --- | --- | --- | | A Mac with Apple Silicon | llama.cpp with Metal | [llama.cpp](/docs/features/local-inference-llama-cpp/) | | A Mac with Apple Silicon | MLX | [MLX](/docs/features/local-inference-mlx/) | | A Mac with Apple Silicon | Ollama | [Ollama](/docs/features/local-inference-ollama/) | | A host or a cluster with NVIDIA GPUs | vLLM in Docker or Kubernetes | [vLLM](/docs/features/local-inference-vllm/) | | Any host without a GPU | llama.cpp, Ollama or vLLM on the CPU | the same pages | On a Mac the model servers run as native processes, not containers: Docker on macOS does not see the Apple GPU. Three rules hold everywhere: - **The weights are yours.** You download or build the model and put it in a directory you name. The gateway never downloads weights and never installs a model server. - **A replica is a destination of its own.** Each one becomes a provider connection named `-r`, so the router, the [circuit breaker](/docs/features/resilience/), the request log and the metrics treat it like any other destination. - **Everything is off until you turn it on.** The feature has its own flag, and each GPU capability has one more. ## Turn it on 1. Set `features.local_inference: true`. This alone is enough for replicas on the CPU and for replicas you run yourself. 2. Turn on the GPU flags you need (see [Flags](#flags)). 3. To let the gateway start model servers, set `local_inference.supervise: true` and the path of each executable under `local_inference.runtimes` in the gateway YAML, then restart. Skip this step if you only register servers that already run. 4. Declare a pool under `local_inference.pools`, in the YAML or on the console's **Local inference** screen. 5. Call the pool's alias like any model. The smallest pool registers two servers that already run and gives them one alias: ```yaml features: local_inference: true local_inference: pools: - id: qwen backend: vllm model: qwen05 alias: local-qwen endpoints: - url: http://10.0.0.5:8000/v1 - url: http://10.0.0.6:8000/v1 ``` ```bash curl -s http://localhost:8080/v1/chat/completions \ -H "Authorization: Bearer $GATEWAY_KEY" -H "Content-Type: application/json" \ -d '{"model":"local-qwen","messages":[{"role":"user","content":"Say hi"}]}' ``` A key may call the alias when the alias is in its allowed models, like any other model. ## Flags Every flag is off by default and is an operator control, changed in the YAML or under **Settings & sources** without a restart. | Flag | What it allows | Needs | | --- | --- | --- | | `local_inference` | Pools, health checks, routing by replica load, supervision. With only this flag on, every replica runs on the CPU | — | | `local_inference_gpu` | A pool may use a GPU at all (`gpu.mode` other than `off`) | `local_inference` | | `local_inference_metal` | Pools with `gpu.mode: metal`: llama.cpp with Metal, MLX and Ollama on Apple Silicon | `local_inference_gpu` | | `local_inference_nvidia` | Pools with `gpu.mode: nvidia`: vLLM, or llama.cpp and Ollama built for CUDA | `local_inference_gpu` | | `local_inference_mig` | One replica bound to each NVIDIA MIG slice by its UUID | `local_inference_nvidia` | A pool whose flags are not all on does not run: its replicas show **Blocked** with the missing flag named, and receive no traffic. Turning a flag off stops the replicas that need it. A pool with `gpu.mode: off` (the default) needs only `local_inference`: llama.cpp is started with no layers offloaded, a vLLM container gets no GPU, and Ollama is started with its GPU offload disabled. Two more flags matter. `routing_strategies` (on in the shipped configuration) is what makes `least_busy` order the replicas; without it the alias keeps its declared order. `provider_metrics_scrape` shows each replica's own queue next to the gateway's numbers (see [Metrics](#metrics-and-events)). ## Two modes | Mode | Who runs the model server | What the gateway does | Use it when | | --- | --- | --- | --- | | `register` (default) | You: a Kubernetes Deployment, systemd, another host | Health-checks each endpoint, routes by load, takes a replica out of routing when it stops answering | The servers run in Kubernetes or on other hosts, or more than one gateway replica serves them | | `supervise` | The gateway process | All of the above, plus: starts each replica, restarts it with backoff when it dies or hangs, stops it on request and when the gateway shuts down | One gateway process on the host that has the GPU: a Mac, a single GPU server | Supervision belongs to one gateway process on one host. Every gateway replica runs its own supervisor, and two of them on the same host would compete for the same ports, so run a single gateway process there. With several gateway replicas (Kubernetes), use `register`. ## What the gateway may start These settings decide what a gateway process is allowed to execute. They are read from the gateway YAML at start, need a restart to change and **cannot be set through the API or the console**, which only show them. A pool written through the API can only combine what they admit. | Setting | Default | What it is | | --- | --- | --- | | `local_inference.supervise` | `false` | `true` lets this process start model servers. With `false`, a pool with `mode: supervise` is refused | | `local_inference.runtimes.llama_cpp` | empty | Absolute path of `llama-server`. Empty: the backend cannot be supervised on this host | | `local_inference.runtimes.mlx` | empty | Absolute path of `mlx_lm.server` | | `local_inference.runtimes.ollama` | empty | Absolute path of `ollama` | | `local_inference.runtimes.container` | empty | Absolute path of the container runtime (`docker`) that runs the vLLM backend | | `local_inference.runtimes.nvidia_smi` | empty | Absolute path of `nvidia-smi`, used to find the GPUs and MIG slices when a pool lists no `gpu.devices` | | `local_inference.model_dirs` | empty | Up to 16 directories weights may be read from. A pool's `weights` must be inside one of them, also after symbolic links are resolved | | `local_inference.container_images` | empty | Up to 16 images a vLLM pool may run, written exactly as the pool names them. Pin a digest | The gateway builds every argument itself from the typed fields below. It runs no shell, starts each model server with a minimal environment (none of the gateway's own variables, so none of its secrets) and binds every supervised replica to `127.0.0.1`: the gateway is the only way in. ## Pool settings `local_inference.pools` takes up to 16 pools, 16 replicas per pool and 32 replicas in all. | Setting | Default | Bounds | What it is | | --- | --- | --- | --- | | `local_inference.pools[].id` | required | 1–40 lowercase letters, digits, hyphens | Names the pool and its replicas: replica 2 of `qwen` is the connection `qwen-r2` | | `local_inference.pools[].backend` | required | `llama_cpp`, `mlx`, `ollama`, `vllm` | The model server | | `local_inference.pools[].mode` | `register` | `register`, `supervise` | Who runs the servers (see [Two modes](#two-modes)) | | `local_inference.pools[].model` | required | 1–128 characters | The model name the replicas serve; it is what the gateway sends upstream | | `local_inference.pools[].alias` | none | 1–128 characters, one pool per alias | The gateway declares a chat model with this ID over every replica. Leave it empty, or declare a model with the same ID in the YAML, to write the targets by hand. The generated alias follows the pool and is not edited in the model catalog | | `local_inference.pools[].routing_strategy` | `least_busy`; `ordered` with `gpu.share_device` | `least_busy`, `ordered` | How the generated alias orders the replicas (see [Routing](#routing)) | | `local_inference.pools[].disabled` | `false` | | Keeps the pool in the configuration and runs and routes nothing | | `local_inference.pools[].scrape_metrics` | `true` | | Declares `/metrics` on each llama.cpp or vLLM replica for the [model server metrics scrape](/docs/features/observability/#model-server-metrics) | Supervised pools (`mode: supervise`): | Setting | Default | Bounds | What it is | | --- | --- | --- | --- | | `local_inference.pools[].weights` | required | inside `model_dirs` | Where you put the model: a `.gguf` file (llama.cpp), a model directory (MLX, vLLM) or the model store directory (Ollama) | | `local_inference.pools[].replicas` | `1` | 1–16 | How many servers run | | `local_inference.pools[].port_base` | required | 1024–65535 | The loopback port of replica 1; replica n listens on `port_base + n - 1`. Ports may not overlap between pools | | `local_inference.pools[].slots` | the server's default | 1–256 | Requests one replica serves at the same time | | `local_inference.pools[].context_tokens` | the server's default | 256–1048576 | The context window of one request. Not for MLX, which takes the model's own | | `local_inference.pools[].image` | required for vLLM | one of `container_images` | The container image of a vLLM pool | | `local_inference.pools[].stop_grace` | `10s` | 1s–5m | How long a stop waits for requests in flight, and then for the process to end, before it is killed | | `local_inference.pools[].extra_args` | none | 32 arguments of up to 256 characters | Appended to the model server's own arguments. **YAML only.** They may not set the model, the address, the credential or a download source, which the gateway owns | GPU use (`local_inference.pools[].gpu`): | Setting | Default | Bounds | What it is | | --- | --- | --- | --- | | `local_inference.pools[].gpu.mode` | `off` | `off`, `metal`, `nvidia` | `off` keeps the pool on the CPU. The others need their [flags](#flags) | | `local_inference.pools[].gpu.devices` | discovered | up to 16 | With `nvidia`: one replica is bound to each entry, a GPU UUID, a MIG UUID or a GPU index. Empty: the gateway asks `nvidia-smi` and takes the MIG slices of a card in MIG mode, the whole card otherwise. Discovery hands the whole host to one pool: to split a host between pools, name the devices in every one of them | | `local_inference.pools[].gpu.share_device` | `false` | | Allows more replicas than devices: several replicas on one GPU without MIG. Accepted with a warning (see [One replica per GPU](#one-replica-per-gpu-or-mig-slice)) | | `local_inference.pools[].gpu.memory_fraction` | `0.85` of a GPU, `0.70` of a small MIG slice | 0.05–0.95 | vLLM only: the share of the device's memory one replica may take (see [Memory headroom](/docs/features/local-inference-vllm/#memory-headroom)). With `share_device`, the replicas on one device must fit in it together | Registered pools (`mode: register`): | Setting | Default | Bounds | What it is | | --- | --- | --- | --- | | `local_inference.pools[].endpoints[].url` | required | 1–16 endpoints | The replica's OpenAI-compatible base URL, such as `http://10.0.0.5:8000/v1`. No credentials, query or fragment | | `local_inference.pools[].endpoints[].device` | none | 1–96 characters | A label for the GPU or MIG slice behind the replica, shown on the screen. A label starting with `MIG-` needs `local_inference_mig` | | `local_inference.pools[].api_key_env` | none | an environment variable name | The variable holding the bearer key the replicas ask for. Empty sends no credential. **YAML only**, like `extra_args`: it sends a variable of the gateway's environment to the endpoints | Health and restart: | Setting | Default | Bounds | What it is | | --- | --- | --- | --- | | `local_inference.pools[].health.path` | `/health`; `/api/version` for Ollama | an absolute path | Probed on the replica's origin. The model list (`/models` under the base URL) is probed too: a replica is ready when both answer 200 | | `local_inference.pools[].health.interval` | `5s` | 1s–5m | Time between probes | | `local_inference.pools[].health.ready_timeout` | `5m` | 5s–1h | How long a started replica may take to pass its first probe. Past it, the replica is ended and restarted. Raise it for a large model | | `local_inference.pools[].health.unhealthy_after` | `3` | 1–20 | Failed probes in a row that take a ready replica out of routing. Twice as many end and restart a supervised replica | | `local_inference.pools[].restart.backoff` | `2s` | 500ms–1m | Wait before the first restart. It doubles on every failure in a row, up to one minute | | `local_inference.pools[].restart.max_per_hour` | `6` | 1–60 | Restarts in one hour after which the replica is left **Failed** until you start it | ## Routing The generated alias uses `least_busy`: each request goes to the ready replica with the fewest requests in flight. That is the right default for replicas that each have their own GPU or MIG slice, and for CPU replicas. Measured on seven MIG slices of one NVIDIA A100, `least_busy` served 9% and 10% more tokens per second than the declared order at 6 and 32 concurrent streams and 125% more at 224, and was never worse. A replica that is not ready is skipped before anything is sent: one still loading its model, restarting, stopped or blocked never receives a request. When no replica of the alias is ready, the answer is `503` with the code `replica_not_ready`. To add a cloud fallback, or any other [routing policy](/docs/features/routing-and-admission/), declare the model yourself with the same ID as `alias` and name the replicas as targets: ```yaml models: - id: local-qwen routing_strategy: least_busy targets: - {provider: qwen-r1, model: qwen05} - {provider: qwen-r2, model: qwen05} ``` ### One replica per GPU or MIG slice Give each replica its own GPU or its own MIG slice. That is the rule the gateway applies: a supervised pool with more replicas than devices is refused, unless you set `gpu.share_device: true`. Sharing is allowed, with a warning on the screen and in the log, because the gain depends on the load: - **On NVIDIA without MIG**, two vLLM replicas on one card take turns on it. Measured on an A100, they served 51% fewer tokens per second than one replica at 6 concurrent streams and 37% fewer at 32, and twice as many only at 224 streams, once a single server was saturated. So the generated alias of a shared pool defaults to `ordered`, which keeps traffic on the first replica until it fails. Prefer MIG where the card has it: the same two replicas on two slices lost nothing. - **On Apple Silicon** there is one GPU, so more than one replica always shares it. Measured on an M4 Pro, three llama.cpp replicas of two slots each served 536 tokens per second at 6 concurrent streams with a first token in 31 ms, against 444 tokens per second and 1.4 s for one replica: the replicas buy slots, so nothing queues, more than raw throughput. Set `routing_strategy: least_busy` on such a pool. ## What a supervised replica goes through | State | Meaning | Receives traffic | | --- | --- | --- | | **Starting** | The process runs and has not passed its health check yet (the model is loading) | no | | **Ready** | Both probes answer 200 | yes | | **Unhealthy** | A ready replica failed `unhealthy_after` probes in a row | no | | **Restarting** | The process ended, or was ended for not answering; the next start waits for the backoff | no | | **Failed** | Restarted `restart.max_per_hour` times in one hour. It stays down until you start it | no | | **Blocked** | It may not or cannot start: a flag is off, no device is left, the port is taken, the weights are missing | no | | **Stopping**, **Stopped** | An operator stopped it | no | Every state comes with its reason, the way the process last ended (exit status or signal) and the last line it wrote, so a dead replica explains itself. On the same M4 Pro a replica killed under load was running again and ready 3.2 seconds later; no client saw an HTTP error, because requests that had not started were moved to another replica. Three things to know: - **A restarted replica also waits for its circuit.** If the dying replica failed enough requests to open its [circuit](/docs/features/resilience/), it takes traffic again when its health check passes and the circuit's open time (30 seconds by default) has run out. - **A stop drains.** It takes the replica out of routing, waits up to `stop_grace` for the requests in flight and only then ends the process. - **A port that is already taken is never fought over.** If another process listens on a replica's port, such as a model server left by a gateway that was killed, the replica shows **Blocked** with `port_in_use`. End that process and the replica starts by itself. When the gateway shuts down it ends every model server it started. ## The Local inference screen **Gateway → Local inference** shows the five flags, what this host may start, and one card per pool with a row per replica: state and reason, health (ready since, last check, circuit), GPU or slice, load (requests in flight from this gateway, plus the replica's own running and waiting requests when the metrics scrape is on) and restarts (total, in the last hour, last exit and last output line). The screen refreshes every five seconds. What you can do depends on your permissions: | Permission | Built-in roles | Allows | | --- | --- | --- | | `local_inference:read` | admin, viewer, operator | Seeing the screen and `GET /api/v1/admin/local-inference` | | `local_inference:operate` | admin, operator | **Start**, **Stop** and **Restart** on a replica | | `local_inference:manage` | admin | **Edit pools**, **Save pools** and **Revert to YAML** | A [custom role](/docs/features/custom-roles/) based on viewer or operator may keep or drop `local_inference:read`. Team roles never see the screen: pools are the operator's infrastructure, shared by every organization. Replica state belongs to the gateway process that answers. With several gateway replicas, each one probes on its own and the screen shows the one your request reached. An action applies to that process and is not stored: after a gateway restart every replica starts again. ## Admin API | Route | Permission | What it does | | --- | --- | --- | | `GET /api/v1/admin/local-inference` | `local_inference:read` | The flags, what the host may start (without the executable paths), the limits and every pool with the state of its replicas | | `PUT /api/v1/admin/local-inference` | `local_inference:manage` | Stores `{"version": n, "pools": [...]}` as the pool list, replacing the YAML's on every gateway replica. Validated like the YAML; `extra_args` and `api_key_env` are accepted only unchanged, for a pool the YAML declares with the same backend, mode, weights, image and endpoints; `409` on a stale version, `422` with the pool and field named | | `DELETE /api/v1/admin/local-inference` | `local_inference:manage` | Removes the stored list: the YAML's pools are in force again | | `POST /api/v1/admin/local-inference/pools/{id}/replicas/{replica}/{action}` | `local_inference:operate` | `action` is `start`, `stop` or `restart`; `replica` is the number from 1. Answers `202`; read the state from the `GET`. `restart` of a registered replica answers `409` | ```bash curl -s -X POST -H "Authorization: Bearer $GATEWAY_ADMIN_TOKEN" -H "Content-Type: application/json" -d '{}' \ http://localhost:8080/api/v1/admin/local-inference/pools/qwen/replicas/2/stop ``` ```json {"action":"stop","pool":"qwen","replica":"qwen-r2","scope":"process"} ``` A saved pool list is a versioned, audited configuration change (`local_inference.set`, `local_inference.revert`). The connections `-r` cannot be edited or deleted through the provider routes, nor the generated alias through the model routes; change the pool. Three cases to know: - **Editing a pool.** A change to how a replica is started (backend, model, weights, image, ports, slots, context, GPU settings, replica count) replaces the replica: the old one finishes its requests in flight, up to `stop_grace`, before the new one starts, and a replica you had stopped stays stopped. Any other change (the alias, the routing strategy, health and restart settings) applies in place and leaves the process alone. - **A stored list the YAML stops admitting.** If you later turn `supervise` off, remove a runtime, an image or a model directory, or change the `extra_args` a stored pool repeats, the stored list is set aside: nothing of it runs, the YAML's pools are in force, the `GET` answers the reason in `override_ignored` and the log has one `local_inference_override_ignored` line. Save a valid list or revert. - **With `gitops.source_of_truth: file`** and pools declared in the YAML, the file wins: the `PUT` and the `DELETE` answer `409` `source_of_truth_file` and a stored list is set aside. ## Metrics and events With `metrics_endpoint` on, `/metrics` (and [OTLP metrics](/docs/features/observability/#otlp-metrics)) carries one series per replica, labelled `pool`, `replica` and `backend`: | Series | Meaning | | --- | --- | | `gateway_local_inference_replica_ready` | 1 while the replica receives traffic | | `gateway_local_inference_replica_state` | 1 on the state it is in (label `state`) | | `gateway_local_inference_replica_in_flight` | Requests this gateway process has in flight on it | | `gateway_local_inference_replica_restarts_total` | Times the gateway restarted it | The gateway's usual series (`gateway_upstream_attempts_total`, `gateway_provider_errors_total`, `gateway_circuit_breaker_state` and the rest) carry each replica as `provider="-r"`. The model server's **own** metrics come through the [model server metrics scrape](/docs/features/observability/#model-server-metrics): turn on `provider_metrics_scrape` and every llama.cpp and vLLM replica is scraped at `/metrics` with no further setting. MLX and Ollama publish no Prometheus metrics. Every change of a replica's state is a structured log line named `local_inference_replica`, with `event` (`replica_starting`, `replica_ready`, `replica_unhealthy`, `replica_backoff`, `replica_failed`, `replica_blocked`, `replica_stopping`, `replica_stopped`), `pool`, `replica`, `backend`, `mode`, `state`, `reason`, `device`, `pid`, `restarts_total` and, for a replica that ended, `last_exit`. An operator action is `local_inference_replica_action` with the request's correlation IDs, and a pool warning is `local_inference_pool_warning`. With `otlp_logs` on they reach your collector like every other line. Nothing a model server wrote is logged. ## Limits - Supervision is for one gateway process per host. Use `register` with several gateway replicas. - Replica state, and a stop or start, live in the memory of one gateway process. - The gateway reads the GPU layout; it does not create MIG slices or switch a card to MIG mode. - Replicas of one pool are treated as equal. Do not mix slices of different sizes in one pool. - `least_busy` counts the gateway's own requests in flight. Traffic that reaches a replica without passing through the gateway is not counted. - Weights are checked for being where you said. Their content is not verified. # Local inference with llama.cpp **Last updated:** 2026-11-24T13:10:14-03:00 (UTC-3) llama.cpp serves GGUF models through `llama-server`. On a Mac with Apple Silicon it uses the GPU through Metal; anywhere it also runs on the CPU alone. This page sets up a [local inference](/docs/features/local-inference/) pool the gateway starts and supervises. The commands and numbers were run on a Mac Mini M4 Pro (24 GB, macOS 26) with llama.cpp 1.0.0 and `Qwen2.5-0.5B-Instruct` in the Q4_K_M quantization. ## 1. Install the server and get the weights Run llama.cpp natively. Docker on macOS does not see the Apple GPU. ```bash brew install llama.cpp which llama-server # /opt/homebrew/bin/llama-server mkdir -p /opt/models curl -fL -o /opt/models/qwen2.5-0.5b-instruct-q4_k_m.gguf \ https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/main/qwen2.5-0.5b-instruct-q4_k_m.gguf ``` The gateway never downloads weights: put the `.gguf` file where you want it and name that directory in `model_dirs`. ## 2. Configure the gateway ```yaml features: local_inference: true local_inference_gpu: true # leave these two off to serve on the CPU local_inference_metal: true local_inference: supervise: true runtimes: llama_cpp: /opt/homebrew/bin/llama-server model_dirs: [/opt/models] pools: - id: qwen-metal backend: llama_cpp mode: supervise model: qwen05 alias: local-qwen weights: /opt/models/qwen2.5-0.5b-instruct-q4_k_m.gguf replicas: 3 slots: 2 context_tokens: 2048 port_base: 14201 gpu: {mode: metal, share_device: true} routing_strategy: least_busy ``` Add `local-qwen` to the allowed models of the keys that may call it, then start the gateway. `supervise` and `runtimes` are read at start. What the gateway runs for replica 1, so you can reproduce it by hand: ```bash /opt/homebrew/bin/llama-server -m /opt/models/qwen2.5-0.5b-instruct-q4_k_m.gguf \ --host 127.0.0.1 --port 14201 --alias qwen05 -ngl 99 --parallel 2 -c 4096 --metrics ``` - `-ngl 99` offloads every layer to the GPU. With `gpu.mode: off`, or with the GPU flags off, the gateway passes `-ngl 0`. - `-c` is `context_tokens` times `slots`: llama.cpp divides its context among the slots, and `context_tokens` is the window of one request. - `--metrics` is added unless `scrape_metrics` is `false`. - An NVIDIA build of llama.cpp uses `gpu.mode: nvidia`; each replica gets its device in `CUDA_VISIBLE_DEVICES`. ## 3. Check it ```bash curl -s -H "Authorization: Bearer $GATEWAY_ADMIN_TOKEN" http://localhost:8080/api/v1/admin/local-inference curl -s http://localhost:8080/v1/chat/completions \ -H "Authorization: Bearer $GATEWAY_KEY" -H "Content-Type: application/json" \ -d '{"model":"local-qwen","stream":true,"max_tokens":160,"messages":[{"role":"user","content":"Explain a hash map."}]}' ``` Each replica goes from `starting` to `ready` once the model is loaded: 7 to 8 seconds on the first start here, about 1 second on a restart. **Check that the GPU is really in use.** A model server that fell back to the CPU still answers. Compare a GPU pool with a CPU pool (`gpu.mode: off`) of the same model, and watch the GPU while they decode: ```bash ioreg -r -d 1 -w 0 -c IOAccelerator | grep -o '"Device Utilization %"=[0-9]*' ``` ## What to expect Streamed chat, 160 output tokens, measured through the gateway unless the row says direct: | Setup | Concurrent streams | First token (median) | Decode per stream | Total tokens/s | GPU utilization | | --- | --- | --- | --- | --- | --- | | One Metal replica, direct | 1 | 5 ms | 247 tok/s | 225 | 69% average, 81% peak | | One CPU replica (8 threads), direct | 1 | 7 ms | 171 tok/s | 159 | 8% average | | Three Metal replicas of two slots, `least_busy` | 1 | 17 ms | 263 tok/s | 236 | 76% | | Three Metal replicas of two slots, `least_busy` | 6 | 31 ms | 103 tok/s | 536 | 94% | | Three Metal replicas of two slots, `least_busy` | 12 | 1,552 ms | 103 tok/s | 602 | 99% | | One Metal replica of two slots, direct | 6 | 1,440 ms | 223 tok/s | 444 | 82% | | One CPU replica of two slots | 2 | 21 ms | 118 tok/s | 210 | 3% | How to read it: - **Size the slots to your concurrency.** Past `replicas × slots` concurrent streams, requests queue inside the model server and the first token waits (1.5 s at 12 streams on 6 slots). - **Replicas on one Mac buy slots, not much throughput.** The GPU is one shared budget: three replicas gave 536 tokens per second against 444 for one, and no queueing up to six streams. That is why this pool needs `share_device: true` and why the gateway warns about it. - **The GPU gain is modest on Apple Silicon** (247 against 171 tokens per second here): decoding is bound by memory bandwidth, which the CPU and the GPU share. Give the CPU pool enough threads before comparing (`extra_args: ["-t", "8"]` in the YAML). ## When a replica dies A replica killed with `kill -9` in the middle of 36 requests at 6 concurrent streams: every request answered HTTP 200, one that had not started moved to another replica, two streams already running were cut (reported to the client as `stream_interrupted` and counted in `gateway_provider_errors_total`). The gateway restarted the replica after its 2 second backoff and it was ready 3.2 seconds after the kill. An operator **Stop** under the same load drained in 0.9 seconds and cut nothing. # Local inference with MLX **Last updated:** 2026-11-24T13:28:29-03:00 (UTC-3) MLX is Apple's array framework for Apple Silicon; `mlx_lm.server` serves MLX models with an OpenAI-compatible API. It always runs on the Apple GPU, so an MLX pool needs `gpu.mode: metal` and the flags `local_inference_gpu` and `local_inference_metal`. This page sets up a [local inference](/docs/features/local-inference/) pool the gateway starts and supervises. The commands and numbers were run on a Mac Mini M4 Pro with mlx-lm 0.32.2 and `Qwen2.5-0.5B-Instruct` in 4 bits. ## 1. Install the server and get the weights A virtual environment keeps MLX out of the system Python: ```bash uv venv --python 3.12 /opt/mlx/venv uv pip install --python /opt/mlx/venv/bin/python "mlx-lm==0.32.2" /opt/mlx/venv/bin/python -c "from huggingface_hub import snapshot_download; snapshot_download('mlx-community/Qwen2.5-0.5B-Instruct-4bit', local_dir='/opt/models/qwen05-mlx')" ``` The weights are a directory (`config.json`, `model.safetensors`, the tokenizer files). The gateway never downloads them. ## 2. Configure the gateway ```yaml features: local_inference: true local_inference_gpu: true local_inference_metal: true local_inference: supervise: true runtimes: mlx: /opt/mlx/venv/bin/mlx_lm.server model_dirs: [/opt/models] pools: - id: qwen-mlx backend: mlx mode: supervise model: qwen05 alias: local-qwen-mlx weights: /opt/models/qwen05-mlx slots: 2 port_base: 14221 gpu: {mode: metal} ``` What the gateway runs for the replica: ```bash HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 /opt/mlx/venv/bin/mlx_lm.server \ --model /opt/models/qwen05-mlx --host 127.0.0.1 --port 14221 \ --decode-concurrency 2 --prompt-concurrency 2 ``` Three things are particular to this backend: - **The server is started offline.** `mlx_lm.server` treats a model name it does not know as a repository to fetch. With the offline variables it answers 404 instead, so nothing is ever downloaded. - **The gateway addresses the replica as `default_model`**, the one name the server answers for the weights it was started with. `model` in the pool is your label; clients call the alias. - **`context_tokens` is refused**: the server takes the model's own window. `slots` sets its decode and prompt concurrency. The server has no Prometheus metrics, so `scrape_metrics` does nothing here. Its health check is `/health`. ## 3. Check it ```bash curl -s http://localhost:8080/v1/chat/completions \ -H "Authorization: Bearer $GATEWAY_KEY" -H "Content-Type: application/json" \ -d '{"model":"local-qwen-mlx","max_tokens":32,"messages":[{"role":"user","content":"Say hi"}]}' ``` A request sent while the replica is still loading the model answers `503` `replica_not_ready`; the replica takes traffic once `/health` answers. ## What to expect Streamed chat, 160 output tokens, through the gateway: | Concurrent streams | First token (median) | Decode per stream | Total tokens/s | GPU utilization | | --- | --- | --- | --- | --- | | 1 | 18 ms | 322 tok/s | 259 | 67% average, 79% peak | | 2 | 457 ms | 301 tok/s | 305 | 77% | One stream decodes faster than on llama.cpp with the same model here (322 against 263 tokens per second). Two streams at once mostly wait for each other on this server version: for many concurrent streams on a Mac, a llama.cpp pool with slots served more (536 tokens per second at 6 streams). # Local inference with Ollama **Last updated:** 2026-11-24T13:41:15-03:00 (UTC-3) Ollama serves models from its own model store with an OpenAI-compatible API under `/v1`. This page sets up a [local inference](/docs/features/local-inference/) pool the gateway starts and supervises. The commands and numbers were run on a Mac Mini M4 Pro with Ollama 0.40.18 and `Qwen2.5-0.5B-Instruct` (GGUF, Q4_K_M). ## 1. Install the server and build the model store The standalone archive needs no installer: ```bash mkdir -p /opt/ollama /opt/models/ollama-store curl -fsSL https://github.com/ollama/ollama/releases/download/v0.40.18/ollama-darwin.tgz | tar -xz -C /opt/ollama ``` The gateway never pulls a model. Put your model in the store yourself, here from a GGUF file you already have: ```bash OLLAMA_HOST=127.0.0.1:11500 OLLAMA_MODELS=/opt/models/ollama-store /opt/ollama/ollama serve & printf 'FROM /opt/models/qwen2.5-0.5b-instruct-q4_k_m.gguf\n' > /tmp/Modelfile OLLAMA_HOST=127.0.0.1:11500 /opt/ollama/ollama create qwen05 -f /tmp/Modelfile kill %1 ``` ## 2. Configure the gateway ```yaml features: local_inference: true local_inference_gpu: true # leave these two off, and gpu.mode off, to serve on the CPU local_inference_metal: true local_inference: supervise: true runtimes: ollama: /opt/ollama/ollama model_dirs: [/opt/models] pools: - id: qwen-ollama backend: ollama mode: supervise model: qwen05 # the name you gave the model in the store alias: local-qwen-ollama weights: /opt/models/ollama-store slots: 2 context_tokens: 4096 port_base: 14231 gpu: {mode: metal} ``` `weights` is the model store directory. What the gateway runs for the replica: ```bash OLLAMA_HOST=127.0.0.1:14231 OLLAMA_MODELS=/opt/models/ollama-store OLLAMA_NOPRUNE=1 OLLAMA_NO_CLOUD=1 \ OLLAMA_NUM_PARALLEL=2 OLLAMA_CONTEXT_LENGTH=4096 /opt/ollama/ollama serve ``` - `slots` becomes `OLLAMA_NUM_PARALLEL` and `context_tokens` becomes `OLLAMA_CONTEXT_LENGTH`. - The store is never pruned, and the cloud models are off: the replica serves what is in the store and nothing else. A model that is not there answers 404. - Ollama keeps a client key and a small cache under `~/.ollama` of the user the gateway runs as. - The health check is `/api/version`. Ollama publishes no Prometheus metrics, so `scrape_metrics` does nothing here. ## CPU only Ollama decides GPU use by itself. With `gpu.mode: off` the gateway adds `LLAMA_ARG_N_GPU_LAYERS=0` (and `OLLAMA_LLM_LIBRARY=cpu` and `CUDA_VISIBLE_DEVICES=-1` for other versions and hosts). Verify it on your version, because the setting that works has changed between releases: ```bash OLLAMA_HOST=127.0.0.1:14231 /opt/ollama/ollama ps # NAME ID SIZE PROCESSOR CONTEXT # qwen05:latest 9806541f10f4 406 MB 100% CPU 4096 ``` On 0.40.18, `OLLAMA_LLM_LIBRARY=cpu` alone left the model at `100% GPU`; `LLAMA_ARG_N_GPU_LAYERS=0` moved it to `100% CPU`. ## What to expect Streamed chat, 160 output tokens, through the gateway: | Setup | Concurrent streams | First token (median) | Decode per stream | Total tokens/s | GPU utilization | | --- | --- | --- | --- | --- | --- | | Metal, two slots | 1 | 16 ms | 269 tok/s | 246 | 58% average, 76% peak | | Metal, two slots | 2 | 16 ms | 222 tok/s | 405 | 83% | | CPU, two slots | 1 | 13 ms | 197 tok/s | 181 | 3% average | The first request after a start loads the model and takes longer (about 0.3 s to the first token here). Ollama unloads an idle model after a few minutes and loads it again on the next request. # Local inference with vLLM on NVIDIA **Last updated:** 2026-11-24T13:10:14-03:00 (UTC-3) vLLM serves models on NVIDIA GPUs from the image `vllm/vllm-openai`. This page covers the three ways to put it behind a [local inference](/docs/features/local-inference/) pool: replicas the gateway starts with Docker, replicas you start yourself and register, and replicas in Kubernetes. The numbers were measured with vLLM 0.27.1 and `Qwen2.5-0.5B-Instruct` (bf16) on an NVIDIA L4 and an A100 40GB, with replicas started by the `docker run` command of this page and routed by the gateway. A vLLM pool with a GPU needs the flags `local_inference`, `local_inference_gpu` and `local_inference_nvidia`, plus `local_inference_mig` for MIG slices. ## The rule: one replica per GPU or MIG slice One vLLM process batches every request it holds on one device. Give each replica a device of its own: | Layout on one A100 | 6 streams | 32 streams | 224 streams | | --- | --- | --- | --- | | One replica, whole card | 2,084 tok/s | 7,969 | 11,870 | | Two replicas sharing the card (no MIG) | 1,026 | 5,059 | 23,136 | | Two replicas on two `3g.20gb` MIG slices | 1,929 | 8,150 | 24,653 | | Seven replicas on seven `1g.5gb` MIG slices | 805 | 3,823 | 16,470 | - Two replicas sharing a card without MIG take turns on it and halve the throughput until one process saturates. The gateway accepts that layout only with `gpu.share_device: true`, warns about it and defaults its alias to `ordered`. - With MIG the slices are isolated and `least_busy` is right at every load. - The slice size sets the speed of one stream (430 tokens per second on the whole card, 371 on `3g.20gb`, 143 on `1g.5gb`). Use the fewest, largest slices your concurrency needs. The gateway reads the layout that exists. It does not switch a card to MIG mode or create slices: ```bash sudo nvidia-smi -i 0 -mig 1 && sudo systemctl reboot # MIG mode needs a reboot or a GPU reset sudo nvidia-smi mig -cgi 3g.20gb,3g.20gb -C # two slices nvidia-smi -L # the UUIDs: MIG-... ``` ## Replicas the gateway starts with Docker Put the model on the host (the gateway never downloads it), then: ```yaml features: local_inference: true local_inference_gpu: true local_inference_nvidia: true local_inference_mig: true local_inference: supervise: true runtimes: container: /usr/bin/docker nvidia_smi: /usr/bin/nvidia-smi model_dirs: [/opt/models] container_images: ["vllm/vllm-openai:v0.27.1"] # pin a digest in production pools: - id: qwen backend: vllm mode: supervise model: qwen05 alias: local-qwen weights: /opt/models/Qwen2.5-0.5B-Instruct image: "vllm/vllm-openai:v0.27.1" replicas: 2 context_tokens: 4096 port_base: 8001 gpu: {mode: nvidia} # devices discovered with nvidia-smi; or devices: [MIG-..., MIG-...] health: {ready_timeout: 10m} ``` For each replica the gateway runs, after removing a container left under the same name: ```bash docker run --rm --name gateway-local-qwen-r1 --ipc=host --gpus device=MIG- \ -p 127.0.0.1:8001:8000 -v /opt/models/Qwen2.5-0.5B-Instruct:/models/Qwen2.5-0.5B-Instruct:ro \ -e HF_HUB_OFFLINE=1 vllm/vllm-openai:v0.27.1 \ --model /models/Qwen2.5-0.5B-Instruct --served-model-name qwen05 --host 0.0.0.0 --port 8000 \ --gpu-memory-utilization 0.85 --max-model-len 4096 ``` - The replica is bound to one device with `--gpus device=`: a container on a MIG slice sees that slice and nothing else. - The weights are mounted read-only and the server runs offline. - The port is published on `127.0.0.1` only. - `slots` becomes `--max-num-seqs`. A stop is `docker stop` with `stop_grace` as its timeout. - The gateway needs to run `docker`, so the user it runs as needs access to the Docker socket. That is a strong permission: grant it only on a host dedicated to inference. With `gpu.mode: off` no `--gpus` and no memory fraction are passed; pick an image built for the CPU. ### Memory headroom `--gpu-memory-utilization` is a fraction of the device the replica sees, a whole card or one slice. Leave room: on a `1g.5gb` slice, 0.85 left 137 MiB free and a restarted replica failed to start; 0.70 held. So the default of `gpu.memory_fraction` is: | Device | Default | | --- | --- | | A whole GPU, or a MIG slice of 10 GB or more | 0.85 | | A smaller MIG slice, or a slice named by UUID whose size the gateway did not read | 0.70 | | A device shared by n replicas (`share_device`) | the value above divided by n | A replica that cannot start shows its exit status and the last line it wrote on the Local inference screen, with the device it was bound to. ## Replicas you start yourself Start the containers with the command above (or any other way) and register them: ```yaml local_inference: pools: - id: qwen backend: vllm model: qwen05 alias: local-qwen endpoints: - {url: "http://10.0.0.5:8001/v1", device: MIG-} - {url: "http://10.0.0.5:8002/v1", device: MIG-} ``` The gateway health-checks `/health` and `/v1/models` on each endpoint, routes by load and stops routing to one that fails. **Stop** and **Start** on the screen take a registered replica out of and back into routing; restarting it is yours. If the servers ask for a key (`--api-key`), name the environment variable that holds it in `api_key_env`. ## Kubernetes In a cluster the gateway does not start Pods: run vLLM as a workload and register the replicas. A StatefulSet with a headless Service gives each replica a stable name; request one GPU or one MIG slice per Pod. A starting point, to adapt to your GPU operator's resource names and your storage: ```yaml apiVersion: apps/v1 kind: StatefulSet metadata: {name: vllm} spec: serviceName: vllm replicas: 2 selector: {matchLabels: {app: vllm}} template: metadata: {labels: {app: vllm}} spec: enableServiceLinks: false # a Service named vllm would inject VLLM_PORT, which vLLM reads as its own setting containers: - name: vllm image: vllm/vllm-openai:v0.27.1 args: ["--model", "/models/Qwen2.5-0.5B-Instruct", "--served-model-name", "qwen05", "--gpu-memory-utilization", "0.70", "--max-model-len", "4096"] ports: [{containerPort: 8000}] resources: {limits: {nvidia.com/gpu: 1}} # with MIG and the mixed strategy: nvidia.com/mig-1g.5gb: 1 readinessProbe: {httpGet: {path: /health, port: 8000}} volumeMounts: [{name: models, mountPath: /models, readOnly: true}] volumes: [{name: models, persistentVolumeClaim: {claimName: models}}] ``` ```yaml local_inference: pools: - id: qwen backend: vllm model: qwen05 alias: local-qwen endpoints: - {url: "http://vllm-0.vllm:8000/v1"} - {url: "http://vllm-1.vllm:8000/v1"} ``` Every gateway replica probes the endpoints on its own. Scaling the StatefulSet is yours; add the new endpoint to the pool. ## What to expect Through the gateway with `least_busy`, 160 output tokens per stream: | Layout | Streams | First token (median) | Total tokens/s | | --- | --- | --- | --- | | One replica on an L4 | 6 | 45 ms | 1,116 | | One replica on an L4 | 32 | 109 ms | 4,719 | | Two `3g.20gb` slices of an A100 | 6 | under 45 ms | 1,929 | | Two `3g.20gb` slices of an A100 | 32 | under 75 ms | 8,150 | | Two `3g.20gb` slices of an A100 | 224 | under 450 ms | 24,653 | The gateway added 3 to 15 ms to the first token and cost 1% to 6% of the throughput against a replica called directly. A replica killed under 32 streams caused no HTTP error for requests that had not started; streams already running on it were cut and reported as `stream_interrupted`. ## Metrics vLLM publishes `vllm:` Prometheus metrics at `/metrics`. With `provider_metrics_scrape` on, every replica of the pool is scraped with no further setting, and the Local inference screen shows `vllm:num_requests_running` and `vllm:num_requests_waiting` per replica. In MIG mode `nvidia-smi` reports no utilization per slice; use the DCGM exporter (`DCGM_FI_PROF_GR_ENGINE_ACTIVE`, `DCGM_FI_DEV_FB_USED`) for that. # Network policy per provider **Last updated:** 2026-11-22T07:30:00-03:00 (UTC-3) Use `providers[].network` when one connection needs a different CA, client certificate or proxy from the [global upstream network](/docs/operate/network-configuration/). Each connection keeps its own TLS/proxy capture and connection pools. Other providers, PostgreSQL, caches and identity providers keep their existing configuration. `features.provider_network` defaults to `false`. A provider with an explicit profile refuses calls while the flag is off; it never falls back to a less restrictive transport. Providers without a profile continue using the global network. ## Inherit, replace or reset | Declaration | Result | | --- | --- | | No `network` field, or YAML `network: null` | Inherit the global CA, mTLS and proxy | | `network: {}` | Explicit replacement: system CAs, no client certificate, direct connection | | Nonempty `network` object | Replace the complete trust/proxy profile; omitted selectors use the reset defaults below | A provider profile does **not** merge individual credential fields with the global network. If you specify only a private CA, you do not accidentally inherit a global client identity or proxy. To use a global reference in the replacement profile, select it explicitly. Global operation/stream deadlines, transport timeouts, IPv4 selection, HTTP version, numeric connection pools and admission limits still apply. A single `proxy_url_env` adds no retry loop or failover; for several proxies with health and failover, require a [proxy pool](#proxy-pools). ## YAML example Provision the proxy and mount the certificate files before starting the gateway. The referenced variables contain a proxy URL or a mounted file path; these values never belong in the provider API or console form. ```yaml features: provider_network: true providers: - id: private-models protocol: openai base_url: https://llm.corporate.example/v1 api_key_env: PRIVATE_LLM_KEY network: ca_file_env: PRIVATE_LLM_CA_FILE client_cert_file_env: PRIVATE_LLM_CERT_FILE client_key_file_env: PRIVATE_LLM_KEY_FILE proxy_url_env: PRIVATE_LLM_PROXY_URL no_proxy: - llm.corporate.example:443 - id: public-models protocol: openai base_url: https://api.openai.com/v1 api_key_env: OPENAI_API_KEY # No profile: use the global upstream network. ``` In this example, the exact `no_proxy` match makes the private endpoint connect directly, while still requiring its configured CA and client certificate. Remove that entry to use the configured proxy. Choose the route deliberately; a bypass list is an operator policy, not a permission supplied by a caller. Docker, Kubernetes, native binaries and NPX use the same YAML. The operator supplies the mounted files, process environment and services through that deployment's normal mechanisms. Kubernetes Secret volume symlinks retain the existing validated-file profile; no Kubernetes distribution or addon is required by the data path. ## Fields and defaults | Field | Replacement default | Contract | | --- | --- | --- | | `providers[].network.ca_file_env` | Absent: system roots | ENV name containing a mounted PEM CA file path; private CA is added to system trust | | `providers[].network.client_cert_file_env` | Absent: no mTLS | ENV name containing the mounted client certificate path; requires the key selector | | `providers[].network.client_key_file_env` | Absent: no mTLS | ENV name containing the mounted private-key path; requires the certificate selector | | `providers[].network.proxy_url_env` | Absent: direct | ENV name containing an HTTP(S) proxy URL, optionally with proxy authentication; no query, fragment or non-root path | | `providers[].network.no_proxy` | `[]` | Up to 64 unique canonical destination patterns, each at most 256 UTF-8 bytes | | `providers[].network.proxy_pool` | Absent: no pool | ID of a [proxy pool](#proxy-pools) declared in the YAML; every call must go through one of its members. Cannot be combined with `proxy_url_env` or `no_proxy` | Reference names follow the existing ENV-name grammar, up to 128 ASCII bytes. Empty reference strings and omission both mean absent. The object accepts no other fields. Null member values, wrong types, duplicate/case-aliased names and malformed bypass patterns are rejected. Null at the **whole-profile** level is the distinct inheritance choice. TLS keeps chain and hostname verification and the existing minimum TLS version. No `insecure_skip_verify` option is added. Each certificate/key file uses the existing regular-file, bounded 1 MiB reader. Invalid/missing material is rejected without printing paths or contents. On Windows the reader also requires the file and the directories above it to be protected from untrusted accounts, and refuses links ([mounted files on Windows](/docs/operate/deployment-modes/#mounted-files-on-windows)). Existing platform certification for mounted files still applies; a supported binary does not by itself certify a new filesystem/OS profile. The profile governs TLS connections made through its transport, including an HTTPS proxy hop. Choose a trusted proxy and certificate chain for that path. A `no_proxy` match changes only proxy selection; it never disables CA validation, mTLS or provider authentication. ## Exact bypass matching | Pattern | Meaning | | --- | --- | | `api.example.com` | This exact DNS name, case-insensitive | | `.example.com` | Subdomains such as `a.example.com`; excludes `example.com` and `badexample.com` | | `api.example.com:443` | Exact host and effective port 443 | | `192.0.2.10` | This literal IP | | `192.0.2.0/24` | Literal destination IPs in this canonical prefix | | `2001:db8::1` | This literal IPv6 address | | `[2001:db8::1]:443` | This IPv6 address and port 443 | Default effective ports are 80 for HTTP and 443 for HTTPS. CIDR matching does not resolve a DNS name to guess whether its eventual address is private. Mapped literal destinations use their IPv4 equivalent consistently. Use ASCII DNS names, including an encoded name when needed. Patterns cannot contain URLs, credentials, paths, queries, whitespace, zones, regex, `*`, arbitrary wildcards, malformed ports or CIDR-plus-port combinations. Prefixes must be canonical; mapped prefixes are refused. There is **no automatic localhost/loopback bypass** and no ambient `HTTP_PROXY`, `HTTPS_PROXY` or `NO_PROXY` lookup. This preserves the existing explicit-proxy contract. ## Console and API authority Open **Providers → Edit → Network policy**. Choose global inheritance or an explicit replacement, select admitted reference names and edit the bounded bypass list. No PEM, key, mounted path, resolved proxy URL or proxy password is loaded into the editor. A remote writer may select a nonempty reference only if that exact **slot** was admitted at process boot for the **same provider ID**, or is the corresponding global slot. A CA reference does not grant access to an arbitrary key slot, and one provider cannot borrow another provider's client identity. A new console-only provider can use global admitted slots or no host material. To add new material, update the deployment/YAML and roll out first; saving a new ENV name remotely does not grant host-file access. V21 configuration readers with current provider-write authority receive `network` (selected profile or null), `network_references` (admitted names) and the applicable `provider_network_access` capability. Its writer-only `global_references` supports creating a connection. Read-only readers receive safe `network_policy` configured/source/inheritance facts, with no reference inventory. These facts describe configuration, **not a successful TLS handshake, negotiated protocol or health check**. Team/public projections expose no profile/reference inventory. Use the existing versioned provider PUT/DELETE API. In a complete PUT: - Omitting `network` preserves the existing profile, including for an older client. - `"network": null` restores global inheritance. - `"network": {}` selects the explicit reset. - A nonempty object supplies the complete replacement. Deleting a console override restores its YAML provider/profile when one exists. Global version checks, current live role/permission, feature-license checks and audit apply to additions, removal and restoration. A flag enables behavior; it never grants access. The operational flag may be off while an authorized writer stages a valid profile, but that provider will refuse calls until activation. ## Cache identity A client certificate or authenticated proxy can select a different upstream account even when its reference name stays the same. Exact-cache identity and cached helper/vector-index identity therefore include private captured material identity. Existing unprofiled keys and single-target exact-cache restrictions stay unchanged. A disabled/unavailable explicit profile cannot serve a warmed exact answer. Semantic answer caching is bypassed when the answer or embedding provider has an explicit network profile. No private material or fingerprint is exposed in metadata, logs or metrics. Updating a reference/capture does not claim semantic equivalence between upstream accounts. ## Reload, rotation and failure The gateway validates and captures mounted material before accepting a configuration generation. It does not reread files or ENV values for each request, and it adds no file watcher. Explicit reviewed reload/configuration changes capture new material. Replacing a Secret file alone does not promise immediate transport rotation. The accepted operation captures its configuration and transport bundle consistently. A newly admitted request uses the new generation; already admitted HTTP operations, streams and WebSockets retain their selected generation through close. Retired idle connections are closed, and late completions release their remaining ownership. There is no permanent cache of old profile fingerprints. A failed material capture rejects the candidate before its database/control publication. Refresh failure keeps the last accepted configuration and transport; startup failure stops initialization. Missing/disabled profile transport is a known-not-sent refusal, preserving existing financial reservations and attempt semantics. It produces no upstream-attempt record or provider valuation. A pinned video observation refused before polling retains its existing job state; it does not create an unknown provider result or reroute to another account. A valid CA that does not trust a server can still produce an ordinary TLS transport failure during connection; configuration capture is not remote endpoint certification. Existing authorized fallback may choose another target under its own policy, but it never silently changes this provider to the global or direct transport. With an explicit profile, provider-authenticated catalog calls, shared inference/resource calls, video polling and realtime establishment use that selected transport. Without a profile, authenticated catalogs retain their existing dedicated catalog client; global inference TLS/proxy settings did not previously govern that client, and this feature does not silently add them. Community/public catalogs and unrelated IdP, MCP, guardrail and log-destination clients do not acquire its client certificate. Existing redirect refusal remains in force. ## Authenticated proxy error privacy When the selected provider transport actually uses a proxy with user information, including an owned captured global proxy, the gateway withholds error bodies and untrusted response headers instead of searching them for a password. At the provider-transport boundary, the response retains its HTTP status and a fixed native-format error with `provider_proxy_error_withheld`. Public routes retain their existing mappings: for example, a catalog failure can become 503 and an asynchronous video failure can become 502. A rejected WebSocket upgrade is also withheld, including an upstream 200 that did not complete the upgrade. This applies regardless of credential length or what the error text contains. Proxy-visible transport errors use a finite message while retaining cancellation/timeout classification internally. HTTP status-based retries/fallback retain their existing rules. Context-window/content-policy fallback cannot classify text that was withheld; no hidden text channel bypasses the privacy boundary. Direct connections, matching `no_proxy` routes and proxies without authentication retain their ordinary error treatment. Successful responses are unchanged. Global inheritance keeps its existing transport/trust selection; authenticated global proxy errors receive the same privacy repair. Unauthenticated and direct global requests are unchanged. Dedicated catalog clients that do not use that proxy do not acquire this treatment. ## Proxy pools A **proxy pool** is a named set of outbound HTTP(S) proxies. A provider profile that sets `proxy_pool` **requires** the pool: every call goes through one of its members, and when no member can take it the call is refused before reaching the provider. It is never sent directly, through the global proxy or through another pool. It needs `features.proxy_pools` (operator control, off by default, requires `provider_network`). ```yaml features: provider_network: true proxy_pools: true proxy_pools: - id: egress-eu strategy: failover # or round_robin max_in_flight: 256 max_connections_per_member: 64 # omit to inherit network.max_connections_per_host failure_threshold: 3 cooldown_seconds: 30 providers: [other-models] # optional: more providers a remote writer may attach members: - id: eu-1 proxy_url_env: EGRESS_EU_1 # http(s)://[user:password@]host:port - id: eu-2 proxy_url_env: EGRESS_EU_2 providers: - id: private-models protocol: openai base_url: https://llm.corporate.example/v1 api_key_env: PRIVATE_LLM_KEY network: ca_file_env: PRIVATE_LLM_CA_FILE proxy_pool: egress-eu ``` | Field | Default | Bounds and meaning | | --- | --- | --- | | `id` | required | Unique, `^[a-z][a-z0-9_-]{1,63}$`; at most 32 pools | | `members[]` | required | 1–16 members, each a unique `id` (same pattern as the pool ID) and a distinct `proxy_url_env` (the ENV name holding an `http` or `https` proxy URL, optionally with user information; no path, query or fragment) | | `strategy` | `failover` | `failover` tries members in order, the first healthy one first; `round_robin` rotates the first member over the healthy ones | | `max_in_flight` | 256 | 1–10,000 requests through the pool at once, on this replica, across every provider and HTTP version that uses it. One more is refused at once with `503 provider_proxy_pool_saturated`, not queued. A streaming response holds its slot until it ends | | `max_connections_per_member` | inherits `network.max_connections_per_host` | 1–1,024 connections per destination through one member; further requests wait for a connection within the request's own deadline. Each member also keeps its own idle connections, so idle connections can reach members × `network.max_idle_connections` | | `failure_threshold` | 3 | 1–100 consecutive member faults that eject a member | | `cooldown_seconds` | 30 | 1–3,600 seconds an ejected member is skipped; afterwards real traffic tries it again, and one more fault ejects it again. Concurrent calls in that moment all try it and fail over if it is still down | | `providers` | `[]` | Up to 64 provider IDs that may require this pool besides providers whose YAML profile already requires it (see authority below) | A profile with `proxy_pool` cannot also set `proxy_url_env` or `no_proxy`: a required pool has no direct bypass. CA and client-certificate selectors combine with it as usual, and TLS to the provider is verified end to end through the member's tunnel. **Failover is safe by construction.** The gateway moves a request to the next member only when the previous one never produced a connection: the proxy refused the TCP connection, the `CONNECT` was answered with an error, the member did not finish connecting within the connect timeout (`network.connect_timeout` plus the TLS handshake timeout; a proxy that accepts and never answers would otherwise hold the request until its deadline), or the tunnel's TLS handshake failed. Nothing of the request was written, so a body is replayed on the next member. Once a connection exists the request is never replayed, whatever happens next: the answer, or the error, is the call's outcome, and the usual retry and fallback rules apply to it. A body that cannot be replayed is never sent through a second member. **Health is passive and counts member faults only.** Only real requests feed it, and nothing probes a member, so no request is sent just to test a proxy. A fault is a failed connection to the member, no `CONNECT` answer within the connect timeout, or `407 Proxy Authentication Required`. A `CONNECT` refused for the destination (`403`, `502`, `503`...) or a TLS failure toward the provider after a successful `CONNECT` still fails the request over, but is not counted: it belongs to that provider, and must not eject a member other providers rely on. A success resets a member's fault count. Health is per replica and lives in memory: a restart or a configuration change to a member's URL starts it healthy. **Refusals.** When every member is ejected or fails to connect, the call ends with `503 provider_proxy_pool_unavailable` before any provider call. It is a known-not-sent refusal, handled exactly like the profile's other ones described in [reload, rotation and failure](#reload-rotation-and-failure): no provider valuation and the same financial-reservation and attempt semantics. Fallback to another target of the model follows its own policy and its own network profile. With `proxy_pools` off, a provider that requires a pool refuses the same way, and its models report not ready. A realtime WebSocket handshake refused this way answers `502 upstream_unavailable`, as other realtime handshake failures do; nothing reached the provider. **Material and authority.** Pools are boot trust, like reference names: their members are captured from the environment when the configuration is accepted, and a missing or malformed member URL rejects the configuration, even while `proxy_pools` is off. A pool's members carry credentials and network reach, so a pool is admitted per provider, like a reference slot: a remote writer can make a provider require a pool (**Providers → Edit → Network policy → Required proxy pool**, or `"proxy_pool"` in the provider PUT body) only when that provider's YAML profile already requires it or the pool lists the provider under `providers`. Any other choice is refused (`422`). Adding a pool, a member or a listed provider requires a YAML change and rollout. Provider readers with write access receive the admitted pools of each provider as `network_proxy_pools`; `provider_network_access.proxy_pools` lists every declared pool for creating a provider, and the server still applies the admission rule to the new ID. A member with user information receives the [authenticated proxy error privacy](#authenticated-proxy-error-privacy) treatment: when any member of the pool is authenticated, every error answer through the pool is withheld. The pool's member URLs join the private capture identity used for cache isolation. **Status.** `GET /api/v1/admin/proxy-pools` (`providers:read`, `proxy_pools` on) lists each pool (`proxy_pools`, with the YAML names: `strategy`, `max_in_flight`, `max_connections_per_member`, `failure_threshold`, `cooldown_seconds`, as effective values) with the providers that require it and, per member, its ID, scheme, whether it is authenticated, whether it is ejected, consecutive failures, successes and connection failures. It never returns proxy URLs, hosts, credentials or reference names. The console shows the same under **Providers → Proxy pools**. ## Rollout and recovery No new schema migration or secret-ciphertext family is needed: stored provider JSON contains reference names and bypass tokens, never resolved material. Mount admitted files/variables consistently on every replica. Upgrade or quiesce all older readers/writers **before persisting profiles**; older binaries can ignore the new JSON field or replace it on a full write. A mixed-version pool cannot enforce this policy reliably. Back up the existing configuration/database and keep recovery on the new binary. Repair the material/reference and explicitly reload; do not recover by bypassing TLS validation or routing through an old replica. # Native provider passthrough **Last updated:** 2026-11-23T10:17:09-03:00 (UTC-3) A passthrough alias exposes an operator-selected native provider action through the gateway. The gateway authenticates the caller and the provider, applies the alias's access policy, and forwards the request bytes without translating the payload or replacing its model field. Use ordinary inference endpoints when you want protocol translation, prompt policies or a protected financial profile. The alias has the exclusive `passthrough` capability and one target. Its target fixes the provider connection and the operator's upstream model label. The `passthrough` policy fixes the method and path relative to that provider's Base URL. The client never supplies another origin, provider credential or forwarding URL. ## Configuration This fragment defines one native OpenAI Responses action. The model name is an example, not a gateway default; confirm availability in your provider account. Add it to the gateway configuration and provide the referenced secret through the deployment. It is not a complete installation configuration. ```yaml features: provider_passthrough: true provider_passthrough_usage: true providers: - id: openai protocol: openai base_url: https://api.openai.com/v1 api_key_env: OPENAI_API_KEY models: - id: native-responses capabilities: [passthrough] targets: - provider: openai model: gpt-5.4-nano passthrough: method: POST upstream_path: /responses include_subpath: false usage_profile: openai_responses allowed_query_params: [] ``` Grant a key `route:passthrough` and the `native-responses` alias through the ordinary team/key policy. The body names the upstream model explicitly; `native-responses` is a gateway permission and route name, not a substituted JSON model. ```bash BASE_URL='http://localhost:8080' : "${GATEWAY_API_KEY:?set a key authorized for native-responses}" curl --fail-with-body -sS -X POST "$BASE_URL/v1/passthrough/native-responses" \ -H "Authorization: Bearer $GATEWAY_API_KEY" \ -H 'Content-Type: application/json' \ --data-binary '{"model":"gpt-5.4-nano","input":"Reply with OK","reasoning":{"effort":"none"},"max_output_tokens":16,"store":false}' ``` ## Fields, defaults and bounds Keys of the `models[].passthrough` block: | Field | Default | Accepted profile | | --- | --- | --- | | `models[].passthrough.method` | Required; the editor presets `POST` only for a new draft | One of `GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE` | | `models[].passthrough.upstream_path` | Required | Rooted ASCII path, 1–2048 bytes, appended to the configured provider Base URL | | `models[].passthrough.include_subpath` | `false` | When enabled, a client suffix can contain at most 2048 bytes and 32 safe segments | | `models[].passthrough.usage_profile` | `none` | `none`, `openai_chat`, `openai_responses`, `anthropic_messages`, `gemini_generate_content` | | `models[].passthrough.allowed_query_params` | `[]` | At most 32 unique case-sensitive names, each at most 64 bytes; credential, identity and hop-control names remain forbidden | The exclusive passthrough alias must be a safe 1–64 character URL segment: letters/digits first, followed by letters, digits, dots, underscores or hyphens. It must have exactly one target. No implicit alias-family, cache, retry or fallback broadens the native action. Paths cannot contain another authority/URL, query, fragment, dot segment or ambiguous encoded slash/backslash. The request query is limited to 8192 bytes, each value to 1024; duplicate names and unlisted names are rejected. Allow only query parameters your selected endpoint actually needs. Enabling a suffix grants the configured subtree, while retaining the same host and prefix. The execution flag `provider_passthrough` and the separate usage flag `provider_passthrough_usage` default to `false`. Usage depends on execution. If a non-`none` profile is configured while its usage flag is off, the action refuses rather than silently disabling the configured observation. Use `none` explicitly when no measurement is wanted. OpenAI profiles require an OpenAI-protocol connection, Anthropic Messages requires Anthropic, and GenerateContent requires Gemini. JSON observation uses the existing 64 KiB capture bound; an answer beyond the measurement profile may be relayed with unknown usage. SSE measurement additionally requires `stream_usage` and its bounded supported event profile. Binary vendor event streams are relayed as bytes, with no invented token decoder. ## Permissions and feature controls Calling an alias requires `route:passthrough` (or the reviewed `route:*` scope), permission for that alias in the key and team policy, and the applicable feature and plan rights. Existing source-IP, attribution, rate and concurrency controls apply. A route or feature flag grants no permission by itself. An alias grants the configured native action and its accepted body. It does not rewrite or independently authorize every resource ID or model name nested in that opaque body. Grant narrowly scoped endpoints to the teams and keys that need them. Do not expose an entire account's management API through a broad path unless that is the intended permission. With [organization admins](/docs/features/organization-admins/) on, every organization shares the provider account, so an action whose usage profile is `openai_chat`, `openai_responses`, `anthropic_messages` or `gemini_generate_content` refuses, with `422 provider_state_not_isolated` and before sending, any subpath (it addresses a stored object by the provider's own ID), a body naming stored state (`previous_response_id`, `conversation`, an item reference, a reasoning item by ID, a provider file the request reads, a Messages `container` or `container_upload`, a Gemini `cachedContent` or `fileData.fileUri`) and a body the gateway cannot read, such as a compressed one. Use the gateway's own `/v1/responses` and `/v1/messages` routes for stored state. Actions with no usage profile stay opaque: only what the alias grants limits them. ## Raw request and response The body is not parsed and reserialized for forwarding. This preserves multipart boundaries, binary content and native request formats. The configured provider supplies authentication; the client's gateway bearer and protected identity headers never become upstream provider credentials. Per-provider CA, mTLS and proxy settings use the same captured transport generation as ordinary inference. Requests and responses retain the existing body/admission/stream limits and cancellation ownership. Upstream redirects are refused. There is no retry, fallback or response cache: a timeout or broken stream must not replay a potentially stateful operation. Configuration changes affect newly admitted operations, while an admitted response retains its selected connection. Optional subpaths and query names must be explicitly allowed in the alias policy. They do not allow a different host or escape the configured path prefix. Invalid or ambiguous paths, credential-bearing query parameters and unlisted query names are refused before sending. Configure a separate alias for an action requiring a different method or destination. ## Usage is separate from financial proof Optional usage collection uses an explicitly selected existing native response profile. It observes reported token counts without altering the response, and it does not infer support or cost from an arbitrary endpoint name. Missing, unsupported or incomplete usage remains unknown; it is never treated as zero. Usage observation does not qualify an opaque operation for a budget or TPM reservation. If an applicable policy requires a financial/token profile that this action cannot prove, the gateway refuses before contacting the provider. This includes applicable global and provider policies, in addition to key, team, user, organization, project and model policies. Disabling usage collection cannot bypass a limit. Likewise, an opaque endpoint cannot silently bypass an applicable prompt, guardrail or request transformation that it cannot implement. Use a supported ordinary inference profile when those controls are required. ## Traceability and privacy The request retains its request/correlation ID and W3C trace context through the provider call. Request metadata, native usage and failures use the ordinary log/telemetry flow. Payloads, provider credentials and proxy authentication are not telemetry. A refusal before dispatch never becomes an upstream attempt or a charge. Authenticated proxy errors retain the existing privacy boundary described in [provider network policy](/docs/features/provider-network/). ## Deployment and recovery The same versioned YAML, administrative API and native console manage this policy. YAML remains the base; a validated versioned console/API override takes precedence, and reverting restores the YAML alias. Current write permissions, optimistic version checks, license guards and audit apply to every mutation. Upgrade older writers/readers before persisting a new policy field. A network or credential failure keeps its normal failure classification; repair the selected provider rather than broadening the route or enabling an unprotected alternative. Route availability is configuration, not a claim that the upstream supports an operation or that a health check passed. # Provider credential pools **Last updated:** 2026-11-21T09:54:10-03:00 (UTC-3) A provider can retain one legacy API key or declare a pool of named static credentials. The gateway keeps a stable primary credential for account-bound operations and can distribute qualified text Chat traffic by relative weight. A pool does not increase a provider's quota, prove two accounts equivalent, grant client permissions or add retries. ## Defaults and supported scope Keys of each `providers[]` entry and the flags around them: | Setting | Default | Effect | | --- | --- | --- | | `features.provider_credential_pools` | `false` | Runtime operator switch for weighted selection. Off uses only the explicit primary. | | `features.provider_credential_cooldowns` | `false` | Requires pools; excludes failed credentials from future qualified weighted selections. | | `providers[].credentials` | Absent | Existing scalar credential behavior. At most 16 named entries for static bearer/protocol-specific or custom-header authentication. | | `providers[].credentials[].id` | Required | Name of the credential within the connection, used by `primary_credential_id`, the logs and the console | | `providers[].credentials[].api_key_env` | Required for a static key | Variable holding that credential's key | | `primary_credential_id` | No implicit choice | Required with a pool; must name an entry. No fallback to a legacy scalar secret. | | `credentials[].weight` | `1` | Integer 1–1000, relative share. Use `disabled` to stop an entry. | | `credentials[].cooldown` | `30s` | Go duration, whole milliseconds 0–1h; `0s` disables this entry's cooldown. | | `credentials[].disabled` | `false` | Prevents use of this credential on every path, including primary-only and weighting-off paths. | | `credential_cooldown_statuses` | `[401,429]` | At most32 unique HTTP statuses 400–599. Explicit `[]` disables signals. | | `credential_selection_max_body_bytes` | `65536` | Raw0 selects the default; explicit 1024–1048576. Larger bodies use primary without modification. | Each ID matches `[a-z][a-z0-9_-]{0,63}` and is unique within its provider. A pool cannot coexist with a legacy scalar key/reference or cloud/no-auth authentication. An entry needs an admitted secret reference or stored secret. A temporarily unavailable reference does not certify readiness or prevent the gateway from starting: unresolved entries cannot be selected, and an unavailable primary fails primary-only operations closed. The initial weighted profile is **text Chat execution**, JSON or streaming, after defaults and per-target encoding. Native OpenAI Chat and the existing Chat-to-Anthropic/Gemini basic-text encoders are qualified. The gateway requires private proof of Chat execution and checks the final body structurally. Unknown extensions, duplicate/ambiguous fields, tools/history, media/file/resource references, stored state, prompts or continuations use primary unchanged. Text containing a word such as `file_id` remains ordinary text. The classifier neither deletes fields nor rewrites a request to make it eligible. Every other operation uses primary: native Messages/GenerateContent outside Chat translation, Responses/Conversations, files, vector stores, fine-tuning, containers, media/video, realtime, token counting and catalogs. Pagination/polling uses one captured primary handle. These paths ignore weighted cooldown, but never disabled or missing primary. This is not automatic affinity across a change of primary or secret: changing either can change the provider account and invalidate existing provider objects. ## Configure in YAML ```yaml features: provider_credential_pools: false provider_credential_cooldowns: false providers: - id: openai-pool preset: openai primary_credential_id: production credential_cooldown_statuses: [401, 429] credential_selection_max_body_bytes: 65536 credentials: - id: production api_key_env: OPENAI_API_KEY_PRODUCTION weight: 3 cooldown: 30s disabled: false - id: overflow api_key_env: OPENAI_API_KEY_OVERFLOW weight: 1 cooldown: 30s disabled: false ``` This fragment is part of a complete gateway configuration. Existing environment/file/secret-manager resolution supplies the values; do not put provider keys in version control. The preset does not inject its conventional scalar reference into a pool. Review primary/account ownership before enabling weighting. All client route, model, role, team, budget and rate checks still apply. Pool members share the connection URL, headers, model aliases and approved price profile; the provider still checks each key's access. Use separate providers/targets when accounts require different connection/model policy. Catalogs inspect primary only; they do not merge permissions or advertise secondary-account models. With weighting on, the example has a 3:1 configured relative share among available entries. Bounded smooth weighted round robin is process-local, not a promise that every short sample, fleet or provider quota has that ratio. Disabled/unresolved/cooling entries do not participate. Duplicate resolved enabled secrets under different IDs fail closed, preventing aliases around the cooldown. ## Cooldown and failure behavior Only response-header signals from qualified weighted dispatches feed cooldown. Caller cancellation, local rejection, an ambiguous transport outcome or a midstream failure do not mark a credential unhealthy. Native/primary-only/catalog calls do not feed this mechanism. It is not universal provider-health monitoring. For a configured status, a valid `Retry-After` can shorten the entry's configured duration; that duration is also the upper bound. Invalid/absent values use the configured duration. No cooldown sleep or additional retry loop is introduced. Existing retry/fallback eligibility remains authoritative; a started stream is never replayed. If a provider has no eligible credential, it is unavailable **before a send**. An existing configured and authorized target fallback may proceed only under its normal flag/operation/replay rules, without inventing a paid attempt or breaker failure. If no lawful target remains, the request receives 503 `provider_credentials_unavailable` with bounded `Retry-After`. An account-bound operation never silently switches credentials or provider to recover. State is local to a process and starts cold after restart. Secret/policy generations fence old flights so they cannot cool a replacement or reinstall older state. Correlated diagnostics identify finite configured provider/credential IDs; they never include secret values, references, ciphertexts or fingerprints. ## Manage through the API and console The existing provider editor and `PUT /api/v1/admin/providers/{id}` use the same global version, current permissions, CSRF, full-snapshot validation and audit. `provider_credential_access` contains only two effective extra write capabilities (`pool_write`, `cooldown_write`), intersecting provider permissions and feature-aware license state. Child writes also require parent. Missing/malformed capability data disables the new editor, without granting permission or stopping established inference. The typed pool descriptor introduced in V13 is preserved in V14, which the current console requests; it supplies the actual bounds/defaults. The strict reader accepts V13 or V14; missing or malformed metadata disables this new editor rather than inventing values. Safe configuration shows the primary, effective pool policy and per-entry credential presence/source. Presence is configuration information, not successful authentication or provider health. Weight, cooldown, status-list and body-bound sources distinguish `default`, `yaml` and `console`; material source is separately `yaml`, `console` or `unconfigured`. Pool fields are omitted for legacy providers. API pool metadata goes inside `provider`; secrets are a separate write-only `credential_secrets` map keyed by entry ID. No arbitrary secret reference is accepted through the pool API. Secrets are limited to 2048 UTF-8 bytes each, without HTTP-invalid ASCII controls (C0 except HTAB, plus DEL); the entire provider request is bounded to 64 KiB. Omitted/blank secrets retain only that existing ID's secret or exact admitted YAML binding. A new ID needs a new secret or exact declaration. Omitted pool metadata on an unchanged static-auth edit preserves it; removing it requires explicit `credentials: []` and a valid legacy source. An auth transition cannot resurrect an old inactive ciphertext. This example creates a **new** connection; do not reuse it to overwrite another provider's headers/auth options. Supply an authenticated cookie jar and its CSRF token through the normal console session procedure: ```sh BASE_URL='http://localhost:8080' : "${COOKIE_JAR:?Set the authenticated console cookie file}" : "${CSRF_TOKEN:?Set the session CSRF token}" : "${OPENAI_API_KEY_PRODUCTION:?Load the primary key outside the repository}" : "${OPENAI_API_KEY_OVERFLOW:?Load a distinct secondary key outside the repository}" SNAPSHOT=$(mktemp) trap 'rm -f "$SNAPSHOT"' EXIT curl --fail-with-body -sS -b "$COOKIE_JAR" \ "$BASE_URL/api/v1/admin/config" > "$SNAPSHOT" python3 - "$SNAPSHOT" <<'PY' | curl --fail-with-body -sS \ -b "$COOKIE_JAR" -X PUT -H "X-CSRF-Token: $CSRF_TOKEN" \ -H 'Content-Type: application/json' --data-binary @- \ "$BASE_URL/api/v1/admin/providers/openai-pool-example" import json, os, sys snapshot = json.load(open(sys.argv[1])) json.dump({ "version": snapshot["version"], "provider": { "id": "openai-pool-example", "preset": "openai", "primary_credential_id": "production", "credentials": [ {"id": "production", "weight": 3, "cooldown": "30s", "disabled": False}, {"id": "overflow", "weight": 1, "cooldown": "30s", "disabled": False} ] }, "credential_secrets": { "production": os.environ["OPENAI_API_KEY_PRODUCTION"], "overflow": os.environ["OPENAI_API_KEY_OVERFLOW"] } }, sys.stdout) PY ``` Do not record the pipeline input or use verbose credential-bearing HTTP traces. The response never returns these secrets. Saving the provider does not make a paid model call or prove its keys work. A409 requires reloading/reviewing the version; an uncertain write requires a fresh read before retry. The editor discards secret drafts and late replies on authority, provider, authentication or flag changes. ## Cache, rotation and recovery Exact/catalog/discovery/latency namespaces include private pool/primary identity; they do not advertise account equivalence. **Semantic cache is bypassed when either the answer or embedding connection has a pool**, including weighting-off. This avoids storing a response under another secret generation; legacy nonpool semantic caching is unchanged. No cache result grants permission or bypasses budget/revocation checks. Migration 119 stores pool ciphertexts separately from metadata and binds each to its provider/entry with authenticated encryption. Removing an entry/override deletes its ciphertext atomically; backup/restore must retain the matching operator encryption keyring. The explicit offline [reencryption procedure](/docs/security/keyring-rotation/) includes this family. Preserve the usual quiesced-writer backup and unknown-COMMIT recovery rules. Upgrade every replica before admitting pools or enabling their flags. Older binaries do not understand the new YAML, schema or metadata; follow the normal backup/configuration rollback procedure. Default PostgreSQL is the validated managed-persistence boundary; no optional-engine or cloud-host certification is implied. Source-IP restrictions, credentials, provider flags and client permissions remain independent ceilings. See [providers](/docs/features/providers/), [parameter metadata](/docs/reference/parameter-registry/), [resilience](/docs/features/resilience/), [automatic pricing](/docs/features/automatic-pricing/) and [operations](/docs/operate/operations/). Enterprise classification remains an optional vendor build input with no chosen cutoff. A free pool parent and read-only enterprise cooldown child can still edit weights/secrets/primary while preserving effective cooldown policy; durations compare by value and status codes as sets. New/enabled entries under active cooldown are new child activation. Parent readonly bounds the entire pool writer, while unrelated free scalar providers retain their ordinary writer. Provider policy, license/trial and candidate version are checked coherently under the control transaction locks; omission or an explicit empty list is not a license bypass. # Capabilities and routes **Last updated:** 2026-11-25T02:26:16-03:00 (UTC-3) A **capability** is something a model (alias) can do: chat, generate an image, transcribe audio. You declare the capabilities of each alias, and the gateway accepts a request only if the alias declares that route's capability. That way, nobody calls `/v1/images/generations` on a text model by mistake and gets an obscure error from the provider: the gateway responds `422 capability_unsupported` before any call. ## Routes and capabilities | Capability | Route | Format | Body limit | Flag | |---|---|---|---|---| | `chat` | `/v1/chat/completions` | Chat Completions, with streaming | 1 MiB | `chat_completions` | | `responses` | `/v1/responses` | OpenAI Responses, with streaming | 8 MiB | `openai_responses` | | `messages` | `/v1/messages` | Anthropic Messages, with streaming | 8 MiB | `anthropic_messages` | | `generate_content` | `/v1beta/models/{alias}:generateContent` and `:streamGenerateContent` | Native Gemini | 8 MiB | `gemini_generate_content` | | `embeddings` | `/v1/embeddings` | JSON | 8 MiB | `embeddings` | | `images` | `/v1/images/generations` | JSON | 8 MiB | `image_generation` | | `image_edits` | `/v1/images/edits` | JSON or multipart with `image`/`image[]` files; see [image generation and edits](/docs/features/image-generation/) | 8 MiB | `image_generation` | | `audio_speech` | `/v1/audio/speech`; `GET /v1/audio/voices` lists voices (`speech_voices`) | JSON; audio response, streamed as it arrives ([speech](/docs/features/speech/)) | 8 MiB | `audio_speech` | | `audio_transcriptions` | `/v1/audio/transcriptions` | multipart with `file` | 8 MiB | `audio_transcriptions` | | `moderations` | `/v1/moderations` | JSON | 8 MiB | `moderations` | | `rerank` | `/v1/rerank` | JSON | 8 MiB | `rerank` | | `video` | `/v1/videos/generations` | JSON | 8 MiB | `video_generation` | | `decisions` | `/v1/decisions` | OpenAI Decisions | 8 MiB | `openai_decisions` | | `systemone` | `/v1/systemone` | System One (TypeSafe, Cloudflare, vLLM Semantic Router) | 8 MiB | `systemone_decisions` | | `gemini_decisions` | `/v1beta/decisions` | Gemini Decisions (`gemini-decision-1`); see [decisions](/docs/features/decisions/#gemini-decisions) | 8 MiB | `gemini_decisions` | | `interactions` | `/v1beta/interactions` and `/v1/interactions` | Gemini Interactions, native on the Gemini API only, alone on the alias; see [file inputs](/docs/features/file-inputs/#the-interactions-api) | 8 MiB | `gemini_interactions` | The body limits are the built-in defaults; `network.max_request_body_mib` changes them for every route and `models[].max_request_body_mib` for one alias (1 to 64 MiB). See [request body limits](/docs/operate/http-input-limits/#request-body-limits). Every route requires a key with the route's scope (`route:chat`, `route:embeddings`...) and the alias on the key's allowlist. An alias without `capabilities` serves only `chat`. ## Declaring capabilities on an alias ```yaml models: - id: assistant capabilities: [chat, responses] targets: [{provider: openai, model: gpt-4.1-mini}] - id: rerank-default capabilities: [rerank] targets: - provider: my-reranker model: bge-reranker paths: {rerank: /rerank} # routes without an OpenAI convention need the path ``` For `video` and `rerank`, which have no standard path in the OpenAI format, the target declares the provider's path in `paths`. Moderation has its own page with requests, the response fields and the errors: [Moderation](/docs/features/moderations/). ## What is translated The gateway swaps the `model` for the provider's name and passes the rest through. When the provider does not speak the route's format, the **protocol adapter** translates the request and the response. Anything without an equivalent is refused with 422 before the call, never silently ignored. The four text routes (Chat Completions, Responses, Messages and GenerateContent) reach every text provider through one canonical format: see [protocol translation](/docs/features/protocol-translation/). | Protocol | Translated capabilities | |---|---| | `openai` | native `chat` and `responses`; `chat` on the Responses API and `responses` on Chat Completions with the target's `api` (`auto` picks per request); `messages` and `generate_content` | | `anthropic` | `chat`, `responses` and `generate_content`, and native `messages` | | `gemini` | `chat`, `messages`, `responses`, native `generate_content`, embeddings (Vertex AI), `audio_speech` on the Gemini API (`speech_gemini`), and native `interactions` on the Gemini API (`gemini_interactions`). File parts and their slices reach it on every one of these routes ([file inputs](/docs/features/file-inputs/)) | | `bedrock` | `chat`, `messages`, `responses` and `generate_content` (Converse), and embeddings | | `cohere` | `chat`, `messages`, `responses` and `generate_content`, `embeddings`, and `rerank` (Cohere v2) | | `sagemaker` | `chat` | | `oci` | `chat` | | `elevenlabs` | `audio_speech` | | `polly` | `audio_speech` (`speech_polly`) | | `azure_speech` | `audio_speech` (`speech_azure`) | | `deepgram` | `audio_transcriptions` | | `stability`, `replicate`, `fal`, `bfl` | `images` | | `runway` | `video`, as an asynchronous job | What each translation covers and refuses is in [providers](/docs/features/providers/). ## Native APIs For SDKs that expect a provider's original format, the gateway serves the native routes without translating when every target of the alias speaks that format: it swaps only the `model` and the credential. An alias with another provider among its targets is translated instead ([protocol translation](/docs/features/protocol-translation/)). ### OpenAI Responses ```yaml features: {openai_responses: true} models: - id: assistant capabilities: [responses] targets: [{provider: openai, model: gpt-4.1-mini}] ``` Tools, stream events, and usage pass through as received. Without the `responses_lifecycle` flag, `previous_response_id` and `conversation` require a single-target alias, and `background: true` is refused. With it, response IDs are signed by the gateway and unlock: - retrieval and cancellation; - background mode; - continuation on aliases with several targets. With `responses_lifecycle` on, a raw provider ID in `previous_response_id` still passes to the provider in single-tenant mode. With [organization admins](/docs/features/organization-admins/) on as well, it answers `404 response_not_found` before the provider, on `/v1/responses` and `/v1/responses/input_tokens`: every organization's responses live in the same provider account, so only the key's own signed IDs continue a response. A provider whose answers lack `"object": "response"` gets no signed IDs, so its responses cannot be continued in that mode. In multi-tenant mode, a request naming stored state the gateway cannot attribute answers `422 provider_state_not_isolated` with the setting that fixes it: a raw `previous_response_id` without `responses_lifecycle`, a raw `conversation` without `conversations`, a container ID without `containers`, an item reference input or a reasoning item by ID without `encrypted_content`, a provider file the request reads (`input_file`/`input_image` `file_id`; a Chat Completions `file` part's `file_id`), and, on `/v1/messages`, a `container` ID (omit it and the provider creates a new container), a `file` source or a `container_upload`, and, on Gemini GenerateContent, a `cachedContent` or a `fileData.fileUri` (contents, system instruction or function response parts). File IDs in replayed output (citations, annotations, code-execution results) are not refused. Responses is never retried automatically, because it may have executed tools. ### Anthropic Messages An alias with `capabilities: [messages]` on an `anthropic` provider serves `/v1/messages` in the native format, with the connection's `anthropic-version` and the gateway's credential. This is the path for Claude Code ([providers](/docs/features/providers/#claude-code)). An Anthropic alias serves one capability: `messages` (native), or `chat`, `responses` or `generate_content` (translated). ### Gemini GenerateContent An alias with `capabilities: [generate_content]` on a `gemini` provider serves `/v1beta/models/{alias}:generateContent` and `:streamGenerateContent?alt=sse` in the native format. The provider key goes only in the `x-goog-api-key` header. The alias is part of the path, so it uses only letters, digits, dots, dashes and underscores, on any provider. ## Conversations With the `conversations` flag, the gateway serves OpenAI's Conversations API and the Responses `conversation` parameter, even on aliases with several targets. - **Gateway IDs:** every conversation comes back as `conv_gw1.…`, a signed ID that carries the provider and the owner, which is the key's team. An ID from another team, tampered with, or raw returns 404 without calling the provider. The signature uses the session key (`admin.session_key_env`); changing that key makes old conversations unreachable. - **Creation:** `POST /v1/conversations` accepts `model` to choose the provider when the key reaches more than one. - **Items:** new items go through the input guardrails. ```python conv = client.conversations.create(items=[{"role": "user", "content": "My name is Ana."}], extra_body={"model": "assistant"}) client.responses.create(model="assistant", conversation=conv.id, input="What is my name?") ``` ## Multimodal and limits - **Chat with image or audio:** the JSON parts pass through as received. The gateway does not fetch URLs or convert media, and the chat body limit (1 MiB unless [configured](/docs/operate/http-input-limits/#request-body-limits)) restricts embedded media. - **Concurrency:** inference shares the configured per-instance generation/body admission limits (`network.max_inflight_requests`, `max_buffered_request_mib`), with a default 512 generation slots. Multipart uploads are read into memory. The optional boot flag `stream_admission` allows separately bounded detached relays; full relay room keeps the generation slot, so the relay cap is not the total open-stream cap. See [network controls](/docs/operate/network-configuration/#stream-relay-admission). - **Fallback:** happens on a transport error, 429, or 5xx before the first byte of the response, and when a target cannot express the request in its protocol (skipped without a call). Stateful `responses` requests are the exception ([Responses fallback](/docs/features/feature-routing/#responses-fallback)). ## Other API families Beyond per-alias capabilities, the gateway also serves: - [Realtime](/docs/features/realtime/), [Files and Batches](/docs/features/batches/), and [fine-tuning](/docs/features/fine-tuning/); - [Containers](/docs/features/containers/) and [vector stores](/docs/features/vector-stores/); - [OCR](/docs/features/ocr/); - [A2A agents](/docs/features/a2a-agents/) and [MCP tools](/docs/features/mcp-execution/); - the public [evals](/docs/features/evals/) API. ## See also - [Providers](/docs/features/providers/): what each adapter covers. - [Protocol translation](/docs/features/protocol-translation/): any client route to any text provider. - [Decisions](/docs/features/decisions/): the bridge between OpenAI Decisions and System One. - [Inference flags](/docs/reference/inference-flags/): the flag for each capability. # Speech **Last updated:** 2026-11-24T12:31:51-03:00 (UTC-3) `POST /v1/audio/speech` turns text into audio. The request is the OpenAI speech request (`model`, `input`, `voice`, and optionally `response_format`, `speed` and `instructions`); the answer is the provider's audio. This page covers how a clip is delivered, what happens when it is cut, how it is charged, how to list voices, and the providers that serve it. ## Turn it on Speech needs the `audio_speech` flag (on by default), an alias with the `audio_speech` capability and a key with the `route:audio_speech` scope. ```yaml features: audio_speech: true providers: - id: openai preset: openai models: - id: tts capabilities: [audio_speech] targets: [{provider: openai, model: tts-1}] ``` ```sh curl -sS https://gateway.example.com/v1/audio/speech \ -H "Authorization: Bearer $GATEWAY_KEY" -H "Content-Type: application/json" \ -d '{"model":"tts","input":"Hello","voice":"alloy"}' -o hello.mp3 ``` Everything below this section is optional and off by default, each part behind its own flag: | Flag | What it enables | |---|---| | `speech_buffer` | `speech.delivery: buffer` on an alias: [whole clips only](#whole-clips-only) | | `speech_voices` | [`GET /v1/audio/voices`](#voice-discovery) | | `speech_polly` | [Amazon Polly](#amazon-polly) targets | | `speech_azure` | [Azure AI Speech](#azure-ai-speech) targets | | `speech_gemini` | [Gemini text to speech](#gemini) targets | All five need `audio_speech`. They are operator controls: set them in the YAML, with `PUT /api/v1/admin/features/{id}`, or on the console's Feature flags page. ## How a clip is delivered The gateway sends each piece of audio to the client as soon as the provider produces it, so playback can start before the clip is complete. Measured with a stand-in provider that sends a 3.0 s clip in 20 pieces, and the request log on PostgreSQL, the client's first byte arrives within 10 ms of the provider's; before this behaviour existed it arrived at 2.4 s, with most of the clip. The answer has no `Content-Length`: it is chunked on HTTP/1.1 and a plain stream on HTTP/2. Nothing needs to be set, and `stream` in the request body is passed to the provider as it is. ## When a clip is cut Three things can stop a clip after it started. The status is already `200` by then, so each is told another way: | What happened | What the client sees | Request log and request event | Provider error count and circuit breaker | |---|---|---|---| | The provider cut the clip | The connection is aborted: an unterminated chunked body on HTTP/1.1, a stream reset on HTTP/2. `curl` exits with an error; an HTTP library raises one | status `200`, `error_code: stream_interrupted`, `truncated: true` | counted (`gateway_provider_errors_total{class="stream_interrupted"}`), one failure of the destination | | The client hung up | Nothing: it left | status `200`, `error_code: client_closed_stream`, `truncated: true`; the log line `stream_copy_failed` with `side: client` | not counted | | The gateway was stopped | The connection is aborted | status `200`, `error_code: stream_aborted` | not counted | A clip that fails before its first byte has put nothing on the wire, so the client gets a plain error instead: `502` with the code `stream_interrupted`, recorded and counted as above with that status. A cut clip is never ended as if it were complete: a client that checks for a transport error cannot take part of a clip for a whole one. A cut clip is a failure everywhere a failure is counted (the request log's error filter, analytics, the error rate, spans and their OTLP export), exactly as a [cut text stream](/docs/features/stream-usage/#what-is-recorded) is. Each record carries the key, principal, team and organization of the request, and reads are filtered by the reader's teams and organization. When the client hangs up, the gateway cancels the provider call instead of reading the rest of the clip. Once audio has started the request is never sent to another target or retried: the client already has part of an answer. ## How a clip is charged A provider that prices speech by the characters of the request (OpenAI `tts-1`, ElevenLabs, Amazon Polly, Azure AI Speech) charges the whole request once it accepts it, whether or not the clip reaches its end. The gateway charges the same way: **from the first audio byte, the request costs its full per-character price**, including when the provider cut the clip and when the client hung up. With [durable receipts](/docs/features/durable-usage/) the receipt is settled, not left unknown. Three cases stay unknown, never zero and never estimated: - the provider answered `200` and cut the clip before any audio byte; - a [buffered](#whole-clips-only) clip answered as an error (`502`, or `499` when the client left): the gateway values only requests that succeeded. A per-character provider has charged such a clip all the same, so read these rows as spend not yet priced, and use `stream` where every cut clip must carry its cost; - a clip priced by tokens ([Gemini](#gemini)) that was cut: the tokens are reported only at its end. The characters counted are those of `input`; Amazon Polly reports the count it billed (`x-amzn-RequestCharacters`) and that count is used instead. A per-character price comes from the price catalog, or from the price book: ```yaml price_book: - provider_id: openai model_id: tts-1 unit: per_character unit_price: "0.000015" source_url: https://openai.com/api/pricing/ effective_from: "2026-01-01T00:00:00Z" ``` ## Whole clips only Some clients cannot use part of a clip: they store the file, or play it only when complete. For them an alias can hold the answer until the provider finished the clip. ```yaml features: speech_buffer: true models: - id: tts-whole capabilities: [audio_speech] speech: delivery: buffer buffer_max_mib: 32 targets: [{provider: openai, model: tts-1}] ``` | Field | Default | Bounds | Meaning | |---|---|---|---| | `models[].speech.delivery` | `stream` | `stream`, `buffer` | `buffer` delivers only whole clips. Read only while `speech_buffer` is on; with the flag off the alias streams | | `models[].speech.buffer_max_mib` | `32` | 1 to 256 | The largest clip kept in memory while it arrives, per request | With `buffer`: - a whole clip is answered with its `Content-Length`, after the provider's last byte. The client waits for the whole clip before its first byte: choose this only when part of a clip is useless; - a clip the provider cut is answered `502` with the code `stream_interrupted`, and no audio byte. It is counted as a provider error and as one failure of the destination, and its cost is recorded as unknown ([how a clip is charged](#how-a-clip-is-charged)); - a clip longer than `buffer_max_mib` is answered `502` with the code `speech_buffer_exceeded`. Raise the limit, or use `stream`; - a client that hangs up while the clip arrives cancels the provider call, and the request is recorded with status `499`. Size the limit for your longest clip and your concurrency: each buffered request holds its clip in memory, up to the limit. One minute of MP3 at 128 kbit/s is about 1 MiB; one minute of 24 kHz PCM is about 2.8 MiB. The setting is per alias, so one deployment can stream on one alias and buffer on another with the same provider. It is set in the YAML, in the alias sent to `PUT /api/v1/admin/models/{id}`, or in the console's model editor under **Speech**. It is refused on an alias without the `audio_speech` capability, on an auto route and on an `alias_of` entry. A change applies to the next request, with no restart. ## Voice discovery `GET /v1/audio/voices` lists the voices of the speech aliases a key may use, with the provider and provider model each voice belongs to. Add `?model=` for one alias. ```yaml features: speech_voices: true ``` ```sh curl -sS "https://gateway.example.com/v1/audio/voices?model=tts" -H "Authorization: Bearer $GATEWAY_KEY" ``` ```json { "object": "list", "data": [ {"id": "alloy", "model": "tts", "provider": "openai", "source": "built_in"}, {"id": "Joanna", "name": "Joanna", "model": "tts-polly", "provider": "polly", "languages": ["en-US"], "gender": "female", "source": "provider"} ], "unavailable": [ {"model": "tts-local", "provider": "kokoro", "reason": "unknown_model"} ] } ``` Send a voice's `id` as `voice` on `/v1/audio/speech`. `provider` is the connection ID, the value of `X-Gateway-Provider` on an answer. Each entry also has `provider_model`, the target's model, only when the operator shows it on inference answers (`server.response_headers.served_target: true`, [response headers](/docs/features/response-headers/)); by default a key learns the connection and not the model behind the alias. Where each list comes from, in this order: | `source` | Used for | Where it comes from | |---|---|---| | `declared` | Any alias with `speech.voices` | The alias's own list. Use it for a self-hosted speech server, or to show a subset | | `provider` | ElevenLabs, Amazon Polly, Azure AI Speech | The provider's voice list, read with the connection's credential. Polly is asked for the voices of the target's engine. The credential must be allowed to list voices: an ElevenLabs key needs the `voices_read` permission, an AWS identity `polly:DescribeVoices`; without it the target is `provider_unavailable` | | `built_in` | OpenAI `tts-1`, `tts-1-hd`, `gpt-4o-mini-tts`; Gemini | The voices the provider documents for the model. These providers have no route that lists them | ```yaml models: - id: tts-local capabilities: [audio_speech] speech: voices: [af_heart, bm_george] targets: [{provider: kokoro, model: kokoro}] ``` `models[].speech.voices` takes up to 256 unique names of 1 to 128 letters, digits, dots, underscores, colons or hyphens. A target that cannot be listed is in `unavailable` with a `reason`: `unknown_model` (no list exists for the model: declare `speech.voices`), `provider_disabled` (the flag of the target's speech provider is off) or `provider_unavailable` (the provider's list could not be read; the next request tries again). What to know: - The key needs the `route:audio_speech` scope, and sees only aliases it may use. An alias it may not use, one that does not serve speech and one that does not exist all answer `404 model_not_found`. - A provider's list is kept in memory for five minutes on each replica. A new voice at the provider appears after at most that long. A list that could not be read is remembered for 30 seconds, so a provider that is down is not called by every request; one listing waits 10 seconds at most, whatever its number of targets. - The listing is not an inference request: nothing is charged, and no request log row is written. The request line in the log carries the key, principal, team and organization. - Listing a voice grants nothing. The speech route applies its own checks to every request. - In the console, the Playground's Speech tab suggests the alias's voices when `speech_voices` is on and a typed gateway key is in use; any voice name can still be typed. ## Providers | Provider | Protocol | Flag | Target `model` | `voice` | `response_format` | `speed` | Priced by | |---|---|---|---|---|---|---|---| | OpenAI and compatible servers | `openai` | `audio_speech` | The speech model | The provider's | Passed through | Passed through | Characters | | ElevenLabs | `elevenlabs` | `audio_speech` | The model ID | A voice ID | `mp3`, `opus`, `pcm` | 0.7 to 1.2 | Characters | | Amazon Polly | `polly` | `speech_polly` | The engine | A Polly voice ID | `mp3`, `opus` | Refused | Characters Polly bills | | Azure AI Speech | `azure_speech` | `speech_azure` | Your name for the price tier | A voice short name | `mp3`, `opus`, `pcm`, `wav` | 0.5 to 2 | Characters | | Gemini | `gemini` | `speech_gemini` | The TTS model | A prebuilt voice | `pcm`, `wav` | Refused | Tokens | `instructions` is passed through on `openai` targets, becomes the spoken direction on Gemini, and is refused on ElevenLabs, Amazon Polly and Azure AI Speech. The request is always the OpenAI one. A member the provider has no equivalent for is refused with `422 unsupported_on_provider` before anything is sent, never dropped or approximated. A target whose flag is off answers `404 feature_disabled`. An alias on `polly` or `azure_speech` serves `audio_speech` and nothing else. On `gemini`, an alias with `audio_speech` as its only capability is a speech alias. ### Amazon Polly Polly's [SynthesizeSpeech](https://docs.aws.amazon.com/polly/latest/dg/API_SynthesizeSpeech.html), signed with SigV4 for the `polly` service. The target's `model` is the engine: `standard`, `neural`, `long-form` or `generative`. ```yaml features: speech_polly: true providers: - id: polly protocol: polly base_url: https://polly.us-east-1.amazonaws.com auth: {type: aws_sigv4, region: us-east-1} models: - id: tts-polly capabilities: [audio_speech] targets: [{provider: polly, model: neural}] ``` - The base URL must be `https://polly..amazonaws.com` (`.amazonaws.com.cn` in the China regions; the FIPS hosts are accepted), and `auth.region` must be that region: a signature is sent to no other host. Credentials come from the usual AWS chain ([provider credentials](/docs/features/providers/)); the identity needs `polly:SynthesizeSpeech`, and `polly:DescribeVoices` for voice discovery. - `voice` is a Polly voice ID such as `Joanna` or `Camila`. Not every voice has every engine; Polly refuses a pair it does not have. - `input` is 1 to 3,000 characters, sent as plain text (not SSML). - `response_format` is `mp3` (default) or `opus` (Ogg Opus). `pcm` is refused: Polly's PCM is 8 or 16 kHz and OpenAI's is 24 kHz. - Prices differ per engine: give each engine its own price book entry, with `model_id` the engine. ### Azure AI Speech The Speech service's [text to speech REST API](https://learn.microsoft.com/azure/ai-services/speech-service/rest-text-to-speech). The gateway builds the SSML from `input`, `voice` and `speed`. ```yaml features: speech_azure: true providers: - id: azure-speech protocol: azure_speech base_url: https://eastus.tts.speech.microsoft.com api_key_env: AZURE_SPEECH_KEY auth: {type: header, header: Ocp-Apim-Subscription-Key} models: - id: tts-azure capabilities: [audio_speech] targets: [{provider: azure-speech, model: neural}] ``` - The base URL is your region's endpoint, or your resource's custom domain. The resource key goes in `Ocp-Apim-Subscription-Key`. A bearer token is also accepted (`auth.type: bearer`), but Azure's tokens last ten minutes and the gateway does not renew them: use the key unless you rotate the token yourself. - `voice` is a voice short name such as `en-US-AvaMultilingualNeural` or `pt-BR-FranciscaNeural`. Its first two parts are the language of the SSML. - `input` is spoken as plain text: markup in it is escaped, not interpreted. - `response_format`: `mp3` (default; 24 kHz, 48 kbit/s), `opus` (Ogg, 24 kHz), `pcm` (raw 24 kHz 16-bit mono) or `wav` (the same PCM in a RIFF file). - `speed` from 0.5 to 2 becomes the prosody rate. - Azure has no model parameter: the voice decides the tier. The target's `model` is the name you price by; use one alias per tier (for example `neural` and `neural-hd`) when their prices differ. ### Gemini Gemini's [speech generation](https://ai.google.dev/gemini-api/docs/speech-generation) on the Gemini API (not on Vertex AI). The gateway asks for a streamed answer and relays the audio as it arrives. ```yaml features: speech_gemini: true providers: - id: gemini preset: gemini models: - id: tts-gemini capabilities: [audio_speech] targets: [{provider: gemini, model: gemini-2.5-flash-preview-tts}] ``` ```sh curl -sS https://gateway.example.com/v1/audio/speech \ -H "Authorization: Bearer $GATEWAY_KEY" -H "Content-Type: application/json" \ -d '{"model":"tts-gemini","input":"Hello","voice":"Kore","response_format":"wav"}' -o hello.wav ``` - `response_format` is required and must be `pcm` or `wav`. Gemini returns 24 kHz 16-bit mono PCM and the gateway does not transcode; `mp3`, the OpenAI default, is refused. `pcm` is the raw samples (`audio/pcm;rate=24000`), the same format as OpenAI's `pcm`. `wav` is those samples behind a RIFF header whose sizes are the maximum value, as in any streamed WAV file; players accept it, and a tool that needs exact sizes should take `pcm`. - `voice` is one of Gemini's 30 prebuilt voices, such as `Kore` or `Puck`; [voice discovery](#voice-discovery) lists them. - The text is sent as `Say: `, the form Gemini's speech models are prompted in: given a bare short text, the model treats it as a message to answer and refuses the request. With `instructions`, they replace `Say` as the direction (`"instructions": "Speak slowly and warmly"` sends `Speak slowly and warmly: `); up to 1,000 characters. The direction is part of the prompt Gemini bills. - `speed` is refused; describe the pace in `instructions`. One speaker per request. - The clip is charged by the tokens Gemini reports at its end, at the model's input and output prices (the output price of a TTS model is its audio price). The request log shows both counts. A cut clip has no usage, so its cost is unknown. - A text Gemini refuses to speak (a blocked prompt, a safety stop) is answered `422` with the code `speech_refused` when no audio was sent yet. It is the request's outcome: no provider error is counted and the circuit of the destination is untouched. A clip Gemini stops for its content after it started is aborted like a cut clip and recorded with `error_code: stream_aborted`, also without blaming the destination. - A stream that fails before any audio is answered `502`, counted as a provider failure, and the alias's next target is tried when there is one. A stream that ends without Gemini's `STOP`, or with an error event, after audio started is a cut clip. - With `speech.delivery: buffer`, a `wav` clip carries its real sizes. ## Limits - The gateway does not convert audio formats or sample rates. - Speech requests take no part in token budgets; their cost is in the request log and the cost reports. - The Playground lists voices only with a typed gateway key; with the console session it suggests OpenAI's voices and accepts any typed name. # File inputs and file slicing **Last updated:** 2026-11-25T06:38:11-03:00 (UTC-3) Gemini reads documents, spreadsheets, images, audio and video as part of a request, and bills only the part of a file it is told to read: a page range of a PDF, one sheet of a workbook, a lower resolution. Sending pages 3 and 4 of a six-page PDF instead of the whole file cut the prompt from 3,133 to 1,053 tokens in a measured call through the gateway (`gemini-3.5-flash-lite`, 2026-11-25). This page explains how to send a file to a Gemini target on each route, how to give an alias a default slice so no caller pays for a whole file by accident, how such requests are priced and reserved, and how to use the Gemini Interactions API. Slicing is done by the provider; the gateway carries the fields, checks them before any call and accounts for the result. It works on Gemini 3 and later models. ## Which route to use | You send | Route | What you need | |---|---|---| | Gemini's own request | `POST /v1beta/models/{alias}:generateContent` (and `:streamGenerateContent`) | `gemini_generate_content` (on by default). The body passes through, slice included | | An OpenAI-style request | `POST /v1/chat/completions`, `POST /v1/responses` | `gemini_file_inputs` (it also prices and reserves file requests on GenerateContent) | | Gemini's Interactions request | `POST /v1beta/interactions`, `POST /v1/interactions` | `gemini_interactions` | | Nothing: the alias decides | any of the above | `gemini_file_defaults` and `models[].file_defaults` | All three new flags are off by default. Turn on only what you use: ```yaml features: gemini_file_inputs: true # file parts on Chat Completions and Responses gemini_file_defaults: true # apply models[].file_defaults gemini_interactions: true # the Interactions API routes ``` ## Send a file on Chat Completions With `gemini_file_inputs`, a Gemini target accepts a `file` content part in a user message: ```json { "model": "docs", "messages": [{ "role": "user", "content": [ {"type": "text", "text": "Summarize the chart on pages 3 and 4."}, {"type": "file", "file": { "file_data": "data:application/pdf;base64,JVBERi0xLjQK...", "document_metadata": {"start_page": 3, "end_page": 4}, "resolution": "low" }} ] }] } ``` The members of `file`: | Member | Meaning | |---|---| | `file_data` | The file inline: base64, or a base64 data URL that names its type | | `file_id` or `file_url` | A reference the provider reads itself: a `gs://` object or a Files API URI. See [references](#references). Exactly one of `file_data`, `file_id` and `file_url` is required | | `format` | The MIME type. Required when nothing else names it: a data URL, or the extension of `filename` or of a `gs://` path, names it too | | `filename` | Used only to find the type | | `document_metadata` | For PDF, Word, PowerPoint and OpenDocument files: `start_page` and `end_page` (1-indexed, inclusive, 1 to 2,000; one alone is valid) and `content_layers`, a list of `page_image` and `page_text`. A sliced document is read as page images unless you list `page_text` | | `spreadsheet_metadata` | For Excel and OpenDocument spreadsheets: `sheet_index` (1-indexed, in tab order), `visible_cells` (an A1-style cell or range such as `A1:G40`) and `content_layers`, a list of `data`, `formulas` and `visual` | | `video_metadata` | For video: `start_offset` and `end_offset` (seconds, as `"90s"`) and `fps` (above 0, up to 24) | | `resolution` | `low`, `medium` or `high`; `ultra_high` for images only. A page or an image costs about 280, 560 or 1,120 tokens | The gateway sends Gemini's own part: `inlineData` or `fileData` with `documentMetadata`, `spreadsheetMetadata`, `videoMetadata` and `mediaResolution`. A file part that is malformed, of a type Gemini does not read, sliced with the wrong kind of metadata, or referenced without approval is refused with `422 unsupported_on_provider` and a message naming the member, before any provider call. A tool can return a file too. Put the `file` part in the tool message's content, beside its text; it reaches Gemini inside the function response: ```json {"role": "tool", "tool_call_id": "call_1", "content": [ {"type": "text", "text": "attached"}, {"type": "file", "file": {"file_data": "data:application/pdf;base64,...", "document_metadata": {"start_page": 5, "end_page": 5}}} ]} ``` Files are accepted in user and tool messages only. Streaming works the same way. ### On Responses On `POST /v1/responses` routed to a Gemini target, an `input_file` part carries the same members, flat on the part, in a user message or a `function_call_output`: ```json {"type": "input_file", "file_data": "data:application/pdf;base64,...", "document_metadata": {"start_page": 3, "end_page": 4}} ``` ### On a target that is not Gemini No other provider slices a file. With `gemini_file_inputs` on, a request that names a slice and reaches another target follows the alias's [`unsupported_parameters`](/docs/features/request-parameter-policy/): - `refuse` (the default): `422 unsupported_on_provider`, naming the first slice field (`file.document_metadata is not supported by this provider`). The whole file is never billed for a request that asked for a few pages. - `drop`: the slice fields are removed, the file is sent whole, and `X-Gateway-Dropped-Parameters` lists what was removed (`file.document_metadata,file.resolution`). ## References A reference is a file the provider fetches itself. It is accepted only under a prefix you approve, because the provider reads it with the gateway's own credentials or from the gateway's own provider project: ```yaml file_inputs: reference_prefixes: - gs://acme-docs/reports/ # a storage prefix, ending in / - https://generativelanguage.googleapis.com/v1beta/files/ # files uploaded to the Files API page_tokens: 560 ``` | Setting | Default | Meaning | |---|---|---| | `file_inputs.reference_prefixes` | empty | Up to 64 entries: `gs://bucket/` or `gs://bucket/path/` prefixes, and the Files API prefix (`…/v1beta/files/` or `…/v1/files/`; either one allows both spellings). Empty means every file is sent inline | | `file_inputs.page_tokens` | 560 | The tokens a budget reserves per page at medium resolution (64 to 8,192). See [budgets](#budgets-and-token-ceilings) | Both are read on every request, so a configuration change applies without a restart. The console shows them, read-only, under **Routing status → File inputs**, and `GET /api/v1/admin/file-inputs` returns them with the flags and the aliases that set defaults (permission `providers:read`). A `gs://` reference needs a type: `format`, or a path with a known extension. A path with a `..` segment is refused. Storage objects are read by Vertex AI targets; the Gemini API reads Files API URIs. On GenerateContent, a file search tool (`tools[].fileSearch`) reads a store of the provider project in the same way: with organizations it is refused with `422 provider_state_not_isolated`. There is no per-organization allow-list of stores; send the content in the request. **With organizations.** When [organizations](/docs/features/organization-admins/) share the gateway, they share the provider project too, and a Files API URI names a file any of them could have uploaded. Such a URI is refused with `422`, whatever the prefixes say, on every route (`provider_state_not_isolated`; `unsupported_on_provider` when it comes in `file_url`); send the file inline instead. In that mode `file_id` is refused for every value, so name an approved storage object in `file_url`. ## Give an alias a default slice `models[].file_defaults` is the slice and resolution a file part gets when the request names none. It is a cost control: a caller that attaches a 300-page PDF without thinking pays for the first 20 pages at low resolution, not for all of it. ```yaml models: - id: docs file_defaults: resolution: low start_page: 1 end_page: 20 targets: - provider: gemini model: gemini-3.5-flash-lite ``` | Field | Bounds | Applies to | |---|---|---| | `resolution` | `low`, `medium`, `high` | Documents, spreadsheets, images and video that name no resolution | | `start_page`, `end_page` | 1 to 2,000, `end_page` not before `start_page` | Documents that name no `document_metadata` | | `document_layers` | `page_image`, `page_text` | Documents that name no `document_metadata` | | `sheet_index` | 1 to 10,000 | Spreadsheets that name no `spreadsheet_metadata` | | `visible_cells` | An A1-style cell or range | Spreadsheets that name no `spreadsheet_metadata` | | `spreadsheet_layers` | `data`, `formulas`, `visual` | Spreadsheets that name no `spreadsheet_metadata` | How it behaves: - It applies only while `gemini_file_defaults` is on. The value is validated either way, so turning the flag on never activates an invalid one. - What the request names always wins. A part with its own page range keeps it; the default resolution is still added if the part names none. - It applies on every route to a Gemini target: GenerateContent, Chat Completions and Responses (with `gemini_file_inputs`), and Interactions. - When a default changed a part, the answer carries `X-Gateway-File-Defaults: applied`, so a slice the caller did not ask for is never silent. - On GenerateContent a request that sets `generationConfig.mediaResolution` keeps that choice for every part. A GenerateContent body that repeats a member name is refused with `400` on an alias with defaults. - A file part must declare its type on an alias with defaults, since the default is chosen by type: one that does not is refused with `422` (`file_type_required` on GenerateContent and Interactions, `unsupported_on_provider` on the translated routes). - It is set in YAML, through `PUT /api/v1/admin/models/{id}` and in the console's model editor (**File defaults**). It is not allowed on an `auto_route` or `alias_of` entry, and needs at least one field. ## What a file request costs With [usage valuation](/docs/features/usage-valuation/) and `gemini_file_inputs` on, a request with a file is priced from the usage the provider reports by modality, on GenerateContent and on the translated routes; an Interactions request is priced the same way under `gemini_interactions`. Without the flag a GenerateContent request with a file part keeps the cost `unknown`, as before. | The file is read as | Priced at | |---|---| | Text: text files, a document's `page_text` layer alone, a spreadsheet's cells | The input price | | Images: an image, a document's pages, a spreadsheet's `visual` layer | The input price on the Gemini API and Vertex AI, where images bill as input; elsewhere the rate's image input price | | Audio, video | The rate's audio or video input price | The cost stays `unknown`, never a guess, when a file part declares no type (`non_text_or_stateful_profile`), when the rate publishes no price for a modality the request sends (`media_token_unpriced`), or when the answer's usage does not count a modality the request sent (`media_usage_unreported`). To get a cost, declare the type: `format` on the OpenAI-style routes, `mimeType` on GenerateContent, `mime_type` on Interactions. The request span records how many file parts named a slice (`file_slices` in the [structure](/docs/features/content-capture/), `gateway.structure.file_slices` over OTLP), with no content. ## Budgets and token ceilings A [budget or token ceiling](/docs/features/budgets-and-tpm/) reserves a request's cost before the call, so it needs a bound the gateway can check. A file has one in a single case: **an inline PDF with a closed page range whose layers name `page_image` alone** (`document_metadata: {start_page, end_page, content_layers: ["page_image"]}`). The gateway holds the bytes and checks they are a PDF; the provider clamps the range to the pages that exist; and a page image costs a fixed number of tokens at its resolution. The layer must be written out, so the bound rests on the request and not on a provider default. Each such page is reserved like an image, at the larger of the rate's per-image ceiling (`image_input_tokens`) and `file_inputs.page_tokens` for its resolution: half of it at `low`, twice at `high`. The charge settles on the usage the answer reports. The rate must approve an image ceiling, as for any [image input](/docs/features/quota-protocols/). Every other file keeps the request out of the protected profile and is refused with `422 quota_profile_unsupported` (reason `media_input_not_bounded`): a reference, whose real type and size cannot be checked before the provider reads it; an open range; a range that names no layer, or the `page_text` layer, whose tokens follow the page's own text; office documents, spreadsheets, audio and video. An alias default makes requests bounded without the caller's help: with `file_defaults: {start_page: 1, end_page: 20, document_layers: [page_image]}`, an inline PDF sent with no slice is reserved as 20 pages. On Chat Completions and GenerateContent this needs `gemini_file_inputs`; the Interactions API has [its own profile](#under-a-budget-or-token-ceiling). ## The Interactions API The Interactions API is Gemini's current generation interface. With `gemini_interactions`, the gateway serves it natively: the body passes through with only `model` replaced, so everything works as the provider documents it, the file slice included. ```yaml features: gemini_interactions: true models: - id: docs capabilities: [interactions] # alone on the alias targets: - provider: gemini # the Gemini API; not Vertex AI model: gemini-3.5-flash-lite keys: - id: app scopes: [route:interactions] ``` ```bash curl https://gateway.example.com/v1beta/interactions \ -H "x-goog-api-key: $GATEWAY_KEY" -H "Content-Type: application/json" \ -d '{ "model": "docs", "input": [ {"type": "text", "text": "Summarize the chart on pages 3 and 4."}, {"type": "document", "data": "JVBERi0xLjQK...", "mime_type": "application/pdf", "resolution": "low", "processing": {"type": "static", "page_options": {"start_page": 3, "end_page": 4}}} ] }' ``` The key goes in `x-goog-api-key` or `Authorization: Bearer`, never in `?key=`. `/v1/interactions` is the same route. With `"stream": true` the answer is the provider's event stream: `interaction.created`, `step.start`, `step.delta`, `step.stop`, `interaction.completed` with the usage, then `done`. ### Stored interactions The provider stores an interaction unless the request says `"store": false`, and its ID alone reads, continues, cancels or deletes it. Every key of the gateway shares one provider project, so the gateway never accepts the provider's ID from a caller it cannot attribute it to. The `id` in an answer is the gateway's own (`int_gw1.…`), signed to the key that created it. It is signed, not encrypted: it proves which key may use it and is not a secret. | Call | Behavior | |---|---| | `"previous_interaction_id": "int_gw1.…"` | Continues the interaction at the provider that holds it. Another key's ID, or a tampered one, answers `404 interaction_not_found` without a provider call | | `GET /v1beta/interactions/{id}` | Reads it. No tokens are billed | | `POST /v1beta/interactions/{id}/cancel` | Cancels it | | `DELETE /v1beta/interactions/{id}` | Deletes it | The same three exist under `/v1/interactions/{id}`. The provider's own ID is accepted in `previous_interaction_id` only when the gateway has one tenant; with organizations it is refused like a foreign ID. The IDs are signed with the console session secret, as stored responses are, so they survive a restart and work on every replica; without a configured secret a per-process key is used, and IDs last until the process restarts. A request with `store: false` and no `previous_interaction_id` keeps nothing at the provider; it falls back to the alias's next target on a 429 or 5xx, like any stateless call (a retry policy is not available on an `interactions` alias). Any other request is one send to one provider, and an alias with several targets refuses it with `422 stateless_fallback_needed` unless it continues an interaction. ### Background interactions With `"background": true` the provider answers at once with the interaction `in_progress` and runs it afterwards. The answer carries the signed ID; read it with `GET /v1beta/interactions/{id}` until its `status` is no longer `in_progress`, or stop it with `POST …/cancel`. A background interaction must be stored (`store: false` is refused) and is not streamed. `webhook_config` is refused with `422 webhook_unsupported`. The provider would post the result straight to the caller's URL, around the gateway, with its own interaction ID: nothing on that path can be verified, attributed to a tenant or kept from naming provider state. Poll the interaction instead. ### Agents and remote environments An agent interaction (`agent`, `agent_config`) and a remote environment (`environment`, `environment_id`) run tools and code at the provider. The gateway's guardrails, tool policies and egress controls see none of it, so both are refused with `422 agents_disabled` unless you turn on `gemini_interactions_agents` (off by default, an operator control; it needs `gemini_interactions`). Read the [threat note](/docs/security/threat-model/#agent-interactions-t199) first. With the flag on, the request names the agent where it would name a model: `{"agent": "research", "input": "…", "background": true}`. `research` is a gateway alias with the `interactions` capability whose target model is the provider's agent ID. A request names a model or an agent, not both. The cost of an agent interaction is `unknown` (its tools bill per use) and it is not admitted under a budget. With organizations, `environment` and `environment_id` are refused whatever the flag says (a remote environment is state in the shared project), and so is an `agent_config` that names a store or a file. ### Guardrails [Guardrails](/docs/features/guardrails/) apply to this route as to the others. - **Input.** The system instruction and every text of the input are checked in order: text blocks, the content of turns, and tool results (`function_result`), whether the result is a string, a list or a structured value (every string in it is checked). A mask rewrites the text the provider receives; a block refuses the request. Media blocks and function call arguments are not inspected. An input the guardrails cannot read (an item that is not an object, nesting deeper than the documented shapes) is refused with `400 invalid_request` instead of sent on unchecked. - **Output.** The text of every `model_output` step is checked on the whole answer. A blocked answer is the guardrail's refusal as a completed interaction. - **Streaming.** With an output guardrail on the alias, a request with `"stream": true` is sent to the provider without streaming, checked whole, and then delivered as the stream's events (`interaction.created`, each step with its text in one delta, `interaction.completed`, `done`). The text arrives at once instead of token by token; that is the price of checking all of it first. - **An enforcing output guardrail needs the answer to exist nowhere else.** The gateway sends such a request with `store: false`, and refuses `store: true`, `previous_interaction_id` and `background: true` with `400 guardrail_output_unsupported`: a stored interaction keeps the original answer at the provider, readable by its ID. Send the history in `input` instead. A guardrail that only monitors never changes the answer or what may be stored; a streamed answer is still read whole before it is delivered, so the monitor sees all of it. ### Under a budget or token ceiling With `quota_native_protocols`, an `interactions` alias is admitted under a [budget or token ceiling](/docs/features/budgets-and-tpm/) when the request is bounded: | Part | Rule | |---|---| | Input | Text: a string, text blocks, turns and function results made of text, function calls. An inline PDF with a closed page range that names `page_image` alone adds its pages, as [above](#budgets-and-token-ceilings) | | Output | `generation_config.max_output_tokens` is required. It includes thought tokens: a limit of 24 with high thinking ended at 19 thought tokens and 1 output token | | Tools | Function tools only | | Tier | `service_tier` absent, `standard`, `flex`, `priority` or `batch` | | Stream | Needs `quota_streaming` and `stream_usage`, as on the other routes | The reservation settles on the usage of the answer: the JSON object, or the stream's `interaction.completed` event. An answer that stopped at its output limit (`status: incomplete`) or ended in a function call for the client to run (`status: requires_action`) is measured like a completed one. The policy's item, tool and content-part limits apply to the input list, the tools and the widest turn. Refused with `422 quota_profile_unsupported`: a continuation (`stored_history_not_bounded`: the provider adds the stored history to the input), an agent (`agent_not_bounded`), hosted tools, media other than the bounded PDF, and any member outside the profile. **Background.** With `quota_background_responses` on, a background interaction is admitted too. Its reservation stays open until the interaction ends: the gateway settles it from the stored interaction when the caller reads or cancels it, and a worker polls the ones nobody read (`charge_accounting.background_poll_seconds`); past `background_max_age_seconds` the reservation is held as unknown for reconciliation. A completed or incomplete interaction settles on its usage; a failed or cancelled one settles on the usage it reports, and is held as unknown without one. `DELETE` on an interaction whose reservation is still open answers `409 background_interaction_pending`. Without that flag a background interaction under a budget is refused (`background_tracking_disabled`). Tracking needs the PostgreSQL store, and rows are bound to the key and team that created the interaction. Without a budget, a background create is recorded with no usage and an `unknown` cost: the tokens exist only in the stored interaction. ### What is refused Before any provider call: | Request | Answer | |---|---| | `agent`, `agent_config`, `environment`, `environment_id` without `gemini_interactions_agents` | `422 agents_disabled` | | `webhook_config` | `422 webhook_unsupported` | | `background: true` with `store: false` or `stream: true` | `422 background_unsupported` | | A member spelled in lowerCamel (`previousInteractionId`) | `400 member_spelling`: the API's members are snake_case, and a twin could bypass the checks above | | An `input` that is a single object | `400 invalid_interaction`: send a string or a list | | With organizations: a Files API file anywhere in `input` (a `uri` on the API's host or a `files/` name), a `file_search` tool or a tool that names a store, a `continuation_token`, an `environment_id` | `422 provider_state_not_isolated` | | A provider answer the gateway cannot read to sign its ID | `502 invalid_provider_response`: withheld, never relayed as it came | | A body that repeats a member name | `400 invalid_request` | | A stored, continued or background interaction on an alias with an enforcing output guardrail | `400 guardrail_output_unsupported` | ### Cost An interaction is valued from its `usage`: `total_input_tokens` as input, `total_output_tokens` plus `total_thought_tokens` as output, `total_cached_tokens` as cache reads, and `input_tokens_by_modality` by modality, with the rules of the table above. Hosted tools (search, code execution and the like), tool-use tokens and grounding leave the cost `unknown`. The request log names the operation `interactions`. ## Limits - Files in system and assistant messages are refused on the translated routes. - On Chat Completions and Responses a reference must be a `gs://` object or a Files API URI; any other URL is refused, and the gateway does not download files. - The provider's own limits apply: 50 MB per file, 1,000 pages per PDF, 2,000 pages or slides per office document, 50,000 cells per sheet. Page limits apply to the whole file even when you slice it. - A `start_page` past the last page returns an empty slice; an `end_page` past it is clamped. # Protocol translation **Last updated:** 2026-11-27T10:53:03-03:00 (UTC-3) Clients speak four API dialects: OpenAI Chat Completions, OpenAI Responses, Anthropic Messages and Google Gemini GenerateContent. Providers speak six: those four plus Cohere v2 and AWS Bedrock Converse. The gateway lets any of the four client routes reach any of the six providers, so a Messages client (Claude Code, the Anthropic SDKs) can use a GPT, Gemini or Bedrock model, and a Responses client can use Claude, without changing the client. ## How it works Every translation goes through one **canonical format**: the Chat Completions request, response and stream the chat route already speaks, with the gateway's extensions for reasoning text (`reasoning_content`), cached prompt tokens and reasoning tokens. - Each client route has a **decoder** (its request to the canonical format) and an **encoder** (the canonical answer, stream and errors back to its own shape). - Each provider has one **encoder** (canonical to its API and back), the same one the chat route uses. Four decoders and six encoders instead of 24 hand-written pairs. A translated request runs the whole chat pipeline: guardrails, budgets and TPM, semantic cache, admission, circuit breaker, fallback, usage and live evaluation. | Client route | Native target | Reaches through translation | |---|---|---| | `POST /v1/chat/completions` | `openai` | `openai` with `api: responses` (or `auto`, per request), `anthropic`, `gemini`, `cohere`, `bedrock` (and `sagemaker`, `oci`) | | `POST /v1/responses` | `openai` | `openai` with `api: chat_completions`, `anthropic`, `gemini`, `cohere`, `bedrock` | | `POST /v1/messages` | `anthropic` | `openai` (either API), `gemini`, `cohere`, `bedrock` | | `POST /v1beta/models/{alias}:generateContent`, `:streamGenerateContent?alt=sse` | `gemini` | `openai` (either API), `anthropic`, `cohere`, `bedrock` | ## Configure it Declare the route's capability on an alias whose target is another provider. The declaration is the opt-in: there is no extra flag beyond the route's own (`anthropic_messages`, `openai_responses`, `gemini_generate_content`). ```yaml features: {anthropic_messages: true, openai_responses: true, gemini_generate_content: true} models: # Claude Code against a GPT model. - id: coder capabilities: [messages] targets: [{provider: openai, model: gpt-5}] # A Responses client against Claude. - id: assistant capabilities: [responses] targets: [{provider: anthropic, model: claude-sonnet-4-5}] # A Gemini SDK against a model on Bedrock. - id: travel capabilities: [generate_content] targets: [{provider: bedrock, model: amazon.nova-lite-v1:0}] ``` - An alias whose targets all speak the route's dialect natively keeps the native passthrough, byte for byte. - If **any** target is not native, **every** target of that alias goes through the canonical format, so a fallback never switches dialect in the middle of a request. - `anthropic`, `gemini`, `cohere` and `bedrock` aliases keep one capability per alias. SageMaker and OCI stay chat only. ### OpenAI targets: Chat Completions or Responses An `openai` target speaks one of two OpenAI APIs, chosen with `api`: ```yaml models: # A chat client against a model that only exists on the Responses API. - id: deep capabilities: [chat] targets: [{provider: openai, model: o3-pro, api: responses}] # A Responses client against a server that only has /chat/completions. - id: local-agent capabilities: [responses] targets: [{provider: vllm, model: qwen3, api: chat_completions}] ``` The default is `responses` on a `responses` alias and `chat_completions` everywhere else. On the Responses API the gateway sends `store: false` unless the chat client asked to store, because a chat client does not expect the provider to keep the conversation. ### `api: auto`: the API chosen per request Current OpenAI reasoning models accept some requests only on the Responses API, while most clients and most requests are fine on Chat Completions. With `api: chat_completions` those requests fail with the provider's 400; with `api: responses` every request pays the translation and its refusals (`stop`, `n`, `logprobs`, ...). `api: auto` sends each request to the API it needs: ```yaml models: - id: reasoning capabilities: [chat, messages] targets: [{provider: openai, model: gpt-6-luna, api: auto}] ``` The decision is made for each attempt, on the body that attempt would send: the client's request after the target's [request parameter policy](/docs/features/request-parameter-policy/). The first matching row wins. | # | The attempt's body | API | `wire_api_reason` | |---|---|---|---| | 1 | `reasoning_effort` is an object (`{effort, summary}`), set by the target's `request_defaults` or `request_overrides` | Responses | `reasoning_effort_object` | | 2 | `reasoning_effort: max` | Responses | `reasoning_effort_max` | | 3 | A `function` tool, and `reasoning_effort` other than `none` | Responses | `tools_with_reasoning_effort` | | 4 | Rows 1–3 match, but the Responses translation would refuse a field (`n`, `stop`, `logprobs`, `seed`, a non-function tool, ...), `unsupported_parameters: drop` would remove one, or a message, content part, tool call, tool or `response_format` has a non-empty member the translation does not map (a message `name` or `refusal` text, `annotations`, a part's `cache_control`, ...); empty members (`null`, `[]`, `""`, `{}`) and a tool call's stream `index` are ignored | Chat Completions | `responses_translation_refused` | | 5 | Anything else, including a client's own `reasoning_effort` object, tools without `reasoning_effort`, and `reasoning_effort: none` | Chat Completions | `chat_completions_sufficient` | Why these rows: - **Rows 2 and 3 are what Chat Completions refuses.** Measured on 2026-11-08 against `gpt-5.4-nano` and `gpt-6-luna`: Chat Completions answered 400 to `reasoning_effort: max` ("Supported values are: 'none', 'low', 'medium', 'high', and 'xhigh'") and to function tools with any effort but `none` ("use /v1/responses or set reasoning_effort to 'none'"); the Responses API accepted both. The [Chat Completions reference](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create) lists `max` among the values and warns that not every model supports every value; the [reasoning guide](https://developers.openai.com/api/docs/guides/reasoning) says Chat Completions does not support function calling with some current models (both read on 2026-11-08). - **Row 1** is the T101 object form, which only the Responses API carries (`reasoning: {effort, summary}`). - **Row 4 keeps auto lossless.** A field the Responses translation cannot carry is never dropped or refused because of auto: the request goes to Chat Completions as before and gets the provider's own answer. - **Row 5 keeps the established behavior.** When the need is not explicit in the body, auto behaves like a target without `api`. Tools without `reasoning_effort` stay on Chat Completions even though some models default to a reasoning effort: the gateway does not know a model's default. To send them to Responses, set the effort on the target (`request_defaults: {reasoning_effort: medium}`), which row 3 then sees. - **Paths.** On an `auto` target, `paths.chat` is the Chat Completions path only; a call on Responses goes to `paths.responses` when the alias also serves `responses` and sets it, otherwise to `/responses` under the connection's base URL. (`api: responses` keeps sending its calls to `paths.chat`, as before.) Both APIs of a target share its circuit breaker, which counts failures per destination: a destination failing on one API is not admitted on the other either. Use `auto` only with a server that has both APIs: an OpenAI-compatible server without `/responses` answers 404 to the requests rows 1–3 send there. - **Native Responses stays native.** A `/v1/responses` request to an alias whose targets all speak Responses natively (`api: responses`, `auto` or the default) is passed through as is. On an alias that goes through the canonical format (another target is not native), an `auto` target decides like any other ingress. What changes on Responses is what `api: responses` already does: the request goes with `store: false` unless the client asked to store, `max_completion_tokens` becomes `max_output_tokens`, function tools keep `strict: false` unless the client set it, and the answer, the stream and errors come back in the Chat Completions shape. The rules apply to every route translated through the canonical format (Chat Completions, Messages, GenerateContent, and Responses on a translated alias), to every attempt of a fallback or [retry](/docs/features/inference-retries/), and to the quota profile of a single-target alias, which measures the API the attempt uses. A semantic cache entry is the Chat Completions answer either way, so it does not depend on the API. Each attempt of an `auto` target logs which API it used and why in `upstream_attempt` (`wire_api`, `wire_api_reason`), the attempt span carries `openai.api.type`, and the [request event](/docs/features/request-events/) has `wire_api`. ### Claude thinking mode Chat Completions has one field for reasoning, `reasoning_effort`. Claude has had two request shapes for it, and a model accepts only one of them: the older models take thinking with a token budget, and the models from Opus 4.7 on (Opus 4.7 and later, Sonnet 5 and later, Haiku 5.5, Fable) removed the budget and take adaptive thinking with an effort. A budget sent to one of the newer models is refused with a `400`, so a client that sets `reasoning_effort` fails on them. Which shape a target takes is declared on the target: ```yaml models: - id: claude targets: - provider: anthropic model: claude-opus-4-8 thinking_mode: adaptive ``` | `thinking_mode` | `reasoning_effort` becomes | Accepted efforts | | --- | --- | --- | | `budget` (default) | `thinking: {type: enabled, budget_tokens: 1024 \| 2048 \| 4096}` | `low`, `medium`, `high` | | `adaptive` | `thinking: {type: adaptive}` and `output_config: {effort: ...}` | `low`, `medium`, `high`, `xhigh`, `max` | - It applies to Chat Completions, and to Responses and GenerateContent requests, translated to an `anthropic` target or to Claude on a `bedrock` target (there the same fields travel as additional model fields of Converse). Where it would do nothing it is refused when the configuration loads or the model is saved: a target of another protocol, a Bedrock model that is not Claude, a passthrough alias, or an alias with none of the `chat`, `messages`, `responses` and `generate_content` capabilities. A native `/v1/messages` request is not changed: the client already wrote `thinking` in the shape it chose. On a target declared `adaptive`, a native request that asks for a token budget (`thinking: {type: "enabled", ...}`) is refused with `422 unsupported_on_provider` before the call, naming the field: the model would answer `400` after it, and under a budget a call that went out keeps its reservation. The gateway does not turn the budget into an effort, because no budget maps to one effort; send `thinking: {type: "adaptive"}` with `output_config.effort`, or turn thinking off in the client. - A request without `reasoning_effort` does not turn thinking on in either mode. - Thinking counts inside the output limit. Under `adaptive` there is no budget to size it from, so a request without `max_tokens` gets 8192, and 16384 at `xhigh` and `max`; a client's own limit is sent as it is. Set `request_defaults: {max_tokens: N}` on the target when answers are cut (`finish_reason: length`). - An effort the mode does not have (`minimal`, or `xhigh` under `budget`) is refused with `422` before the call, naming the field; with another target on the alias, that target is tried. - In both modes thinking needs `temperature` 1 or unset, and `top_p` is not sent with it. The newer models refuse the sampling parameters altogether: see the [`sampling` drop preset](/docs/features/request-parameter-policy/#drop-presets). - The newer models return an empty thinking block unless asked for a summary: see [reasoning summaries](/docs/features/request-parameter-policy/#reasoning-summaries). - **Why it is declared and not looked up.** The gateway does not decide a request's shape from a model's name, which changes with every release and alias, nor from the external model catalogue, which is advisory, fetched on demand and absent after a restart. A wrong guess would fail every reasoning request on that target. The model catalogue shows `supports_adaptive_thinking` for a model, which is where an operator reads the right value. - **Default.** Unset means `budget`, the behavior before this field existed. Nothing changes on upgrade. - **Bedrock.** The adaptive shape on Converse was not exercised against the real service; it sends the fields Anthropic documents for its own API. ## What crosses, and what does not Messages, system prompts, images, tool definitions, tool calls and their results, tool choice, parallel tool calls, temperature, top-p, stop sequences, output limits, structured output, reasoning effort, stop reasons, usage (with cached and reasoning tokens) and errors are mapped in both directions, for JSON and for streams. **Refused before the call** (`422 unsupported_translation`, naming the field), because dropping them would change the answer: - Messages: `top_k`, provider tools (web search, code execution, computer use, text editor, bash), `document` and `search_result` blocks, images inside a tool result, `container`, `mcp_servers`, `context_management`, metadata other than `user_id`. - Responses: stored state (`store: true`, `previous_response_id`, `conversation`, `background`), prompt templates, `truncation: auto`, `max_tool_calls`, built-in tools, files and images by `file_id`, `item_reference`. - GenerateContent: `cachedContent`, `topK`, more than one candidate, non-text output, Google tools (search, code execution, URL context), files by URI, non-image inline data, `functionCallingConfig` `VALIDATED`. - Provider side: each provider encoder still refuses what its API cannot express (for example `stop` on the Responses API). The refusing target is skipped without a call and the next target is tried; when no target accepts the request, the answer is `422 unsupported_on_provider` naming the first and last refusal ([fallback across translation refusals](/docs/features/feature-routing/#fallback-across-translation-refusals)). An alias with `unsupported_parameters: drop` removes such fields instead and names them in `X-Gateway-Dropped-Parameters` ([request parameter policy](/docs/features/request-parameter-policy/)). **Carried to Claude** (T115): prompt cache marks (`cache_control` on a block, a tool or, in Messages, the whole request) travel in the canonical format as `cache_control` on a content part, a message or a tool, and reach Anthropic Messages as `cache_control` and Claude on Bedrock as `cachePoint` blocks; a target can also place its own points (`prompt_cache`). Any other target cannot use them: the attempt removes them and `cache_control` is announced in `X-Gateway-Translation-Lossy`. A Chat Completions request to an OpenAI Chat Completions target keeps them as sent. See [prompt caching](/docs/features/prompt-caching/). **Left out and announced** in the `X-Gateway-Translation-Lossy` response header, because they steer cost, latency or storage but not the content of the answer: `service_tier`, `metadata`, `include`, `prompt_cache_key`, `stream_options`, `text.verbosity`, `safetySettings`, `labels`, and `cache_control` on a target that is not Claude; and history the canonical format cannot replay: signed thinking blocks, reasoning items, Gemini thought parts and thought signatures. Approximations are listed there too: a thinking budget becomes an effort level (`low` up to 1,024 tokens, `medium` up to 2,048 for Messages and 8,192 for Gemini, `high` above), and a Responses tool without `strict` is sent without it. Every translated answer also carries `X-Gateway-Translation: >chat`. **Other differences to know:** - A translated Responses answer is never stored: its ID cannot be retrieved or continued with `previous_response_id`. - A Messages `stop_reason` of `stop_sequence` comes back as `end_turn` (Chat Completions does not say which sequence stopped the answer), and translated thinking blocks carry an empty `signature`. - A Gemini function call without an ID is paired with its response by name, in order; the gateway gives it an ID that is stable within the request. - Gemini streams function calls whole, so a translated Gemini stream sends each call when its arguments are complete. - Without usage from the provider, a Messages answer reports zeros (the format requires the field); Responses and Gemini omit usage. - `/v1/messages/count_tokens` and `/v1/responses/input_tokens` still need a native target. - The Cohere encoder sends text only: an image to a Cohere target is refused with 422 `unsupported_on_provider`. - An OpenAI refusal (`finish_reason: stop` with refusal text) and Cohere's safety stop (`ERROR_TOXIC`) end as a refusal: `stop_reason: refusal` for Messages, `SAFETY` for Gemini, `incomplete` with `content_filter` for Responses (Cohere) or a `refusal` part (OpenAI). ## Images Every route translated through the canonical format carries an image as a Chat Completions `image_url` part: a Messages `image` block (base64 or `url` source), a Responses `input_image` with `image_url`, and a GenerateContent `inlineData` image all become one. What reaches the provider depends on the target: | Image | Anthropic | Gemini and Vertex | Bedrock Converse | OpenAI, compatible | | --- | --- | --- | --- | --- | | `data:image/{png,jpeg,gif,webp};base64,...` | `image` block, `base64` source | `inlineData` | `image` block with `bytes` | sent as is | | `https://...` | `url` source (Anthropic fetches it) with `image_input_translation` | refused, or downloaded with `image_url_download` | refused, or downloaded with `image_url_download` | sent as is (the provider fetches it) | | a `file` part (Chat Completions) or `input_file` (Responses), with its slice | refused | Gemini's own part with `gemini_file_inputs` ([file inputs](/docs/features/file-inputs/)) | refused | sent as is; the slice fields follow `unsupported_parameters` while `gemini_file_inputs` is on | | `gs://bucket/path.png` | refused | `fileData` with `image_input_translation`, only under `image_inputs.reference_prefixes` and with an image extension | refused | sent as is | | `s3://bucket/path.png` | refused | refused | `s3Location` with `image_input_translation`, only under `image_inputs.reference_prefixes` and with an image extension | sent as is | | `https://generativelanguage.googleapis.com/.../files/` | refused | refused (`image_reference_not_allowed`) | refused | sent as is | An image is never dropped. Without `image_input_translation` (operator flag, off by default) only data URLs translate, as before: anything else makes the target refuse the request, and the client gets `422 unsupported_on_provider` when no target accepts it. With the flag on, a refused image answers **400** with its own code when every target refused it for its image (another target that takes the image, such as an OpenAI one later in the alias, still answers): - `image_url_requires_download`: the target needs the image's bytes and the URL is not a reference it fetches; send a data URL, or turn on `image_url_download`. An `http://` URL to Anthropic, or a URL with credentials, is refused the same way. - `image_format_unsupported`: a data URL that is not base64 png, jpeg, gif or webp, or a `gs://` or `s3://` path without an image extension. - `image_reference_not_allowed`: a `gs://` or `s3://` reference outside `image_inputs.reference_prefixes`, or a Gemini Files API URI. Vertex and Bedrock read a storage reference with the **gateway's own credentials**, so without an approved prefix a caller could have them read any object those credentials can read, other tenants' included; the list is empty by default, so every storage reference is refused until the operator approves a bucket or path (`gs://bucket/` or `s3://bucket/path/`, ending in `/`, up to 64). A Files API URI names a file of the provider project every team shares, which the gateway does not own, so it is refused as on Decisions. The prefixes are gateway-wide, not per team. - `image_download_refused`, `image_download_failed`: see below. ### Server-side download With `image_url_download` (operator flag, off by default, requires `image_input_translation`), an `https` image URL sent to a Gemini, Vertex or Bedrock target is downloaded by the gateway and sent as bytes. A storage reference (`gs://`, `s3://`, a Files API URI) is never downloaded: it is passed or refused as above. Each image is downloaded once per request, whatever the number of targets tried. The download is built against server-side request forgery: - **https on port 443 only**, without credentials in the URL; every redirect must stay https on 443, and at most `max_redirects` are followed. - **Every address is checked at connection time.** The host is resolved, every address it resolves to must be public unicast, and the connection is made to the address that was checked, so a second resolution cannot point it elsewhere (DNS rebinding). Each redirect hop and each new connection is resolved and checked again. Refused: loopback, private (RFC 1918, `fc00::/7`), link-local (`169.254.0.0/16` and `fe80::/10`, the cloud metadata services `169.254.169.254` and `fd00:ec2::254` included), shared address space `100.64.0.0/10`, `0.0.0.0/8`, multicast, broadcast, benchmark, documentation and reserved ranges, IPv4-mapped addresses of any of these, and the IPv6 forms that embed or route to another address (IPv4-compatible `::/96`, IPv4-translated `::ffff:0:0:0/96`, NAT64 `64:ff9b::/96`, 6to4 `2002::/16`, Teredo `2001::/32`). The environment's HTTP proxy is never used, because it would connect past these checks. - **Bounded:** `max_bytes` per image (checked against `Content-Length` and while reading), 32 MiB per request in total, `timeout` per image including redirects, and `max_images` downloads per request. A failed download is remembered for the request, so another target does not try it again. - **An image, checked twice:** the answer must be `200` with a `Content-Type` of `image/png`, `image/jpeg`, `image/gif` or `image/webp`, and the bytes must sniff as that same type (an HTML page labeled `image/png` is refused). A refused download answers `400 image_download_refused` (address, scheme, size, type, redirects, too many images) or `400 image_download_failed` (timeout, the URL answered another status, the host does not resolve), naming the reason and never the address it resolved to. Nothing reaches the provider. ```yaml features: image_input_translation: true image_url_download: true image_inputs: download: max_bytes: 5242880 # 1024-20971520, default 5 MiB timeout: 10s # 1s-60s, default 10s max_redirects: 3 # 0-5, default 3 max_images: 8 # 1-32, default 8 reference_prefixes: # gs:// and s3:// prefixes callers may name; empty by default (all refused) - gs://shared-images/ ``` The settings are read on every request. `GET /api/v1/admin/image-inputs` (`providers:read`, either flag on) and the **Image inputs** panel in **Providers** show the flags, the effective bounds and the reference each provider family fetches. The answer carries the settings as an `image_inputs` object (`download` and `reference_prefixes`), named after the YAML block. Both flags are operator controls, not plan rights. **Verified with real providers** (2026-11-17): an 8x8 PNG data URL encoded by the gateway reached Anthropic (`claude-haiku-4-5`, 20 input and 4 output tokens) and Gemini (`gemini-3.5-flash-lite`, 1,089 image tokens) as native bytes, and both answered its color. Two calls, under US$0.001 in total. Bedrock (`bytes` and `s3Location`) is covered by tests against the documented Converse shape only; it needs an AWS account. ## Authenticating SDKs Send the gateway key as `Authorization: Bearer `. Because the Anthropic and Google SDKs put the key in their own header, the gateway also accepts it in `x-api-key` on `/v1/messages` and in `x-goog-api-key` on the GenerateContent routes, when there is no `Authorization` header. A key in the URL (`?key=`) is refused with 400: query strings end up in logs. ```python anthropic.Anthropic(base_url="https://gateway.example.com", api_key="") genai.Client(api_key="", http_options={"base_url": "https://gateway.example.com"}) ``` `:streamGenerateContent` serves the SSE stream (`?alt=sse`, which the SDKs send); the JSON-array stream without `alt=sse` is refused with 400. ## Errors and streams - A provider error comes back with its status in the client route's own error shape: `{"type":"error","error":{...}}` for Messages, the OpenAI envelope for Responses and Chat Completions, `{"error":{"code","message","status"}}` for Gemini. The provider's message is kept. Errors raised by the gateway itself (authentication, limits, refusals) keep the gateway's shape, as on every route. - A stream that fails after the first byte, ends without the provider's end marker, or loses its connection ends with the route's own error event (an `error` chunk for Chat Completions, `error` for Messages, `response.failed` for translated Responses and `error` for native ones, an `error` object for Gemini). It never ends with `message_stop`, `response.completed`, a finish reason or `[DONE]`. This holds on the native routes too. - When the provider sent its own error event, its message and kind go to the client (an overloaded provider stays `overloaded_error` for Messages, `UNAVAILABLE` for Gemini); `stream_interrupted` is only for a stream that broke without one. Either way the request is recorded as failed (`error_code: stream_interrupted` in the request log and in every error count, a provider error in the metrics, an error span), although its status is the 200 already sent. - A provider that answers a stream request with a buffered JSON body gets a 502 `provider_did_not_stream` before the client's stream starts. - The provider's `Retry-After` on 429 and 503 is passed on. - A provider redirect is never followed: it answers 502 `provider_redirect`, without the `Location`. - An AWS authentication error is replaced by a fixed message: on a signature mismatch AWS repeats the signed request, session token included, and that never reaches the client. - A refusal from the provider names the field as the client sent it (`thinking`, `reasoning.effort`, `generationConfig.thinkingConfig`). - Parallel tool calls stream as separate blocks or items keyed by call, so interleaved argument deltas stay with their call. - Every route falls back on transport errors, 429 and 5xx before the first byte, like chat. A translated `/v1/responses` request is always stateless (its decoder refuses stored state), so it falls back too; a native one falls back only when stateless ([Responses fallback](/docs/features/feature-routing/#responses-fallback)). ## See also - [Capabilities and routes](/docs/features/capabilities/) - [Providers](/docs/features/providers/): what each provider encoder covers and refuses. - [Stream usage](/docs/features/stream-usage/) # Prompt caching for Claude **Last updated:** 2026-11-08T13:49:34-03:00 (UTC-3) Claude reads a prompt prefix from its cache only up to a point the request marks with `cache_control`. A cached read costs a tenth of the input price or less, but the provider never caches on its own: a request without a mark pays the full input price every time. An application that talks to Claude in the OpenAI format (Chat Completions or Responses) usually sends no mark, and until T115 the gateway also dropped the marks an OpenAI-compatible SDK did send, so a Claude alias reached through an OpenAI client never got the discount. The gateway now carries the marks a client sends to every Claude target, and can place marks itself on a target with `prompt_cache: {mode: auto}`. This covers requests translated to the Anthropic Messages API and to Claude on Amazon Bedrock (Converse). A native `/v1/messages` call to an Anthropic target is already the client's own request and goes as the client sent it. ## Marks the client sends A Chat Completions request may carry `cache_control`, the extension that OpenAI-compatible SDKs already use for Claude, in three places: | Where | Effect | | --- | --- | | A content part (`text` or `image_url`) of any message | The point is at the end of that part | | A message (`{"role": ..., "content": ..., "cache_control": {...}}`) | The point is at the end of the message's last block; useful for string content | | A tool (`{"type": "function", "function": {...}, "cache_control": {...}}`) | The point is at the end of that tool definition | The value is `{"type": "ephemeral"}`, with an optional `"ttl": "5m"` or `"1h"` (five minutes by default). Anything else, an unknown member included, is refused with `422` before any provider call, because the provider would refuse it too and a guess could double the price of a write. ```json { "model": "claude", "messages": [ {"role": "system", "content": [ {"type": "text", "text": "", "cache_control": {"type": "ephemeral"}} ]}, {"role": "user", "content": "Summarize the attached contract."} ] } ``` A Messages request translated to another provider (for example `/v1/messages` on an alias whose target is Bedrock) keeps its block marks (text and image blocks, assistant text blocks, tool results and the text inside them), its tool marks and its top-level `cache_control` (automatic caching: the last block). Two marks have no exact place in the canonical format and move to the nearest later point: a mark on an assistant `tool_use` block moves to the end of that turn's last tool call, and a mark inside a tool result covers the whole result. Such a point then also covers the rest of that tool-call run or tool result; marks on thinking blocks are not carried, like the thinking blocks themselves. A mark on an empty text block is refused with 400, as the Messages API refuses it. How each target uses the marks: | Target | What it receives | | --- | --- | | Anthropic Messages (`protocol: anthropic`) | `cache_control` on the same block, tool or system block. A system or assistant message with a marked part is sent one block per part, so the point ends where the client put it; without marks it stays one block, as before. | | Bedrock Converse, Claude model (`anthropic.claude-*`) | A `cachePoint` block right after the marked block, in `system`, `messages` or `toolConfig.tools`; `"ttl": "1h"` only for one-hour marks (Bedrock may refuse the field on a model with the five-minute TTL only). A system message with a marked part is sent one block per part, as on Anthropic. | | OpenAI Chat Completions, reached from Chat Completions | The client's body, unchanged, as before T115 (OpenAI-compatible servers that accept the extension keep working). | | Any other target (OpenAI from another route or with the Responses API, Gemini, Cohere, SageMaker, OCI, a non-Claude Bedrock model) | No mark: it is removed from that attempt, and the answer lists `cache_control` in `X-Gateway-Translation-Lossy`. | Each attempt of a fallback decides for itself, so a request that falls back from Claude to another provider loses the marks only on the second attempt, and the header describes the attempt that answered. Two provider rules are checked before the call, on the client's marks and on automatic ones alike, because both providers refuse such a request: at most four points per request, and no one-hour point after a five-minute one (tools come first, then the system prompt, then the messages). An empty text part cannot carry a mark either, nor can a message whose last block is empty text or that has no content. A refusal skips the target without calling it, as any translation refusal does. ## Automatic points ```yaml models: - id: claude targets: - provider: anthropic model: claude-haiku-5-5 prompt_cache: mode: auto # off (default) or auto ttl: 5m # 5m (default) or 1h points: [tools, system, history] # default; in prompt order min_prefix_tokens: 0 # 0: the model's documented minimum ``` | Field | Default | Values | | --- | --- | --- | | `mode` | `off` | `off`: nothing is added. `auto`: the gateway places points when the request has none. | | `ttl` | `5m` | `5m` or `1h`, for every automatic point. | | `points` | `[tools, system, history]` | Up to four of `tools` (end of the tool definitions), `system` (end of the system prompt), `history` (end of the turn before the last one), `last_message` (end of the last turn). | | `min_prefix_tokens` | `0` | 0 to 1,000,000; 0 uses the model's documented minimum (below). | `prompt_cache` is accepted on `anthropic` and `bedrock` targets of `chat`, `messages`, `responses` and `generate_content` aliases; `auto` on Bedrock needs a model ID that names Claude (`anthropic.claude-*`, with or without a regional prefix). It is saved and validated like the rest of the alias (YAML, `PUT /api/v1/admin/models/{id}`, console **Model catalog → Edit routing → Prompt cache**) and applies from the next request, without a restart. There is no feature flag: the setting is opt-in per target. The rules, and why: - **The client's marks win.** A request that carries any mark gets no automatic point. Adding points next to the client's could pass the four-point limit or break the TTL order, and the client knows its own stable prefix better. - **Only where the prefix can be cached.** Each point needs the whole prompt before it (tools, then system, then messages) to reach the model's minimum. The gateway does not tokenize: it counts the serialized prefix at three UTF-8 bytes per token, which overestimates most text (English runs near four), so a point is skipped only when the prefix is clearly too short. A point placed on a prefix that turns out shorter costs nothing: the provider answers without caching and without an error. - **The history point is the conversation before the final turn.** Placed there, the next turn of the same conversation reads everything up to it, and the current question, which changes every time, is never written to the cache. `last_message` also caches the final turn, which pays the write premium on every request and only helps when the same request, or a longer one built on it, comes back within the TTL: an agent loop, or a prompt that ends with a large stable document. - **Writes cost more than reads save on a single call.** A five-minute write bills at 1.25× the input price and a one-hour write at 2×; a read at 0.1× (0.05× or 0.025× on some models). A prefix used twice within five minutes already pays off at `5m`; `1h` needs at least three uses and only helps when uses are more than five minutes apart. The attempt's `upstream_attempt` log names `prompt_cache_points` (how many points were placed) when automatic points were added; every other attempt keeps its log fields. ### Minimum cacheable prefix | Models | Claude API | Bedrock | | --- | --- | --- | | Claude Fable 5.1, Mythos 5.1, Opus 5.5, Sonnet 5.5, Haiku 5.5, Fable 5, Mythos 5, Opus 5 | 512 | 512 | | Claude Opus 4.8, Sonnet 5, Sonnet 4.6, Sonnet 4.5, Opus 4.1, Opus 4, Sonnet 4 | 1,024 | 1,024 | | Claude Mythos Preview | 2,048 | 2,048 | | Claude Opus 4.7 | 2,048 | 4,096 | | Claude Opus 4.6, Opus 4.5, Haiku 4.5 | 4,096 | 4,096 | | Any other model | 4,096 | 4,096 | Sources, read on 2026-11-08: the [Claude prompt caching guide](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) ("Cache limitations": minimums, four breakpoints, TTL order, empty text blocks, prices) and the [Bedrock prompt caching guide](https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html) ("Supported models, Regions, and explicit caching limits": minimums, four checkpoints, `cachePoint` with `ttl`). A model ID matches a family exactly or followed by a date (`-20251101`), a version (`-v1:0`, `@20251101`) or a context tag (`[1m]`), so `claude-opus-5` never matches `claude-opus-5-5`. A model the table does not know takes the largest documented minimum; set `min_prefix_tokens` for a new model. ## Cost and measurement The cache counters the provider reports are what the gateway measures, never an estimate: - The Chat Completions answer reports cached reads in `usage.prompt_tokens_details.cached_tokens` and writes in `cache_creation_tokens`, both inside `prompt_tokens`. - The [usage valuation](/docs/features/usage-valuation/) and [budgets](/docs/features/quota-protocols/#prompt-caching) price reads, five-minute writes and one-hour writes each at its own price, from the provider's own answer: Anthropic's `cache_creation` breakdown and Bedrock's `cacheDetails`. Without a published price for a category the cost stays unknown, never priced as plain input. A request that carries `cache_control` (a mark of the two supported TTLs) is valued and fits the chat budget profile when its target is Claude, whose answer splits the writes by TTL. On an OpenAI Chat Completions passthrough, whose answer reports writes without a TTL, a marked request stays unknown and outside the budget profile, as before: a one-hour write could otherwise be priced as a five-minute one. - The [request event](/docs/features/request-events/) carries `tokens.cache_read` and `tokens.cache_write`. Measured on 2026-11-08 with the native binary, PostgreSQL 16.15 and `claude-haiku-5-5` (input $0.10, output $0.50, cache read $0.01, five-minute write $0.125, one-hour write $0.20 per million tokens), a Chat Completions request with a 14,000-token system prompt, sent twice: | Request | Cache write | Cache read | Valued cost | | --- | --- | --- | --- | | Client mark, first call | 14,013 (5m) | 0 | $0.001755725 | | Client mark, second call | 0 | 14,013 | $0.000144230 | | `prompt_cache: {mode: auto, ttl: 1h}`, first call | 14,014 (1h) | 0 | $0.002806900 | | Same, second call | 0 | 14,014 | $0.000144240 | Uncached, the same request costs about $0.001406: the second call costs about a tenth of that, and the first pays the write premium. ## Upgrade notes - A Chat Completions client that already sent `cache_control` to a Claude target now gets it honored, and a malformed one, which was ignored before, is refused with 422 on that target. On a target that cannot use marks they are removed without being checked. - A Messages client on an alias translated to Bedrock or to an OpenAI target no longer sees `cache_control` in `X-Gateway-Translation-Lossy` when the target is Claude; it still does for any other target. - A multi-part system or assistant message with a marked part reaches Anthropic as one block per part instead of one joined block. - Nothing changes for a target without `prompt_cache` and a request without marks. ## Limits - `prompt_cache_key` (the OpenAI Responses hint) and Gemini's `cachedContent` are not Claude cache marks: the first is still left out and announced, the second still refused. - Automatic points are not added to native `/v1/messages` passthrough requests: the gateway does not rewrite a native body. `prompt_cache` on a `messages` alias whose targets are all Anthropic is accepted but has no effect, since every request there is native. - On Bedrock, marks and automatic points need a model ID that names Claude; an application inference profile ARN that does not is treated as another model. - A Messages assistant turn with a marked text block keeps its text blocks apart in the canonical format; a target that cannot use the mark then receives those blocks joined by a newline, where an unmarked turn joins them directly. - The prefix estimate is not a tokenizer: near the minimum, a point may be placed on a prefix the provider then does not cache (at no cost), or skipped on one it would have cached. # Decisions **Last updated:** 2026-11-15T13:17:19-03:00 (UTC-3) Decision models answer typed questions about a text: "is the customer asking for a refund?" (yes/no), "what is the tone?" (choice), "how urgent is it, from 1 to 5?" (score). Instead of asking a chat model for JSON and hoping it comes back right, you get probabilities and validated labels. There are three formats on the market, and the gateway serves all three: | Route | Format | Key scope | Flag | | --- | --- | --- | --- | | `/v1/decisions` | OpenAI Decisions: `input` and a list of `questions` | `route:decisions` | `openai_decisions` | | `/v1/systemone` | System One: `state` and a map of `questions` | `route:systemone` | `systemone_decisions` | | `/v1beta/decisions` | Gemini Decisions: `input` and a map of `questions` (see [Gemini Decisions](#gemini-decisions)) | `route:gemini_decisions` | `gemini_decisions` (off by default) | With `decision_translation` (which requires `systemone_decisions`), the gateway converts between the first two: a client written for OpenAI Decisions can use a System One model, and vice versa. Gemini Decisions is served natively only. The flags give no one access: the key still needs the route scope and the alias. ## Supported providers | Provider | How to configure | Upstream format | Notes | | --- | --- | --- | --- | | OpenAI | protocol `openai` | Decisions | An image goes as an `input_image` part | | TypeSafe (Jev) | preset `typesafe` (`TYPESAFE_API_KEY`) | System One | The only one with images and `box` questions | | OpenRouter | preset `openrouter_decisions` (`OPENROUTER_API_KEY`) | System One | Automatic Jev pricing | | Cloudflare Workers AI | protocol `cloudflare_ai` | System One | Clef models (`clef`, `clef-flash`, `clef-omni`) | | vLLM Semantic Router | preset `vllm_sr` (`VLLM_SR_API_KEY`) | System One | Free; read the privacy notice below | Model discovery fills the connection's catalog: `jev-latest` and `jev-preview` on TypeSafe, `vllm-sr/d3-*` on vLLM Semantic Router. ## How to turn it on ```yaml features: systemone_decisions: true openai_decisions: true decision_translation: true # only if you want to convert between formats providers: - {id: typesafe, preset: typesafe} models: - id: jev capabilities: [systemone, decisions] # decisions here uses the translation targets: [{provider: typesafe, model: jev-latest}] ``` Declare on the alias the capabilities you offer the client. The gateway does not infer them from the model name. ## How to use it OpenAI format, against any alias with the `decisions` capability: ```bash curl http://localhost:8080/v1/decisions \ -H "Authorization: Bearer $GATEWAY_API_KEY" \ -H 'Content-Type: application/json' \ -d '{"model": "jev", "input": "I want my money back, the product arrived broken", "questions": [{"type": "predicate", "name": "refund", "instructions": "Is the customer asking for a refund?"}]}' ``` System One format, with an image and localization (`box`), only on TypeSafe directly: ```json {"model": "jev", "state": "Customer photo: {img1}", "assets": {"{img1}": {"type": "image", "format": "png", "data_base64": ""}}, "questions": {"color": {"type": "choice", "instructions": "Which color dominates?", "criteria": {"red": "red", "blue": "blue"}}, "object": {"type": "box", "instructions": "Locate the object"}}} ``` - Images and `box` require the `TypeSafe-Danger-Zone-Images: true` header. The gateway forwards that header, and `TypeSafe-Danger-Zone-Long-Context: true`, only to TypeSafe. - The `box` response returns `top`, `bottom`, `left` and `right` as fractions of the image, plus `confidence`. - TypeSafe rejects small images: a 64×64 PNG returns 400 "Invalid image dimensions". - In the console, **API reference** shows ready-made examples of both formats. ## Pricing - **Jev:** automatic on TypeSafe and OpenRouter, $0.042 per million input tokens and zero for output, read from OpenRouter's public catalog. No price book needed. - **vLLM Semantic Router:** free according to the provider's page, and the gateway prices it at zero with that page as the source. - The `usage` reported by the provider is preserved; the gateway does not make up costs. > **Privacy on vLLM Semantic Router.** The provider warns that it may log requests and responses to improve its models. Do not use these aliases with sensitive data. ## Gemini Decisions Google's Gemini Decisions API (launched 2026-11-11, API version `v1beta`) answers with `gemini-decision-1`: up to 1,000 keyed questions about one shared input, scored in one pass with no generated text. The gateway serves it at `POST /v1beta/decisions`, the path the Gemini SDKs call (`client.decisions.create` with `api_version` `v1beta`), so an SDK pointed at the gateway works unchanged. ```yaml features: gemini_decisions: true # off by default providers: - {id: gemini, preset: gemini} # GEMINI_API_KEY models: - id: decide capabilities: [gemini_decisions] # alone on the alias targets: [{provider: gemini, model: gemini-decision-1}] keys: - id: support-app scopes: [route:gemini_decisions] allowed_models: [decide] ``` The alias must declare `gemini_decisions` alone and target the Gemini API (the preset's host, or a base URL ending in `/v1beta`); Vertex AI does not serve the API yet, and validation refuses such a target. The key goes in `Authorization: Bearer` or `x-goog-api-key`, never in `?key=` (`400`). ```bash curl http://localhost:8080/v1beta/decisions \ -H "x-goog-api-key: $GATEWAY_API_KEY" \ -H 'Content-Type: application/json' \ -d '{"model": "decide", "input": "The blue mug I ordered on Monday arrived cracked on Wednesday.", "questions": { "is_damaged": {"type": "noul", "instructions": "Did the item arrive damaged?"}, "tone": {"type": "choice", "instructions": "What is the tone?", "criteria": {"calm": "neutral or polite", "angry": "upset or hostile"}}, "urgency": {"type": "score", "instructions": "How urgent is a reply?", "criteria": ["low", "medium", "high"]}}}' ``` ```json {"answers": { "is_damaged": {"type": "noul", "noul": 0.99, "confidence": 0.99}, "tone": {"type": "choice", "choice": "angry", "probabilities": {"angry": 0.7, "calm": 0.3}, "confidence": 0.7}, "urgency": {"type": "score", "score": 1.6, "probabilities": {"0": 0.1, "1": 0.2, "2": 0.7}, "legend": {"0": "low", "1": "medium", "2": "high"}, "confidence": 0.7}}, "usage": {"total_input_tokens": 100, "input_tokens_by_modality": [{"modality": "text", "tokens": 100}], "total_output_tokens": 0, "total_tokens": 100}} ``` The gateway checks the request against Google's documented limits before any call (`400 invalid_decision` otherwise), and forwards it with only `model` replaced; the answer is relayed as received. | Field | Accepted | | --- | --- | | Top level | `model`, `input` and `questions` only | | `input` | A non-empty string, or content blocks: `{"type": "text", "text"}`, or `image`, `audio`, `video`, `document` (PDF) with exactly one of `data` (base64) or `uri` (https, fetched by Google) and `mime_type`; `resolution` (`low`, `medium`, `high`; `ultra_high` images only) on images and videos | | `questions` | 1 to 1,000, keyed `[A-Za-z0-9_-]{1,64}` | | Instructions | Required text: a string, a text block or a list of text blocks | | `noul` | Optional `criteria` with `true_description` and `false_description` | | `choice` | `criteria` mapping 2 to 255 option IDs (1-128 characters, at most 512 bytes, no control characters, no leading or trailing space) to a description or `null` | | `score` | `criteria`, 2 to 255 non-empty ordered levels (index `i` scores `i`) | Any `uri` on the Gemini API host (`generativelanguage.googleapis.com`, where Files API URIs live, whatever the path spelling) is refused with `422 file_uri_unsupported`: it names a file in the Google project every team shares; public objects such as `storage.googleapis.com` URLs are accepted. A body that repeats a member name at any depth is refused (`400 invalid_request`), whatever the policies, so the gateway and Google always read the same request. The 262,144-token context and the inline-data size limits are Google's; the request body limit is the gateway's (8 MiB by default, up to 64 MiB per alias with `models[].max_request_body_mib`). Google answers a safety block with `400` and no answers; the gateway relays it. **Pricing.** Google bills US$0.10 per million input tokens, every modality alike, and nothing for output; the shared input is billed once however many questions the request asks. The community catalogs do not list `gemini-decision-1` yet, so approve its rate in the [price book](/docs/features/price-book-management/): ```yaml price_book: - provider_id: gemini model_id: gemini-decision-1 input_per_million: "0.1" output_per_million: "0" effective_from: "2026-11-11T00:00:00Z" source_url: https://aistudio.google.com/docs/pricing ``` With [usage valuation](/docs/features/usage-valuation/) on, an answer is valued from `usage.total_input_tokens`; it stays `unknown` when the usage reports output, cached, thought or tool tokens, grounding calls, a modality split that does not add up or a `total_tokens` that is not input plus output, and when the answer was blocked (`prompt_feedback.block_reason`) or has no `answers`. Analytics and request logs record the operation as `gemini_decisions`. **Budgets and token limits** (`quota_native_protocols`, with an approved quota rate) admit text input only: the reservation is the request's bytes, which bound the shared input and every question's instructions and criteria, at the input price, and settles from the same usage. Image, audio, video and PDF input is refused under them (`media_input_not_bounded`): its tokens follow Google's tiling and duration rules, unknown before the call. **No Chat Completions mapping.** The gateway does not offer `gemini-decision-1` on `/v1/chat/completions` and does not translate Gemini Decisions to or from the OpenAI Decisions and System One routes. A chat answer is generated text: it would lose the per-option probabilities, the 0-1 confidence and the keyed answers of up to 1,000 questions in one call, and a client would be back to parsing labels out of text, which is what a decision model avoids. Use the native route. ## How translation works Translation only converts what can be preserved without losing meaning. The gateway prepares all targets before the first call; if any of them would require discarding information, the request returns `422 decision_translation_unsupported`, without spending anything. | Input | Accepted in translation | | --- | --- | | Envelope | Only `model`, `input`/`state` and `questions` | | `input` (OpenAI) | Non-empty text | | `state` (System One) | Text; an object; or an array of objects, which becomes an `input_json` part | | Questions | 1 to 64, each with an explicit text instruction | | Predicate / noul | Direct probability conversion; noul with `criteria` stays native only | | Choice | 2 to 255 values (string or boolean) or text criteria | | Score | 2 to 10 ordered levels, with text labels and descriptions | Conversion guarantees: - **Types preserved.** The boolean `true` and the string `"true"` stay distinct, and the response returns exactly the type requested. Different spellings of the same value (`"a"` and `"\u0061"`) are duplicates, and the request is rejected. - **Order and names preserved.** In OpenAI → System One, internal IDs (`q000`, `c000`) keep the order and the public name; they never reach the client. In System One → OpenAI, question names stay the same. - **Nothing made up.** The gateway does not inject generic instructions or turn criteria into a prompt prefix. If the question depends on that, use the native format. - **Structured input** up to 256 KiB, 32 nesting levels and 10,000 values, with exact integers (never passed through floating point). The translated response is read and validated in full (up to 8 MiB) before any byte goes to the client: model, number and identity of the answers, types, probabilities between 0 and 1, scores within the levels. `null` does not become a score of zero. An invalid response becomes an upstream error or a fallback to the next target, always before the first byte. ## Limits Outside translation (valid in the native format, when the provider supports them): - structured or multi-part instructions, multiple messages, images, `box`, tools, streaming and typed extraction; - fields with no equivalent, such as `safety_identifier` and cache options; - structured or null System One criteria, single-level Choice/Score and `noul.criteria`; - an OpenAI refusal when the client expects System One: there is no matching type. Other limits: - **Media:** images and `box` go only to TypeSafe directly. For Cloudflare, OpenRouter, vLLM Semantic Router or a translated target, the request returns 422 before the call. OpenRouter used to accept an image and ignore it; that is why the gateway rejects it. - **Cloudflare:** the gateway builds the `/ai/run/@cf/cloudflare/{clef|clef-flash|clef-omni}` path and validates the success envelope before converting. - **Credentials:** the client's key never reaches the upstream. - A well-formed response proves neither quality nor equivalence between models. ## See also - [Capabilities and routes](/docs/features/capabilities/): where `decisions` and `systemone` fit in. - [Circuit breaker](/docs/features/resilience/): it applies to decisions too. - [Inference flags](/docs/reference/inference-flags/). - External references: [OpenAI Decisions](https://developers.openai.com/api/reference/resources/decisions/methods/create), [TypeSafe OpenAPI](https://api.typesafe.ai/openapi.json), [Cloudflare Clef](https://developers.cloudflare.com/workers-ai/models/clef/). # Routing and resilience **Last updated:** 2026-11-27T01:08:49-03:00 (UTC-3) Providers go down, slow down and change their prices. With more than one target per alias, the gateway chooses where to send each request and tries another one when the first fails, without the app noticing. ## What's available | Feature | What it does | Flag | Learn more | |---|---|---|---| | **Fallback** | Transport error, 429 or 5xx before the first byte, or a target that cannot express the request: tries the next target. Stateless Responses included | (always) | [Below](#fallback-across-translation-refusals) and [Routing and admission](/docs/features/routing-and-admission/) | | **Semantic fallback** | Alternative targets for context overflow or a content policy refusal | `semantic_fallbacks` | [Strategies](/docs/features/routing-strategies/) | | **Context window check** | Skips a target whose declared `max_input_tokens` the request clearly exceeds, before any provider call, then the next target or the context fallback | `context_window_check` | [Context window check](/docs/features/context-window-check/) | | **Weight** | Splits traffic between targets by weight | `weighted_routing` | [Routing and admission](/docs/features/routing-and-admission/) | | **Latency** | Prefers the target that responded fastest, with periodic probing of the others | `latency_routing` | [Latency](/docs/features/latency-routing/) | | **Cost and load** | Prefers the cheapest or the least busy target | `routing_strategies` | [Strategies](/docs/features/routing-strategies/) | | **Conditional targets** | Restricts eligible targets by authenticated key/team IDs and admitted tags | `conditional_routing` | [Conditional routing](/docs/features/conditional-routing/) | | **Tags** | The client asks for a target by tag, such as region or quality | `tag_routing` | [Strategies](/docs/features/routing-strategies/) | | **Automatic routing** | Chooses the model by the meaning or the difficulty of the question (locally or with a classifier model), on Chat Completions, Messages and Responses, and shows the savings per key | `auto_routing` | [Automatic routing](/docs/features/auto-routing/) | | **Tool-aware routing** | For coding agents and other tool loops: reads what the tools returned and moves the session to a stronger model after repeated failures and back after the work passes, with holds so the provider's prompt cache is not thrown away on every turn | `tool_aware_routing` | [Automatic routing, trajectory strategy](/docs/features/auto-routing/#trajectory-strategy) | | **Circuit breaker** | Stops sending traffic to a failing target for a while | `circuit_breaker`, `resilience_management` | [Resilience](/docs/features/resilience/) | | **Concurrency cap** | A bounded queue and a cap on concurrent requests per target | `destination_limits` | [Routing and admission](/docs/features/routing-and-admission/) | | **Retries** | Bounded retries on the same target, with jitter, before falling back; chat, Messages, Responses, embeddings, moderations, rerank | `inference_retries` | [Retries](/docs/features/inference-retries/) | | **Request parameters** | Per-target defaults, overrides, an output-token ceiling and removed parameters (by name or by path), applied to each attempt; asks for a reasoning summary; refuse or drop what a translated target does not support | `request_parameter_policy` | [Request parameter policy](/docs/features/request-parameter-policy/) | | **Attempt timeout** | Bounds how long each provider attempt may take to start answering, so a hung target hands over to the next one inside the total deadline | `attempt_timeouts` | [Network and timeouts](/docs/operate/network-configuration/#attempt-timeout) | | **Emergency stop** | Cuts off all inference, on every replica, with one command | (always) | [Incident response](/docs/security/incident-response/) | ## Fallback across translation refusals An alias can mix protocols: an OpenAI target and a Gemini target, for example. Each target's encoder accepts only what its API can express; Gemini has no `logprobs`, Anthropic has no `seed`. When the target in turn cannot express the request, the gateway **skips it without calling the provider** and tries the next target. Nothing is sent, no slot or circuit-breaker probe is taken, and the skipped target counts as no attempt for valuation. ```yaml models: - id: assistant targets: - {provider: gemini, model: gemini-2.5-flash} # refuses logprobs - {provider: openai, model: gpt-4.1-mini} # serves it ``` A chat request with `"logprobs": true` goes to the OpenAI target; the answer carries `X-Gateway-Provider: openai`. The log has one `upstream_attempt_skipped` record for the Gemini target, with `reason: translation_refused` and, when the refusal names a known request member, that name in `field` (never client text), and a `provider.chat.skipped` span; the OpenAI send has its usual `upstream_attempt`. When **no** target accepts the request, the client gets `422 unsupported_on_provider`. With one target the message is that target's own refusal, as before. With several, it names the first and the last: ```json {"error": {"code": "unsupported_on_provider", "message": "No target of this model accepted the request. First refusal (gemini): logprobs is not supported by the Gemini API; last refusal (anthropic): logprobs is not supported by the Anthropic Messages API"}} ``` - This applies to every route that goes through the canonical chat format: chat, and Messages, Responses and Gemini requests translated for a target of another protocol. - [`unsupported_parameters: drop`](/docs/features/request-parameter-policy/#unsupported-parameters-refuse-or-drop) still removes such fields instead of skipping the target; the skip happens only when the target would refuse. - An ingress refusal (`422 unsupported_translation`, such as `previous_response_id` on a translated Responses request) is about the client's dialect, not a target, and is not skipped. - The native adapters of other operations (embeddings, images, audio) still answer 422 from the target that refuses. ## Responses fallback `/v1/responses` falls back like chat when the request is **stateless**: transport error, 429 or 5xx before the first byte moves it to the next target, and [weights and strategies](/docs/features/routing-and-admission/#how-weights-work) choose the first target. A request that continues or creates provider state keeps the declared order and a single send, at the provider that holds the state: - `previous_response_id` or `conversation` (with `responses_lifecycle` or `conversations`, the signed ID names the provider, and the request goes only there); - `background` mode, a stored `prompt`, an `item_reference` input, a reasoning item without `encrypted_content`, a content part with `file_id`; - containers and hosted tools (code interpreter, file or web search, MCP, image generation, computer use); only `function` and `custom` tools run at the client. `store: true` does not pin the request: the client only receives the ID of the send that succeeded, and its signed ID names the provider that served it. A failed send may still leave a stored response at its provider, which nothing references. Responses translated for a non-OpenAI target were already stateless (their decoder refuses stored state with 422), so they now fall back too. The same rule decides whether a Responses request may be [retried](/docs/features/inference-retries/#what-is-never-retried). ## What doesn't happen - Once the response has started arriving, there is no retry or fallback: a stream is never repeated. - Stateful Responses (`previous_response_id`, `conversation`, background, containers, hosted tools) stay on the provider that holds the state. - A fallback or retry after the provider has received the request can be billed twice; this shows up in usage as attempts. # Weights and per-target capacity **Last updated:** 2026-11-25T02:22:38-03:00 (UTC-3) Two tools for when you have more than one target for the same model: - **Weights** (`weighted_routing`) split traffic between targets, such as 3 for the main account and 1 for the backup. - **Per-target capacity** (`destination_limits`) puts a ceiling on concurrent requests to each target, with a short queue. It keeps a small deployment, a tight quota or a self-hosted model from taking more load than it can handle. The two flags are independent and can be turned on and off without a restart. The gateway's global limits still apply. ## How to turn it on ```yaml features: weighted_routing: true destination_limits: true models: - id: chat-balanced capabilities: [chat] targets: - provider: openai-primary model: gpt-4o-mini weight: 3 admission: max_concurrency: 4 # up to 4 requests at the same time queue_capacity: 8 # up to 8 waiting queue_timeout: 1s # how long each one waits - provider: alternate model: upstream-id weight: 1 ``` | Field | Values | Default | | --- | --- | --- | | `targets[].provider` | the ID of a configured provider | required; the connection this target sends to | | `targets[].model` | the upstream model ID | required; the model name the provider receives | | `weight` | integer from 1 to 10,000 | 1, if another target of the alias declares a weight | | `admission.max_concurrency` | 1 to 1,024 | required | | `admission.queue_capacity` | 0 to 1,024; zero does not queue | — | | `admission.queue_timeout` | 1 ms to 30 s | 1 s | In the console, **Model catalog → Edit routing** edits the weight and capacity of each target. The API is `PUT /api/v1/admin/models/{id}`. The configuration is validated even with the flag off, and editing these fields neither turns the flag on nor gives anyone access. ## How weights work The weight decides the **first** target of each request. The others remain as fallbacks, in the declared order, without repeating a target. The distribution is deterministic (smooth weighted round robin): at a 3:1 ratio, out of every four requests, three start on the first target. - Weight splits first choices, not tokens, cost or latency. - Each gateway replica has its own sequence; the ratio is exact per process, not across the cluster. - Changing an alias's targets restarts that alias's sequence. - When [tag-based routing](/docs/features/routing-strategies/#by-tags) leaves a request only some of the targets, the weights split the first choice among those, with a sequence of their own; requests that see every target keep theirs. The selection counts are per alias target. - Without a weight or with the flag off, the declared order applies. A **stateful Responses** request (`previous_response_id`, `conversation`, background, containers, hosted tools) also keeps the declared order and a single send; a stateless one follows the weights and falls back like chat ([Responses fallback](/docs/features/feature-routing/#responses-fallback)). - Fallback only happens before the response is sent to the client; there is never a replay after the first byte. ## How capacity works A **target** is the combination of provider connection, protocol, Base URL, API version and upstream model. **Every alias and route that reaches the same target shares the same slots.** The credential is not part of the identity, so rotating the key does not reset the slots in use. - **Combined ceiling.** If several aliases declare `admission` for the same target, the most restrictive applies: lowest concurrency, smallest queue, shortest wait. An alias without `admission` inherits the ceiling of another active alias on the same target, so there is no unlimited path. - **Queue.** FIFO per target, within each process, with bounded size and wait, unless the target declares [tenant fairness](#tenant-fairness-in-the-queue). - **No slot available.** A full queue or an expired wait becomes a 503 when no fallback is available. Cancelling the request frees its place in the queue. - **Slot duration.** The slot is taken before the circuit breaker and is only released when the upstream response ends, including in a stream (SSE). An error, EOF or cancellation releases the slot. - **Not a provider failure.** A refusal for lack of a slot does not open the circuit breaker. - **Configuration change.** Lowering concurrency does not drop what is already running; it just stops granting slots until usage is below the new ceiling. Shrinking the queue discards the last ones in the queue. Removing the target or turning off the flag removes those waiting, and in-progress responses finish normally. - **State limit:** up to 4,096 observed targets per process. Above that, a new admission is denied instead of deleting a target in use. There is no token reservation, financial limit or distributed queue here. For money and tokens, use [budgets and TPM](/docs/features/budgets-and-tpm/). A share of an alias's traffic can also go to one canary target, with sticky sides, shadow copies and automatic rollback: see [canary routing](/docs/features/canary-routing/). ## Tenant fairness in the queue With the operator flag `admission_fairness` (off by default, requires `destination_limits`), a target's `admission` policy can share its queue fairly across tenants, so one team or organization that fills the queue no longer starves the others. ```yaml features: destination_limits: true admission_fairness: true models: - id: chat targets: - provider: primary model: gpt-4.1-mini admission: max_concurrency: 8 queue_capacity: 64 queue_timeout: 2s fairness: by: team # team or organization weights: # optional; unlisted tenants weigh 1 team-checkout: 3 ``` | Field | Values | Default | | --- | --- | --- | | `admission.fairness.by` | `team` (the key's team) or `organization` (the team's organization, with `organizations` on) | required | | `admission.fairness.weights` | tenant ID → turns per round, 1 to 100; at most 64 entries | every tenant 1 | **How it admits.** While a slot is free and nobody waits, a request is admitted at once, as before. When requests wait, each freed slot goes to the next tenant in a weighted round robin over the tenants that have waiters: a tenant takes up to its weight of consecutive turns, then the next waiting tenant goes; within one tenant the order stays first in, first out. A tenant with nobody waiting leaves the round and joins at the end when it waits again. **When the queue is full.** A tenant's share of the queue is `queue_capacity × its weight ÷ the weights of the tenants waiting (with the arrival)`. An arrival whose tenant holds less than its share takes the place of the newest waiter of the tenant furthest over its own share; that waiter is refused with the usual overflow (`503 destination_overloaded`, or the next target) and counted as `displaced`. An arrival whose tenant is already at its share is refused as before. So a noisy tenant can use the whole queue while it is alone, and gives way as soon as another tenant arrives. **Tenant identity.** The tenant comes from the authenticated key's server-owned team and, for `organization`, the organization read with the team's ceiling; no client header can choose it. Requests without a team (or without an organization, for `by: organization`) share one tenant with an empty ID. The gateway's own calls on a request's behalf (guardrails, shadow copies) count for that request's tenant. **Shared targets.** All aliases that reach the same target share one queue; the first fairness policy declared for that target, in configuration order, applies to it. Turning the flag off goes back to FIFO at once, for the waiters already queued too. Fairness is per replica, like the queue. **Where to see it.** `GET /api/v1/admin/routing-status` adds, per destination with fairness, `fairness_by` and `tenants` (tenant, weight, waiting now, admitted, queued, overflow, displaced, timeouts, total and longest wait; at most 256 tenants per destination, the rest counted as `(other)`), and `counters.displaced`. The console shows them under **Providers → Routing & destination capacity**, and the policy in the model editor (**Edit routing → Routing & destination limits → Share the queue fairly across tenants**, weights one `tenant=weight` per line). With Prometheus, `gateway_destination_admission_total{result="displaced"}` is added while the flag is on, without a tenant label. ## Sticky routing (affinity) With `routing_affinity` on (catalog flag, default `false`, a model-policy right of the team plan), an alias with an `affinity` policy keeps the requests of one session, or of one key, on the target that last answered them. A conversation then stays on the same provider deployment, which keeps its prompt cache warm and its behavior consistent; a canary keeps each session on the side it was assigned to. ```yaml features: weighted_routing: true routing_affinity: true models: - id: chat-canary capabilities: [chat] affinity: mode: session # or key header: X-Conversation-Id # session mode; default X-Gateway-Session-Id ttl: 30m # default 1h max_entries: 20000 # default 10000 targets: - {provider: openai-primary, model: gpt-4o-mini, weight: 9} - {provider: openai-canary, model: gpt-4o-mini, weight: 1} ``` | Field | Values | Default | | --- | --- | --- | | `affinity.mode` | `session`: the value of `header`; `key`: the authenticated key | required | | `affinity.header` | 1–64 letters, digits or dashes; never a credential or connection header (`Authorization`, `Cookie`, `X-Api-Key`, `Host`…); `session` mode only | `X-Gateway-Session-Id` | | `affinity.ttl` | 1m to 24h after the pin's last use | 1h | | `affinity.max_entries` | 100 to 100,000 pins per replica for this alias; all aliases together at most 200,000 | 10,000 | The client sends the session in the declared header, for example `X-Conversation-Id: 7f3c…`. A value of 1–256 visible ASCII characters pins; an empty, longer or repeated header routes as if it were absent. The session is never read from the request body. **How a request is routed:** 1. Without a live pin (a new session, an expired pin, no header), the weights, the routing strategy, latency or adaptive routing choose as usual. The target that answers with a status below 400 becomes the pin. 2. With a pin, the pinned target goes first and the others follow in the declared order. The weighted sequence, latency probes and adaptive decisions are not consumed by that request, so weights split **new sessions**, not requests. 3. The pin is not used, and the strategies choose, when its target is no longer a candidate for this request: removed from the alias, excluded by [tag routing](/docs/features/routing-strategies/#by-tags), [target conditions](/docs/features/conditional-routing/), health-based routing or the organization's model ceiling; cooling under [adaptive routing](/docs/features/adaptive-routing/); or at its `admission.max_concurrency` ceiling. 4. Everything after the order is unchanged. A pinned target refused by its circuit breaker or its queue, or one that fails (429, 5xx, transport), falls back to the next target, and the target that answers becomes the new pin. Admission, budgets, TPM, rate limits, organization ceilings and organization aliases are checked as for any request; affinity never lets a request reach a target those would refuse. **Scope.** A pin belongs to one organization, team, key, alias and capability, digested together with the session value. The same session identifier sent by another key, team or organization never reads or steers that pin. Rotating a key starts new pins. **Pin IDs are keyed.** The pin ID is an HMAC-SHA256 of that tuple, not a plain hash, so a reader of the shared routing state cannot confirm a guessed session value, key ID or team against a stored pin. The HMAC key is derived from the current provider encryption key (`storage.provider_encryption_key_env`), which every replica of a deployment shares; without one, from the console session signing key; without either, from a random key per process, so pins then stay on the replica that wrote them even with the shared routing state. Rotating the source key changes every pin ID once: each session is routed by the strategies on its next request and pinned again. Pins written by a release before this one are not read again and expire. Stateful Responses (`previous_response_id`, conversations, containers) and native skills keep their own pinned provider and ignore affinity. **Bounds and lifetime.** Pins live in memory, in a least-recently-used table per alias capped at `max_entries`; the oldest is evicted past the cap. Each use extends a pin by `ttl`. Editing a target's weight or admission keeps its pins; removing or replacing the target ends them; removing the policy or turning the flag off drops every pin of the alias. Pins are per replica unless the [shared routing state](#shared-routing-state-across-replicas) is on. The policy needs two or more targets and is refused on a wildcard alias or with `auto_route`. It is validated even with the flag off. In the console it is the **Routing affinity** section of **Model catalog → Edit routing**; the API is `PUT /api/v1/admin/models/{id}` with the `affinity` object. ## Shared routing state across replicas By default each replica keeps its own latency samples, in-flight counts and pins. With `shared_routing_state` on (operator flag, default `false`) and PostgreSQL as the store, the replicas share them: - **Latency.** A replica uses the header latency the others observed for the same alias, capability and targets, averaged with its own by sample count (each replica's weight capped at 100), so a new replica routes to the fast target from its first request. - **Occupancy.** `least_busy` and adaptive routing count the requests in flight to a destination on every replica. - **Destination ceiling.** `admission.max_concurrency` becomes a ceiling for the whole deployment: this replica admits up to `max_concurrency` minus what the others hold. Waiting requests are admitted when a local slot frees or when a cycle shows the others released theirs. - **Affinity pins.** A pin written by one replica routes the same session on the others. ```yaml features: shared_routing_state: true routing_state: # every field optional; read on each cycle, no restart sync_interval: 1s # 250ms to 60s timeout: 500ms # one store round trip, 50ms to 10s replica_ttl: 10s # another replica's state counts this long; 2s to 10m, at least twice sync_interval ``` | Field | Values | Default | | --- | --- | --- | | `routing_state.sync_interval` | 250ms to 60s | 1s | | `routing_state.timeout` | 50ms to 10s | 500ms | | `routing_state.replica_ttl` | 2s to 10m, at least twice `sync_interval` | 10s | **How it works.** A worker per replica runs one PostgreSQL transaction each `sync_interval` (migration 182, tables `gateway_routing_replicas` and `gateway_routing_affinity`): it writes this replica's document (fresh latency samples, in-flight count per destination) and the pins written since the last cycle, and reads the other replicas' documents written within `replica_ttl` and the pins changed since its last read. The request path never touches the store: it reads the snapshot the worker built and adds its own local state. Pins are batched (up to 5,000 per cycle, 20,000 waiting); a pin keeps its absolute expiry while it waits, its lifetime is counted by the database clock and never exceeds the alias's `ttl`, and a pin the store refuses five cycles in a row is dropped (`pins_dropped`). A replica that stops deletes its row, so its in-flight counts stop counting at once; a replica that crashes stops counting after `replica_ttl`. Only destinations of the current configuration are counted. **When the store fails.** A cycle that fails or takes longer than `timeout` drops the remote part at once: the replica routes on its local state alone, the ceiling is the local one again, and no request fails because of the store. Pins written meanwhile wait for the next cycle. A later successful cycle returns to shared mode by itself. A snapshot older than `replica_ttl` is never used, even if the worker stalls. **Accuracy.** The shared values are as old as one cycle. Two replicas can admit in the same interval, so the global ceiling can be exceeded by at most what the replicas admit within one `sync_interval`; a crashed replica's in-flight count stops counting after `replica_ttl`. Remote state only reorders targets or tightens a ceiling: it never admits a request the local checks refuse. Malformed documents, negative or absurd counts and pins for aliases without a policy are ignored. **Where to see it.** `GET /api/v1/admin/routing-status` adds `shared_routing_state` and `shared_state` (`mode`: `shared`, `local_fallback` with a `reason` — `starting`, `storage_unavailable`, `store_error`, `store_timeout`, `stale` — or `off`; other replicas read, last sync and failure, consecutive failures, pins written, read, pending and dropped, and the effective settings), and `remote_in_flight` per destination. The console shows it in **Providers → Routing & destination capacity → Shared routing state**. With Prometheus, `/metrics` adds `gateway_routing_state_shared` (1 shared, 0 local fallback), `gateway_routing_state_replicas` and `gateway_routing_state_sync_total{result="ok"|"failed"}`. The same pins table carries the session state of the [trajectory strategy](/docs/features/auto-routing/#holds) of auto routing (the tier a session stands on and the turns left of its hold), under the router alias's name: a hold written on one replica reaches the others on their next cycle and a restarted replica reads it back on its first one. Without PostgreSQL the flag is accepted and the replica reports `local_fallback` with `storage_unavailable`. ## How to monitor it **Providers → Routing & destination capacity** shows, for anyone with global `providers:read`: - per alias: the strategy the router applies (`ordered`, `smooth_weighted`, `cost`, `least_busy`, `latency` or `adaptive`); a strategy whose feature flag is off, or an alias with one target, reads `ordered`, because that is how its requests are routed; - per target, for every strategy: how many requests it was the first choice of (`selected`: the request's first provider send went to it; a fallback or a retry is not counted, and the counts start over when the configuration changes); for a weighted alias its weight; for a `least_busy` alias the requests in flight to it (`in_flight`), which is what the strategy ranks by; - per target: effective ceiling, in progress, queue, wait, overflows, cancellations and timeouts, and with tenant fairness the per-tenant rows. - with `tool_aware_routing`, per alias running the [trajectory strategy](/docs/features/auto-routing/#trajectory-strategy): the sessions tracked, how many stand on each tier, how many are held and how many requests came without a session. No session value or key ID is shown; - with `routing_affinity`, per alias with a policy: mode, header, lifetime, pins held out of `max_entries`, and how many requests the pinned target answered (`hits`), found no live pin (`misses`), moved to another target (`moves`), evicted or expired. No pin key, session value or key ID is shown. The API is `GET /api/v1/admin/routing-status`; it answers when any routing feature is on (`weighted_routing`, `routing_strategies`, `destination_limits`, `latency_routing`, `adaptive_routing`, `routing_affinity`, `canary_routing`, `tool_aware_routing` or `shared_routing_state`). The response carries no host, path, key or payload. Read the numbers with these caveats: - `scope: process` and `process_instance_id` tell you which replica the response comes from; another replica shows another queue. With the shared routing state, `remote_in_flight` is what the other replicas hold. - The declared order and Responses do not increment `selected`; zero there does not mean no traffic. - `observed: false` is a ceiling that is only configured, with no admissions yet. `retired: true` is a removed target that is still finishing responses. - An admission is not a paid call: it can be cancelled before it reaches the network. The counters reset when the process restarts. With Prometheus and `destination_limits` on, `/metrics` publishes `gateway_destination_in_flight`, `gateway_destination_queued` and `gateway_destination_admission_total{result=...}`, aggregated per process, with no model, user or request labels. With Prometheus and `routing_affinity` on, `/metrics` adds `gateway_routing_affinity_entries` (pins held by the process) and `gateway_routing_affinity_total{result="hit"|"miss"|"moved"|"evicted"|"expired"}`, with no alias, key or session label. These limits protect a target from all callers together. To keep one key or team from taking the whole capacity, add a [concurrency cap per key or team](/docs/features/access-control/#concurrent-requests-per-key-and-team), checked when the request is admitted, before any target is chosen. ## Limits - Does not combine weights with [latency routing](/docs/features/latency-routing/) or with the [cost and occupancy strategies](/docs/features/routing-strategies/) on the same alias. - Affinity is applied on Chat Completions and the routes translated through it, and on the native operation routes (Messages, Responses, embeddings, images and the others); native Gemini `generateContent` keeps its weighted order without affinity. - The weight ratio and the queues apply per replica; with `shared_routing_state` the destination ceiling, occupancy, latency and pins are shared, within one sync interval. - Responses keeps the declared order. ## See also - [Routing and resilience](/docs/features/feature-routing/): overview of the group. - [Circuit breaker](/docs/features/resilience/): what happens when a target fails. - [Latency routing](/docs/features/latency-routing/): an alternative to weights. ## Shared admission definitions The [parameter registry](/docs/reference/parameter-registry/) shares the existing destination admission constraints with Go validation and console controls. An explicit admission block requires positive `max_concurrency`; the form starts at 1 without making it a backend default. Omitted `queue_capacity` is the real value zero (no queue); an empty `queue_timeout` uses 1s. Selecting a policy does not enable `destination_limits`, grant access or add a new retry. Existing versioned model edits and per-operation ownership remain unchanged. ## Conditional eligibility [Target conditions](/docs/features/conditional-routing/) narrow the pool before these strategies and capacity controls. A matching condition is eligibility, not priority, and an unconditional target remains eligible. Fallback cannot restore an excluded target. # Cost, occupancy, tags and semantic fallbacks **Last updated:** 2026-11-24T13:12:28-03:00 (UTC-3) Four ways to decide which target serves a request, beyond the declared order and [weights](/docs/features/routing-and-admission/): | Feature | What it does | Flag | | --- | --- | --- | | `cost` strategy | Tries the cheapest target first | `routing_strategies` | | `least_busy` strategy | Tries the target with the fewest in-progress requests first | `routing_strategies` | | Tag routing | Reserves targets for requests with certain tags (for example, enterprise customers) | `tag_routing` | | Semantic fallbacks | Sends to another alias when the request exceeds the context or hits the content policy | `semantic_fallbacks` | ## By cost or by occupancy ```yaml features: routing_strategies: true models: - id: chat routing_strategy: cost # or least_busy; ordered is the default targets: - {provider: openai, model: gpt-4.1-mini} - {provider: groq, model: llama-3.3-70b-versatile} ``` - **`cost`:** the lowest-priced target goes first. The price is input + output per million tokens, from the price book or [automatic pricing](/docs/features/automatic-pricing/). A target without a price goes last. - **`least_busy`:** the target with the fewest in-progress requests on this replica goes first. It is the default of the alias a [local inference](/docs/features/local-inference/) pool generates, where a replica that is not ready goes last. - The other targets remain as fallbacks, in the strategy's order. In the console, the model editor shows the **Routing strategy** section when the alias has two or more targets and no weights. Limits: - requires two or more targets; - does not combine with weights, [latency](/docs/features/latency-routing/) or [automatic routing](/docs/features/auto-routing/); - the Responses route keeps the declared order. ## By tags Useful for giving a group of customers a dedicated deployment without creating another alias: ```yaml features: tag_routing: true models: - id: chat targets: - {provider: dedicated, model: gpt-4.1, tags: {tier: enterprise}} - {provider: shared, model: gpt-4.1} usage_tags: allowed_values: {tier: [enterprise, free]} defaults_by_team: {acme: {tier: enterprise}} ``` `targets[].tags` reserves a target for requests whose usage tags carry every listed name and value. Tags come from the `X-Gateway-Tags` header and from the team defaults (see [usage tags](/docs/features/usage-tags/)). - Targets whose tags match the request's come first. - Targets without tags form the general pool. - With no eligible target, the response is `403 no_target_for_tags`. In the console, each target has the **Reserved for tags** field. ## Semantic fallbacks A request too long for the model, or refused by the provider's content policy, can go on to another alias instead of coming back as an error: ```yaml features: semantic_fallbacks: true models: - id: chat context_window_fallback: chat-long # context overflow content_policy_fallback: chat-safe # refusal by content policy targets: [{provider: openai, model: gpt-4.1-mini}] ``` - `context_window_fallback` names the alias that serves a request too long for the model's context window, and `content_policy_fallback` the alias that serves a request the provider refused for its content policy; both need `semantic_fallbacks`. - The second attempt happens only once. Its answer carries `X-Gateway-Fallback: :` (`context_window:chat-long`). - Other 400 errors come back as they were. - With `targets[].max_input_tokens` declared, a request clearly too long for a target is caught **before** it is sent: the target is skipped without a provider call, the next target is tried, and when none is left the request goes to `context_window_fallback` the same way. See [context window check before dispatch](/docs/features/context-window-check/). The fallback alias is admitted exactly like a direct request of the same key, so a fallback can never reach a model, budget or plan the key could not reach on its own: | Check on the fallback alias | Applies when | | --- | --- | | The key's `allowed_models` (and access groups) | Always | | The team policy | `team_policy_enforcement` is on | | The organization ceiling | `organizations` is on | | Plan entitlements for the alias's features (routing strategy, retries, semantic cache and so on) | `feature_plan_entitlements` is on | | Rate limits, including per end user | `rate_limits` / `end_user_rate_limits` are on | | Budgets and TPM/TPD, including model, team and end-user policies, with an approved rate for the fallback's target | `budget_limits` / `tpm_limits` are on | | Input guardrails of the fallback alias | `guardrails` is on | The second attempt carries the client's `X-Gateway-End-User`, `X-Gateway-Session-Id`, `X-Gateway-Tags`, `X-Gateway-Cache` and `X-Gateway-Timeout-Ms` headers, so end-user and tag budgets, tag-reserved targets, cache directives and the client's timeout apply to it too. It is a separate request in usage and budgets, with the request ID `.fallback`. The refused first attempt keeps its own record and reservation under the usual rules. When the fallback alias gets no provider answer, there is no fallback. That covers a refusal by the gateway before dispatch (access, plan, rate limit, budget, guardrail, quota or policy storage unavailable) and a provider that could not be reached or timed out. The client then gets the original provider error unchanged, which names the real cause (the prompt is too long, the content was refused), and the header `X-Gateway-Fallback-Refused: :` with the gateway code of the refusal: ```http HTTP/1.1 400 Bad Request X-Gateway-Fallback-Refused: context_window:model_forbidden {"error":{"code":"context_length_exceeded","message":"This model's maximum context length is 8192 tokens"}} ``` Common codes are `model_forbidden` (key, team policy or organization), `entitlement_forbidden`, `rate_limit_exceeded`, `quota_exceeded` (see [budgets and TPM](/docs/features/budgets-and-tpm/)), `guardrail_blocked`, `quota_unavailable`, `upstream_error` and `request_timeout`. The header never names the fallback alias, which the key may not be allowed to know. The refusal is also logged as `semantic_fallback_refused` with the kind and code. If the fallback's provider answers with an error, that answer is returned as it is, with `X-Gateway-Fallback`. ## See also - [Weights and per-target capacity](/docs/features/routing-and-admission/). - [Automatic routing](/docs/features/auto-routing/): choosing the alias by the request's content. - [Circuit breaker](/docs/features/resilience/): taking a failing target out of rotation. # Conditional target routing **Last updated:** 2026-11-13T07:33:34-03:00 (UTC-3) Use `targets[].when` to restrict which upstream connections may serve an alias for an authenticated key, its team and admitted usage tags. Conditions narrow destinations; they never grant model access, route scopes, team rights or budget. ## Enable and configure `conditional_routing` defaults to **false** and can be managed through YAML, the feature API and **Settings & sources**. The example assumes existing provider connections `openai-primary` and `alternate`, plus permitted usage tags: ```yaml features: conditional_routing: true usage_tags: true usage_tags: allowed_values: region: [eu, us] models: - id: chat-conditional capabilities: [chat] targets: - provider: openai-primary model: gpt-4o-mini when: team_ids: [team_platform] key_ids: [service_chat] tags: region: [eu] - provider: alternate model: alternate-model when: tags: region: [us] ``` The first target needs **both** the exact authenticated team and key IDs, and an admitted `region=eu` tag. Each key/team list accepts any one of its entries. Each tag value list accepts any one of its entries; every configured tag name must match. IDs are IDs, not display names, and are case-sensitive. A client cannot set its identity with `metadata`, a team header or a body field. Tags can be client-selected within the operator's taxonomy, so do not use a tag as proof of identity. Team/key-only conditions do not need usage tags. Conditions with tags use the same bounded header, taxonomy and optional team defaults as [usage tags](/docs/features/usage-tags/). Missing or unpermitted inputs never become an unrestricted match. ## Defaults and limits | Field | Default | Contract | | --- | --- | --- | | `targets[].when` | Absent: unconditional | When present, nonempty object containing only the three fields below; explicit null is invalid | | `when.key_ids` | No key restriction | 1–32 unique exact IDs when present | | `when.team_ids` | No team restriction | 1–32 unique exact IDs when present | | Each ID | None | 1–256 UTF-8 bytes; nonblank, no surrounding whitespace or controls; historical dots/slashes remain literal | | `when.tags` | No tag restriction | 1–8 names, each with 1–32 unique string values | | Tag names/values | None | Existing usage-tag ASCII tokens, 1–64 bytes | | Complete condition | None | At most 16,384 canonical JSON bytes, in addition to the existing model/configuration request bounds | | `features.conditional_routing` | `false` | Runtime operator control; does not grant permission | Lists, objects and strings cannot be empty or null. Unknown, duplicated or case-aliased fields, malformed types, expressions, regex and wildcards are rejected. The combined condition byte limit applies even when each individual list fits its limit. The full model-write JSON envelope also retains its 400 KiB (409600-byte) bound: combining maximum-size Codex instructions and several conditions can exceed that envelope even when every individual field validates. Keep the whole encoded request within that cap; the per-condition limit does not raise it. The API and console use the same typed definition; this definition was introduced in **V19** (107 definitions); the current console uses **V21** (109 definitions), preserving the same condition profile. Older catalog selectors and the omitted V1 response stay unchanged. ## Selection, weights and fallback A target without `when` is eligible for everyone who is otherwise authorized for the alias. A matching condition makes its target eligible; a nonmatching condition excludes it. There is **no implicit conditional-first priority**. Existing [weights and capacity](/docs/features/routing-and-admission/) and [strategies](/docs/features/routing-strategies/) choose among the eligible set, and fallback/retry cannot reintroduce an excluded target. Existing `target.tags` restrictions also apply. An unconditional fallback remains eligible and can be chosen by the configured strategy. To enforce a restricted destination, do not add an unrestricted target that contradicts that restriction. | Situation | Result | | --- | --- | | Alias has conditions but `conditional_routing` is off | 503 `conditional_routing_disabled`, before cache/provider | | No target meets the conditions | 403 `no_target_for_conditions`, without reflecting rule or identity values | | Required tag capture cannot be used | Refusal before provider; never ignore the tag dimension | | Alias has no conditions | Existing routing behavior | | Budget/profile cannot safely protect the resulting operation | Existing quota refusal; conditions do not bypass financial proof | Selection precedes pricing, durable send and provider attribution. A genuinely single eligible destination may use an existing single-destination financial profile. The feature does not add a new retry/accounting protocol or authorize an uncertain paid replay. ## Cache and helper calls Exact-cache identity includes the eligible target set, for both memory and remote storage. The stored key uses a private hash, not raw IDs or tags. Changing a condition/tag that changes the eligible pool cannot return an answer from another pool. Unchanged unconditional cache profiles keep their existing behavior. Semantic answer caching is bypassed when either the answer alias or its embedding alias declares conditions. This preserves routing correctness; it does not claim conditional semantic-cache hits. Auto-router example indexes use a private contextual namespace for conditional embedding aliases and retain their existing bounded lifecycle. Internal embeddings, classifiers and other alias-based helpers evaluate their own alias using the trusted in-process caller and their own admitted/default tags. They do not silently inherit a parent header that was not forwarded by the existing helper. A denied final destination may still follow earlier, visible and accounted helper work; do not treat every denied outer request as a guarantee of zero helper cost. Identity follows the accepted authentication snapshot, including any explicitly enabled [managed-key cache window](/docs/features/managed-key-cache/). This feature does not promise a stronger identity freshness boundary than authentication provides. ## Stateful work and realtime New resource creation and realtime connection establishment apply current eligibility. A new inference that uses a pinned conversation/response provider must also fit the currently eligible pool; it is refused rather than moved to another provider. Existing signed resources remain bound to their owner and provider. Reading, deleting, polling or settling an already admitted resource does not reroute it because a condition changed. Realtime pins its provider at connection establishment; configuration changes affect new requests/connections, not the destination of an admitted socket. Existing live credential, ownership and quota checks remain applicable. ## API and console edits Use **Model catalog → Edit routing**. Each target has typed conditions, with explicit key/team ID lists and tag/value lists. The editor preserves conditions on unrelated edits and derives its bounds from exact V19 metadata. Missing metadata or `target_condition_access.write` makes conditional editing unavailable; flag state and write permission are separate, so an authorized operator can stage a model while routing is disabled. The existing `PUT /api/v1/admin/models/{id}` accepts the full model and reviewed global version. For example, with an existing administrative session cookie and CSRF token: ```bash BASE_URL=http://localhost:8080 # COOKIE_JAR and CSRF_TOKEN come from the existing administrative login. VERSION=$(curl --fail-with-body -sS -b "$COOKIE_JAR" \ "$BASE_URL/api/v1/admin/config?parameter_catalog_version=19" | jq -r '.version') jq -n --argjson version "$VERSION" '{ version: $version, model: { id: "chat-conditional", capabilities: ["chat"], targets: [{ provider: "openai-primary", model: "gpt-4o-mini", when: {team_ids: ["team_platform"], tags: {region: ["eu"]}} }] } }' | curl --fail-with-body -sS -X PUT -b "$COOKIE_JAR" \ -H "X-CSRF-Token: $CSRF_TOKEN" -H 'Content-Type: application/json' \ --data-binary @- "$BASE_URL/api/v1/admin/models/chat-conditional" ``` PUT is a **complete replacement**: omitting `when` removes it; explicit null is rejected. An older full-spec client can therefore remove a rule it does not preserve. Use the current editor or retain every target field when automating. `DELETE` reverts the model override to the reviewed YAML base, including its conditions, rather than patching an individual target. Current identity/role, CSRF, captured version, whole-candidate validation and before/after feature-license checks apply to additions, edits, removals, disabled models and YAML restoration. Stale writes fail409. Read-only inspection does not make Save available; a late response cannot restore lost authority. The fixed publication-only unpublish action remains a recovery action when it leaves conditions identical. Rule IDs and raw predicates are private administration data. Team/public/hub projections do not expose them, and telemetry never records predicate arrays or raw condition values. Use normal request/trace IDs and existing routing/usage records to follow an admitted attempt. ## Upgrade and rollout No new database engine or schema migration is required for the target JSON. Replace or quiesce all older gateway replicas and administrative writers **before persisting conditions**. An older binary may ignore a field in stored JSON or continue serving its last older snapshot, so a normal mixed-version rollout does not prove these destination restrictions. Route traffic only to the upgraded pool, then stage/activate conditions through the versioned API. Preserve the existing configuration/database/key backup and new-binary recovery procedure; do not use an old binary to manage conditional models. # Context window check before dispatch **Last updated:** 2026-11-27T02:00:32-03:00 (UTC-3) A prompt longer than a model's context window is refused by the provider, but only after the gateway has sent it: the request travels, the provider answers 400, and only then can a [semantic fallback](/docs/features/routing-strategies/#semantic-fallbacks) send it to a model with a larger window. When you declare a target's maximum input, the gateway estimates the request's input tokens before calling it and skips a target whose window the request clearly exceeds. No provider call is made for that target; the request goes to the next target, to the alias's `context_window_fallback`, or back to the client with the same context-length error a provider gives. The provider's own refusal stays in place as the backstop: anything the estimate cannot see, or does not count, is still caught there, exactly as before. ## How to enable it Declare `max_input_tokens` on each target whose window you know. The flag `context_window_check` is on in the bundled configuration; it acts only on targets that declare a limit. ```yaml features: context_window_check: true # shipped on; acts only on targets with max_input_tokens semantic_fallbacks: true # for context_window_fallback models: - id: chat context_window_fallback: chat-long targets: - provider: groq model: llama-3.1-8b-instant max_input_tokens: 131072 - provider: openai model: gpt-4o-mini max_input_tokens: 128000 max_input_tokens_margin_percent: 5 - id: chat-long targets: - {provider: openai, model: gpt-4.1-mini, max_input_tokens: 1047576} ``` A request of about 300,000 tokens of English text to `chat` skips both targets without calling them and is answered by `chat-long`, with `X-Gateway-Fallback: context_window:chat-long`. A request only slightly above a window (say 135,000 tokens) is not clearly too large for the estimate, so it is sent as before; the provider refuses it and the semantic fallback takes over, exactly as without this check. In the console, the model editor shows a **Context window** block on each target of a text-generation alias: **Maximum input tokens** and, once a limit is set, **Margin above the limit (%)**. Clearing the limit removes the margin too. With the flag off the block says that the limit is saved but not applied. ## Fields | Field | Values | Default | Applied | | --- | --- | --- | --- | | `features.context_window_check` | `true`, `false` | `true` in the bundled `config/gateway.yaml` and Helm chart; `false` when a configuration file leaves it out | Runtime flag: YAML, the features API and the console Features page; next request | | `models[].targets[].max_input_tokens` | 1–100,000,000 | unset: no check, the target is called as before | YAML, `PUT /api/v1/admin/models/{id}`, console model editor; next request | | `models[].targets[].max_input_tokens_margin_percent` | 0–100 | 10 | Same; requires `max_input_tokens` | - The target is skipped when the estimate is **greater than** `max_input_tokens × (100 + margin) / 100`. With the default margin and a limit of 128,000, an estimate of 140,800 tokens is still sent and one of 140,801 is not. - `max_input_tokens` is compared with the **input** alone. A provider that counts the requested output inside the same window (input plus `max_tokens`) refuses earlier than that; for such a model, set the limit to the window minus the output you reserve, or rely on the provider's refusal for the last few percent. - The fields are accepted only on aliases whose capabilities are all text generation: `chat` (the default), `messages`, `responses` and `generate_content`. Any other value is refused at load and by the model API: `max_input_tokens must be from 1 to 100000000`, `max_input_tokens_margin_percent must be from 0 to 100`, `max_input_tokens_margin_percent requires max_input_tokens`, `max_input_tokens applies only to chat, messages, responses and generate_content aliases`. - The flag is an operator control, not a plan right: [plan entitlements](/docs/features/entitlements/) do not switch it per team. ## Where the check runs | Route | Too-small target with another target left | No target left | | --- | --- | --- | | `POST /v1/chat/completions` | Skipped; the next target in the alias's order is tried | `context_window_fallback` when configured and `semantic_fallbacks` is on; otherwise 400 | | `POST /v1/messages`, `POST /v1/responses`, `generateContent` translated to another protocol | Same (they run through the chat pipeline) | Same, and the error is re-encoded in the route's own dialect | | Native `POST /v1/messages` (Anthropic target) | Skipped | 400 in the Messages error shape | | Native `POST /v1/responses` (OpenAI Responses target) | Skipped, when the request may fall back (stateless) | 400 in the Responses error shape | | Native `generateContent` / `streamGenerateContent` (Gemini target) | Skipped | 400 in the Gemini error shape | On the chat pipeline, when a target was skipped for its window and a later target then fails (destination admission or circuit breaker refusal, a transport failure, a translation refusal, or a 429 or 5xx answer from the last target), the request is offered to `context_window_fallback` before that failure is returned: without the check, the skipped target's provider would have refused the request for context and the fallback would have answered it. Without a fallback, or when the fallback alias refuses, the client gets the later target's failure as before (with `X-Gateway-Fallback-Refused` when the fallback refused). The native routes have no semantic fallback today, with or without this check. A stateful Responses request (`previous_response_id`, `conversation`, containers) stays on the target holding its state: if that target's window is clearly too small, the client gets the 400 without a call. Token counting endpoints, embeddings and the other operations are not checked. The check runs per target, at the moment the target would be called: after guardrails, quota admission and the cache lookup, before the request is translated, before destination admission and the circuit breaker. A target skipped this way does not count as a send: `attempts`, `retries` and `fallbacks` in [request events](/docs/features/request-events/) and `X-Gateway-Attempts` count only real sends, and a [budget reservation](/docs/features/budgets-and-tpm/) of a request that made no send is released. A semantic fallback triggered this way is the same second request as after a provider's refusal, admitted in full against the fallback alias, with the request ID `.fallback`. ## The error the client receives The body imitates a provider's context-length refusal, so a client, an SDK or an agent that already handles that error (for example by compacting its conversation) handles this one too. It names the estimate and the largest limit among the skipped targets; it never names a provider. Chat Completions (and the semantic fallback's reading of it): ```http HTTP/1.1 400 Bad Request Content-Type: application/json {"error":{"code":"context_length_exceeded","message":"prompt is too long: the input has at least 140902 tokens by the gateway's estimate, above this model's maximum context length of 128000 tokens; reduce the length of the messages","param":"messages","type":"invalid_request_error"}} ``` Messages (native, or translated to another protocol): ```json {"error":{"message":"prompt is too long: the input has at least 140902 tokens by the gateway's estimate, above this model's maximum context length of 128000 tokens; reduce the length of the messages","type":"invalid_request_error"},"type":"error"} ``` Responses: `{"error":{"code":"context_length_exceeded","message":"...","param":null,"type":"invalid_request_error"}}`. GenerateContent: `{"error":{"code":400,"message":"...","status":"INVALID_ARGUMENT"}}`. When `context_window_fallback` is configured but its alias refuses before any provider answers (the key may not call it, a budget, a rate limit, or its own targets' windows are too small), the client gets this error with `X-Gateway-Fallback-Refused: context_window:`, for example `context_window:context_length_exceeded` or `context_window:model_forbidden`, exactly as after a provider's refusal. ## What is recorded Each skipped target writes two log records and one trace span, with counts only, never request text (abridged: the records also carry `time`, `correlation_id`, `trace_id` and the span IDs): ```json {"level":"INFO","msg":"upstream_attempt_skipped","request_id":"9f0c...","provider":"groq","model":"chat","capability":"chat","reason":"context_window_exceeded","field":""} {"level":"INFO","msg":"context_window_exceeded","request_id":"9f0c...","provider":"groq","model":"chat","capability":"chat","estimated_input_tokens":140902,"max_input_tokens":131072,"margin_percent":10} ``` The span is `provider..skipped`. A request answered with the 400 has `error_code: "context_length_exceeded"`, `provider: null` and `attempts: null` in its [request event](/docs/features/request-events/); one answered by another target or by the fallback alias records that answer as usual. ## How the estimate works, and how far it can be off Without the provider's tokenizer the count is estimated, and the estimate is built to stay **at or below** the real count, so a skipped target is one the provider would have refused anyway: - Only text the model reads is counted: message and system text, tool call arguments and tool results, tool names, descriptions, parameter names, types and enum values. Images, audio, files, documents, base64 data, opaque reasoning state (Anthropic `thinking`, Responses `reasoning` items, Gemini parts marked `thought`), signatures, IDs, roles, schema titles and the chat template's own tokens count zero. A request whose size comes from media is therefore never skipped by this check; the provider still refuses it if it does not fit. - A top-level member listed in the target's `drop_parameters` ([request parameter policy](/docs/features/request-parameter-policy/)), such as `tools`, is not counted for that target, since it never receives it. Neither is what a path or a preset removes: with `tools[*].description` dropped, the descriptions are left out of that target's estimate and the rest of `tools` is counted. - Text is split the way byte-pair tokenizers split it before merging: a word, a run of digits, a run of other symbols. Each piece is at least one real token in the common tokenizer families, so counting pieces gives a floor. Whitespace counts zero; a single symbol before a word counts with the word; a run of digits counts once, whatever its length. Scripts written without spaces (Chinese, Japanese, Thai...) count one piece per 20 characters, the longest such run one token of the measured vocabularies holds, which makes the estimate very low for those languages: the check rarely acts on them. - Stored state the request only points to (`previous_response_id`, `conversation`) is not read, so it is not counted. **Measured error.** The estimate was compared with the real token counts of seven public tokenizers (OpenAI `o200k_base` and `cl100k_base` through tiktoken 0.14.0; Qwen2.5, DeepSeek-V3, Llama 2 and Gemma through tokenizers 0.23.3; and the legacy public Claude tokenizer) on 229 text samples and 60 conversations with tools. The figure is the estimate divided by the real count, median / largest; 1.00 would be exact. **No sample had an estimate above its real count** with any tokenizer. Every entry of the seven vocabularies (about 927,000) was also checked against the segmentation: apart from three (a special-token fragment, a piece that only occurs inside a contraction the estimate counts as one word, and one kaomoji in Gemma), none counts as more than one piece. | Content | Samples | o200k | cl100k | Qwen2.5 | DeepSeek-V3 | Llama 2 | Gemma | legacy Claude | | --- | --- | --- | --- | --- | --- | --- | --- | --- | | English technical Markdown | 73 | 0.88 / 0.97 | 0.88 / 0.98 | 0.86 / 0.98 | 0.85 / 0.94 | 0.72 / 0.85 | 0.81 / 0.95 | 0.81 / 0.92 | | Portuguese Markdown | 30 | 0.77 / 0.95 | 0.71 / 0.92 | 0.70 / 0.92 | 0.71 / 0.93 | 0.59 / 0.86 | 0.73 / 0.93 | 0.64 / 0.91 | | Go source | 46 | 0.76 / 0.80 | 0.77 / 0.81 | 0.75 / 0.80 | 0.71 / 0.74 | 0.56 / 0.61 | 0.62 / 0.67 | 0.63 / 0.68 | | TypeScript source | 59 | 0.72 / 0.79 | 0.73 / 0.80 | 0.73 / 0.78 | 0.69 / 0.76 | 0.55 / 0.62 | 0.61 / 0.68 | 0.66 / 0.73 | | JSON data | 3 | 0.66 / 0.75 | 0.67 / 0.75 | 0.56 / 0.65 | 0.63 / 0.73 | 0.47 / 0.50 | 0.51 / 0.51 | 0.61 / 0.70 | | YAML (OpenAPI) | 3 | 0.72 / 0.75 | 0.72 / 0.74 | 0.68 / 0.72 | 0.71 / 0.73 | 0.58 / 0.62 | 0.62 / 0.68 | 0.75 / 0.77 | | CSV numbers, log lines | 2 | 0.84–0.85 | 0.84–0.85 | 0.49–0.56 | 0.83–0.85 | 0.49–0.54 | 0.49–0.55 | 0.79–0.83 | | Russian, Arabic, Hindi, Korean | 4 | 0.52–0.68 | 0.22–0.41 | 0.24–0.52 | 0.40–0.58 | 0.17–0.41 | 0.45–0.62 | 0.19–0.32 | | Chinese, Japanese, Thai | 3 | 0.10–0.15 | 0.06–0.07 | 0.11–0.12 | 0.10–0.16 | 0.05–0.06 | 0.12–0.17 | 0.03–0.08 | | Base64 text | 1 | 0.43 | 0.41 | 0.40 | 0.42 | 0.36 | 0.43 | 0.42 | | Conversations with tools (OpenAI accounting: content, 3 tokens per message, tools as the model reads them) | 60 | 0.77 / 0.83 | 0.77 / 0.83 | | | | | | The remaining samples (hex, emoji and accented text, whitespace-heavy code, repeated symbols and letters) stayed between 0.01 and 0.82. Read it this way: on English prose the estimate is typically 12% below the real count and was never above it; on code about 25% below; on unspaced scripts it is a small fraction. A provider also adds its chat template's tokens, so its count is higher still. The current Claude, Gemini and Mistral tokenizers are not public and were not measured: the margin is what covers a tokenizer that splits text more coarsely than these seven. With the default 10%, a target is skipped only when even an estimate inflated by a tenth would not fit. Set the margin to 0 for a target whose tokenizer is one of the measured families, or raise it if you see a provider accept a request the check refused (the logs give the estimate and the limit of every skip). ## Upgrade notes - New flag `context_window_check`, shipped `true` in `config/gateway.yaml` and the Helm chart's `files/gateway.yaml`. A deployment that uses its own configuration file without the key has the check off, which changes nothing either way until a target declares `max_input_tokens`. - New optional target fields, stored with the model: no migration. A target without `max_input_tokens` is called exactly as before, on every route. - Turning the flag off restores the previous behavior immediately; the declared limits stay saved. ## Beyond refusing An alias can opt in to truncating the oldest turns or summarizing them with another alias when no target fits, behind the flag `context_overflow`: see [context overflow](/docs/features/prompt-compression/#when-the-prompt-exceeds-the-window-context-overflow). ## See also - [Semantic fallbacks](/docs/features/routing-strategies/#semantic-fallbacks): the fallback alias and how it is admitted. - [Weights and per-target capacity](/docs/features/routing-and-admission/) and the [fallback order](/docs/features/feature-routing/). - [Request audit events](/docs/features/request-events/). # Automatic routing **Last updated:** 2026-11-25T02:41:33-03:00 (UTC-3) An "auto" alias decides, for each request, which model serves it. A coding question goes to the coding model, math goes to the reasoning model, simple conversation goes to the cheap one, and an agent that keeps failing moves to a stronger model until it recovers. The client always calls the same alias, and you control the criteria. Flag: `auto_routing`. There are three strategies: | Strategy | How it decides | Extra cost | | --- | --- | --- | | Semantic (default) | Compares the user's last message with example phrases for each route, using embeddings | One embeddings call per request | | `complexity` | Scores the text's complexity locally and picks a tier; optionally asks a classifier model | No call; about 0.15 ms for 2,000 characters. With a classifier, one chat call when it runs | | `trajectory` | Reads what the agent's tools have been returning and moves the session one tier up or down; optionally asks a judge model about an undecided turn. Own flag: `tool_aware_routing` | No call; about 0.1 ms for a 50-message conversation ([measured](/docs/performance/trajectory-routing/)). With a judge, one chat call on an undecided turn | Choose `semantic` when the topics are known in advance, `complexity` when the opening prompt says how hard the work is, and `trajectory` for coding agents and other tool loops, where the first prompt says little and the difficulty shows up during the run. ## Which APIs an auto alias serves An auto alias serves Chat Completions (`/v1/chat/completions`), Messages (`/v1/messages`) and Responses (`/v1/responses`), the last two being what coding agents speak. It serves the capabilities it declares, and chat alone when it declares none: ```yaml models: - id: agent capabilities: [chat, messages, responses] # the surfaces this router answers on auto_route: strategy: complexity default: small tiers: {simple: small, complex: big} - id: small capabilities: [chat, messages, responses] # every routed alias serves them too targets: [{provider: openai, model: gpt-4o-mini}] - id: big capabilities: [chat, messages, responses] targets: [{provider: openai, model: gpt-4o}] ``` - **Every routed alias serves every capability of the router.** The `default`, each route target and each tier alias must declare them all; otherwise the configuration is refused at boot and by the API, so a request is never routed to an alias that cannot answer it. A routed alias whose provider does not speak the dialect natively is translated, as it would be when called directly ([protocol translation](/docs/features/protocol-translation/)). - **A surface the router does not declare** answers 422 `capability_unsupported`, before any helper call. - **What the strategies read.** On each surface the router reads the same things: the text of the last user turn that has text (a turn made only of tool results is skipped), the assistant's tool calls and the tool results. - **Stored Responses state is refused.** A request with `previous_response_id` or `conversation` answers 422 `stateful_route_unsupported`: that state lives at one provider under one model, the router cannot read it, and another tier could not continue it. Send the conversation in `input`, as coding agents do. - **Everything else is the routed alias's.** Its rate limits, body limit, feature rights, retries, fallbacks, cache and prices apply; the router alias's own request rate limit is counted first. ## Semantic strategy ```yaml models: - id: auto auto_route: embedding_model: embed # alias with the embeddings capability default: general # when no route passes the threshold max_input_chars: 2000 # optional routes: - name: code target: coder # ordinary chat alias threshold: 0.55 # optional, 0.5 by default utterances: - write a python function - explain this stack trace - name: math target: mathy utterances: [solve this equation for x, what is the derivative of x squared] ``` | Key | Default | What it does | | --- | --- | --- | | `auto_route.strategy` | `semantic` | `semantic` compares embeddings with each route's examples; `complexity` scores the text locally; `trajectory` reads the agent's tool results (both below) | | `auto_route.embedding_model` | required for `semantic` | Alias with the embeddings capability that embeds the examples and each prompt | | `auto_route.default` | required | Alias that serves a prompt no route matches | | `auto_route.max_input_chars` | `2000` | Longest prompt text, in characters, sent to the embedding or classifier model | | `auto_route.routes[].name` | required | Route name, returned in `X-Gateway-Auto-Route` and recorded in the logs | | `auto_route.routes[].target` | required | Ordinary chat alias that serves the prompts this route wins | | `auto_route.routes[].description` | empty | Free text for the console | | `auto_route.routes[].utterances` | required | Example prompts; each prompt is compared with them | | `auto_route.routes[].threshold` | `0.5` | Minimum cosine similarity for the route to win; tune it per embedding model (see calibration) | - **Access:** the key must be allowed to call `auto`. Only routes whose target the key can also call compete. With no allowed target, the response is 403. - **Cost:** the embedding runs as the same key, with quota, ledger and RPM, and keeps the key's owner, so with identity ownership its spend is attributed to the same user or workload as the request it serves (the classifier call does the same). The examples are embedded once per version of the routes. - **Team policy:** the key does not need the embedding alias in its own allowlist, but its team policy and organization ceiling must allow it, plus the `route:embeddings` scope, because the call sends the prompt to that provider. A team policy or organization that allows the `auto` alias without them is refused: at boot for the YAML, with 400 in the team policy editor, with 400 in the organization editor, and with 422 when an alias edit would open the gap against a stored policy. Without that check every request would silently go to `default`. - **Response:** `X-Gateway-Auto-Route` carries the route name or `default`. The ledger and the logs record the chosen alias. - **Embeddings model failure:** falls back to `default`, with no error for the client. - **Calibration:** in the console, the model editor has **Test routing**. Through the API, `POST /api/v1/admin/auto-routes/test` with `{"model":"auto","text":"..."}` returns each route's score. With nomic-embed, off-topic prompts scored between 0.33 and 0.44 and on-topic ones between 0.50 and 0.71. With Amazon Titan Text Embeddings V2 on Bedrock the scale is much lower: off-topic prompts scored between 0.06 and 0.20 and on-topic ones between 0.21 and 0.37, so the 0.5 default routes nothing and a threshold near 0.2 leaves little margin; give each route more examples. A different model calls for different thresholds. - **Scope:** Chat Completions, Messages and Responses, as declared in the alias's `capabilities` (above). Embeddings and every other operation on an `auto_route` alias respond 422. ## How much the router saved Each routed request records the requested alias (`auto_route`), the most expensive candidate the key could use (`auto_route_baseline`), at the automatic price at that moment, and what the router chose and why (`auto_route_choice`, `auto_route_reason`). The **Auto-router usage** tab in the key detail compares the real cost with the baseline cost, per alias and per session, and shows the provider's prompt cache hit rate depending on whether the router kept, switched or went back to the model. Turns routed before the first price update after a restart have no baseline. ## Complexity strategy With `strategy: complexity`, the alias scores the last message locally, without calling a model, and picks a tier. ```yaml models: - id: smart auto_route: strategy: complexity default: small tiers: {simple: small, medium: mid, reasoning: big} # complex missing → next most capable keyword_rules: - {keywords: [contrato, jurídico], tier: reasoning} ``` | Key | Default | What it does | | --- | --- | --- | | `auto_route.tiers` | required | Map of `simple`, `medium`, `complex` and `reasoning` to aliases; a missing tier uses the next more capable one | | `auto_route.boundaries.simple_medium` | `0.15` | Score above which a prompt is at least `medium` | | `auto_route.boundaries.medium_complex` | `0.35` | Score above which a prompt is at least `complex` | | `auto_route.boundaries.complex_reasoning` | `0.60` | Score above which a prompt is `reasoning` | | `auto_route.keyword_rules[].keywords` | required | Words or expressions; a prompt containing any of them goes straight to the rule's tier, before scoring | | `auto_route.keyword_rules[].tier` | required | `simple`, `medium`, `complex` or `reasoning` | - **Dimensions**, with the weights and the tier limits (0.15 / 0.35 / 0.60): - code (0.30); - reasoning (0.25); - technical terms (0.25); - length (0.10); - simple-question indicators (−0.05); - multiple steps; - many questions. The word lists cover English and Portuguese. - **Whole words:** a single word counts only as a whole word ("api" does not match "capital"). Multi-word expressions match as a substring of the text. - **Reasoning override:** two reasoning markers lead to the `reasoning` tier once the score passes the first limit. - **Keyword rules:** `keyword_rules` decide before scoring. - **Access:** a tier whose alias the key cannot call goes to `default`, never to a more capable tier. - **Testing:** the endpoint and the console show the tier, the score and the signals. ## Classifier model The local score reads keywords, so it can misjudge a short but hard question, or a long but routine one. A classifier model reads the request and names the tier instead. It can run on every request, or only where the local score is not confident, so you pay for it only on the traffic that needs it. ```yaml models: - id: smart auto_route: strategy: complexity default: small tiers: {simple: small, medium: mid, complex: big, reasoning: deep} classifier: mode: local_first # or model, near_boundary model: judge # ordinary chat alias, ideally small and fast max_local_tier: simple # local_first: the local score decides up to this tier timeout_ms: 3000 # optional, 3000 by default fallback: local # optional: local (default) or default ``` | `mode` | When the classifier runs | | --- | --- | | `model` | On every request | | `local_first` | When the local score lands above `max_local_tier` (`simple`, `medium` or `complex`) | | `near_boundary` | When the score is within `boundary_margin` (0.05 by default, up to 0.5) of a tier limit, at any tier | | Key | Default | What it does | | --- | --- | --- | | `auto_route.classifier.mode` | required | When the classifier runs: `model`, `local_first` or `near_boundary` (table above) | | `auto_route.classifier.model` | required | Chat alias that names the tier | | `auto_route.classifier.timeout_ms` | `3000` | Deadline of the classifier call; past it the local score (or `default`) decides | | `auto_route.classifier.max_local_tier` | required for `local_first` | Highest tier the local score settles on its own | | `auto_route.classifier.boundary_margin` | `0.05` | For `near_boundary`: distance from a tier limit, up to 0.5, within which the classifier decides | | `auto_route.classifier.fallback` | `local` | What decides when the classifier fails: `local` (the scored tier) or `default` (the default alias) | - **No evidence, no shortcut:** the local tier settles a request only when a keyword rule or a content dimension (code, reasoning, technical terms, simple-question indicators, multiple steps, many questions) fired. Length alone is not evidence: a short prompt such as `Solve for x: 3x^2 - 12x + 9 = 0` scores as `simple` only because it is short, so it goes to the classifier like a prompt where nothing fired. - **Access and cost:** the classifier runs through the gateway as the calling key, restricted to the classifier alias, so quota, RPM and the ledger count it, with the request ID `.classify`. The key does not need the classifier alias in its allowlist, but its team policy and organization ceiling must allow it, and a ceiling that allows the router without it is refused, as for the embedding alias. - **What it sees:** a fixed rubric and the last user message, quoted and bounded by `max_input_chars`. The system prompt and earlier turns are not sent. - **What counts as an answer:** only `{"tier": ""}` or the bare tier name. Anything else is a failure. No `response_format` is sent, so any chat model works. - **Never widens access:** the chosen tier goes through the same check as a scored one. A tier the key cannot call goes to `default`. A prompt that asks the classifier for a higher tier can at most reach a tier the key may already use. - **Failure:** a timeout, an error status or an unreadable answer falls back to the local score, or to `default` with `fallback: default`. A timeout or a 5xx also skips the classifier on that replica for 30 seconds; then one request tries it again. The chat request itself never fails because of the classifier. - **Keyword rules** still decide first, without a call. - **Testing:** the routing test shows whether the classifier decided (and its tier), was skipped because the local score was confident, or failed (and why). The test runs the classifier for real, so it is metered. ## Stall escalation An agent working with a small model can get stuck calling the same tool with the same arguments. With `stall_escalation`, the router notices and sends the request one tier up. ```yaml stall_escalation: window: 6 # optional: tool calls to look at repeat_threshold: 3 # optional: repeats of the newest call that count as stuck ``` - The router looks at the assistant's tool calls in the request's own messages. It is stalled when the **newest** call, by name and arguments, appears `repeat_threshold` times among the last `window` calls. An agent that repeated a call and then moved on is not escalated. - The request goes to the next **configured** tier above the one that would serve it, and only one tier. At the top, nothing changes. - Nothing is stored: the next request is judged on its own messages, so the bump ends when the loop does. - The decision carries the signal `stalled tool loop`. To see it in the routing test, send a conversation (`messages`) instead of a single prompt. - It works the same on Chat Completions, Messages and Responses, and the `trajectory` strategy accepts the same block. ## Trajectory strategy A coding agent sends its task once and then works for dozens of turns. What tells you whether the small model is coping is not that first prompt: it is what the tools return. With `strategy: trajectory` the router reads the newest tool results of each request and moves the session between the tiers: - **up one tier** when the same failure comes back, on a critical error, right after the client compacted the conversation, or when the recent results are mostly failures; - **down one tier** when the recent results are writes and passing checks; - **to `default`** when nothing decides: no tool results yet, tools it does not know, a mixed picture. Nothing is sent anywhere to decide this. The router reads the request it already has. ### Turn it on ```yaml features: auto_routing: true tool_aware_routing: true # off by default session_tracking: true # optional: also records the session in the request log models: - id: agent capabilities: [chat, messages, responses] auto_route: strategy: trajectory default: small # where a session starts and where an undecided turn lands tiers: {simple: small, complex: big} ``` That is a complete configuration: every setting below has a default. `tiers` takes two to four of `simple`, `medium`, `complex` and `reasoning`, and `default` must be the alias of one of them, because "one tier up" is counted from it. With `tool_aware_routing` off, an alias with this strategy is refused at boot and by the API, and nothing else changes. Have the client send a session identifier in `X-Gateway-Session-Id` (one value per agent run). Without it the router still works, but each request is judged alone and nothing is held (see Holds). ### What it reads The router looks at the last `window` tool results, each with the call that produced it: | It reads | Used for | | --- | --- | | The tool name | Its class: reads (`Read`, `Grep`, `Glob`, `LS`, web fetch and search), writes (`Edit`, `Write`, `MultiEdit`, `apply_patch`, the text editor tool) or planning (`TodoWrite`, `update_plan`, `Task`). The built-in list covers the common coding agents; add your own tools with `tool_classes` | | The shell command inside a shell call (`Bash`, `shell`, `exec_command`, `local_shell`) | Whether it checks the work (`pytest`, `go test`, `npm test`, `cargo test`, `make` and `make test`, `npm run lint`, linters and compilers), writes (`sed -i`, `git commit`, `mv`, `rm`, any output redirected to a file) or reads (`ls`, `cat`, `grep`, `git diff`). `2>&1` and pipes are understood; a script or target whose name does not say it checks something (`make clean`, `npm run dev`) is left unclassified | | The error flag | `is_error` of a Messages tool result, the exit code of a Responses shell output, a failed patch | | The result text | Only where it is the tool's own verdict: the output of a shell command that is not a plain read (`exit code 1`, a traceback, a line starting with `FAILED` or `error:`), or any result that opens with `Error:`. A file the agent reads may contain the word "error" and is not a failure | It does not read tool schemas or the `tools` array. Images and other non-text results cannot be read: a window with one is undecided. ### How it decides 1. **A hold is active** (below): the session stays where it is. 2. **Overrides, one tier up:** the newest result is a failure that already appears in the window, from the same call with the same message apart from numbers such as timings (`repeated_failure`; a test that now fails for another reason is progress, not a repeat), the newest result is a critical error such as a panic or out of memory (`critical_error`), the last user message carries one of your `compaction_markers` and no tool ran since, or `stall_escalation` is set and the agent repeats the same call. 3. **Otherwise the score.** Each failure in the window pushes up (a warning a little, an error more, a critical error most; a failure that a later passing check resolved counts half). Each write and each passing check pushes down. A full window of only looking around, with no write, no check and no failure, pushes up a little. The sum is squashed to a confidence between -1 and 1. At or above `confidence_threshold` the session goes one tier up; at or below its negative, one tier down. 4. **Inside the band** the turn is undecided: the judge decides if you configured one, else `default` serves. So one failed test run alone changes nothing (confidence 0.46), and neither does a file that is not there while the agent looks around; the same failure twice escalates, two different failures in the window escalate through the score, and an edit followed by a passing run brings the session back. **A turn sent twice counts once.** A client retry or a parallel request carries the same conversation as the request before it. The router recognizes it (same length, same newest tool call and result, same last user text), serves it as the first one was served, and does not move the tier or use a turn of a hold. The response says `repeat`. Moves are one tier at a time, to the next **configured** tier. At the top or the bottom the session stays. An undecided turn outside a hold is served by `default`, and the session is back on the default's tier. | Turn | Tool results so far | Served (tiers `simple: small`, `complex: big`) | Why | | --- | --- | --- | --- | | 1 | reads a file | `small` | no decision | | 2 | + a failing test run | `small` | one failure is inside the band | | 3 | + the same failure | `big` | repeated failure | | 4 | + the same failure again | `big` | held | | 5 | + an edit | `big` | held | | 6 | + a passing test run | `small` | writes and a passing check | ### Holds Every switch of model leaves the provider's prompt cache behind, because that cache is per model. A session that bounces between tiers on every noisy result can cost more than staying on the big model. Holds keep a session still: - **After moving up**, the session stays on that tier for `hold.escalation_turns` requests (2 by default), whatever their history says, and the one after is scored again. - **After coming down**, it stays on the cheaper tier for `hold.min_cheaper_turns` requests (0 by default) before a signal may take it up again. A hold belongs to one session: the value of the session header, under one key, one team and one organization. The same session value sent by another key, another team or another organization is another session, and neither reads nor changes the first. The state is kept per replica, bounded by `hold.max_entries` and `hold.ttl`; with `shared_routing_state` on ([shared routing state](/docs/features/routing-and-admission/)) it is shared across replicas and survives restarts, through the same tables as routing affinity, where a row is a keyed digest and 32 bytes and names no session, key or model. A hold written on one replica reaches the others on their next sync (`routing_state.sync_interval`). **Without the session header there are no holds**: the request is judged from the default tier on its own history, and the status page counts those requests so you can tell. A request with several values in the header, or a value that is not 1 to 256 visible ASCII characters, counts as having none. ### Settings Every key is optional except `strategy`, `default` and `tiers`. | Key | Default | What it does | | --- | --- | --- | | `auto_route.trajectory.window` | `3` | How many of the newest tool results are read, 1 to 20. A larger window remembers failures longer | | `auto_route.trajectory.confidence_threshold` | `0.5` | How far from zero the score must be to move the tier, above 0 up to 1. Higher moves less often and leaves more turns to `default` or to the judge | | `auto_route.trajectory.overrides.repeated_failure` | `true` | Go one tier up when the newest failing result repeats in the window. Set `false` to leave it to the score | | `auto_route.trajectory.overrides.critical_error` | `true` | Go one tier up when the newest result is a critical error. Set `false` to leave it to the score | | `auto_route.trajectory.overrides.compaction_markers` | empty (off) | Up to 16 strings of 8 to 200 characters that your client writes in the user message that replaces a compacted conversation, for example the opening words of its summary. On the request right after one, the tier goes up, since the model now works from a summary | | `auto_route.trajectory.tool_classes.observe` | empty | Names of your tools that read state (search, list, fetch); up to 100 | | `auto_route.trajectory.tool_classes.mutate` | empty | Names of your tools that change state (create, update, delete); a successful call counts like a write | | `auto_route.trajectory.tool_classes.plan` | empty | Names of your tools that organize the work without touching state | | `auto_route.trajectory.tool_classes.neutral` | empty | Names of tools to ignore, also when the built-in list knows them | | `auto_route.trajectory.hold.escalation_turns` | `2` | Requests the session stays on the tier it moved up to, 0 to 50; `0` turns the hold off | | `auto_route.trajectory.hold.min_cheaper_turns` | `0` | Requests the session stays on a cheaper tier after coming down, 0 to 50 | | `auto_route.trajectory.hold.header` | `X-Gateway-Session-Id` | Request header that carries the session identifier: letters, digits and dashes, never a credential header | | `auto_route.trajectory.hold.ttl` | `1h` | How long a session's state lives after its last request, `1m` to `24h` | | `auto_route.trajectory.hold.max_entries` | `10000` | Sessions tracked per replica for this alias, 100 to 100000; past it the least recently used is dropped. All trajectory aliases together may ask for at most 200000 | | `auto_route.classifier` | none | The judge for undecided turns (below): `mode: ambiguous`, `model`, `timeout_ms` | | `auto_route.stall_escalation` | none | Same block as in `complexity`: a repeated tool call counts as an override | Tool names in `tool_classes` match exactly, ignoring case, with or without an `mcp__server__` prefix (`update_inventory` also matches `mcp__warehouse__update_inventory`). A name may appear once across the four lists; a duplicate or an empty name is refused. A full example for a non-coding agent: ```yaml auto_route: strategy: trajectory default: mid tiers: {simple: small, medium: mid, complex: big} trajectory: window: 5 tool_classes: observe: [kb_search, get_order] mutate: [update_inventory, refund_order] hold: {escalation_turns: 3, min_cheaper_turns: 1} ``` With these lists, three successful `update_inventory` calls take the session from `mid` down to `small`; without them the router does not know the tool and `mid` serves. ### Judge for undecided turns By default an undecided turn goes to `default`, with no model call. You can have a small chat model decide those turns instead: ```yaml classifier: mode: ambiguous # the only mode of this strategy model: judge # ordinary chat alias, ideally small and fast timeout_ms: 3000 # optional ``` - **When it runs:** only on a request with tool results whose score is inside the band, outside a hold. A request without tool results, a decided turn and a held turn never call it. - **What it sees:** the last user message, bounded by `max_input_chars`, and the kind and outcome of the recent tool results (for example `1. check: error`, `2. write: ok`). Tool output, tool arguments and tool names are never sent. - **What its answer does:** it names a tier, and the session moves **one** tier towards it, or stays when the judge names the tier the session is on. - **Failure:** a timeout, an error or an unreadable answer leaves the turn undecided, so `default` serves. The request never fails because of the judge. - **Access and cost:** as for the complexity classifier, it runs as the calling key restricted to the judge alias, with request ID `.classify`; the team policy and organization ceiling must allow the judge alias and the `route:chat` scope. ### Access - A tier the key cannot call is served by `default`, never by that tier or another one, also under an override or a hold. The response says `tier_not_permitted`. - With no permitted `default`, the response is 403. - The conversation is client data: a client that invents failures can at most reach an alias its key may already call, and budgets, rate limits and the ledger count the request as usual. - `tool_aware_routing` is a model-policy right of the team plan, like `auto_routing`. ### What the response and the telemetry say | Where | What | | --- | --- | | `X-Gateway-Auto-Route` | The tier that served (`simple`, `medium`, `complex`, `reasoning`) or `default` | | `X-Gateway-Auto-Route-Reason` | `signals` (the score), `override`, `hold`, `judge`, `default` (nothing decided), `repeat` (the same turn sent again) or `tier_not_permitted` | | `X-Gateway-Auto-Route-Transition` | With a session: `first` (first routed request of the session), `kept` (same model as the previous request), `switched` (a model the session had not used) or `back` (a model it used earlier). `kept` is the only one where the provider's prompt cache can still be warm | | Request log and request events | `auto_route_choice`, `auto_route_reason` and `auto_route_transition`, beside `auto_route` and `auto_route_baseline`; shown in the request journey | | Request span | `gateway.auto_route.strategy`, `.tier` (`.route` for a semantic route name), `.reason`, `.baseline`, `.detail`, `.override`, `.direction`, `.transition`, `.confidence`, `.hold_remaining`, `.window_results` and `.stateless`, stored and exported over OTLP with the span | | Metrics | Below | None of them carries tool output, a tool argument, a tool name or the session value. | Metric | Labels | What it counts | | --- | --- | --- | | `gateway_auto_route_decisions_total` | `alias`, `strategy`, `route`, `reason` | Decisions of every strategy | | `gateway_auto_route_decision_duration_seconds` | `strategy` | Time of the decision (histogram); a strategy that calls a model includes the call | | `gateway_auto_route_switches_total` | `alias`, `direction` (`up`, `down`) | Requests on which a session moved to another tier | | `gateway_auto_route_cache_turns_total` | `alias`, `transition`, `cache` (`hit`, `miss`, `unreported`) | Answered trajectory requests by what they did to the prompt cache and whether the provider reported a cache read; `transition` is `unknown` without a session | | `gateway_auto_route_tokens_total` | `alias`, `transition`, `kind` (`input`, `cached_input`, `output`) | Tokens of those requests | | `gateway_auto_route_cost_usd_total` | `alias`, `transition`, `kind` (`actual`, `baseline`) | Estimated cost at the current automatic price: what was paid and what the most expensive candidate would have cost | | `gateway_auto_route_sessions`, `gateway_auto_route_holds_active` | `alias` | Sessions tracked and sessions currently held, on this replica | | `gateway_auto_route_stateless_total` | `alias` | Requests judged without a session, so without holds | To see whether switching pays, compare the cache hit rate of `kept` with `switched` and `back`, and `actual` with `baseline`: ```promql sum by (transition) (rate(gateway_auto_route_cache_turns_total{alias="agent",cache="hit"}[1h])) / sum by (transition) (rate(gateway_auto_route_cache_turns_total{alias="agent",cache!="unreported"}[1h])) ``` The **Auto-router usage** tab of a key shows the same comparison per session from the request log (see "How much the router saved"). If `back` and `switched` rarely hit the cache and the saving is small, raise `hold.escalation_turns` or `hold.min_cheaper_turns`, or raise `confidence_threshold`. ### Status and testing - **Status:** Providers → Routing shows, per trajectory alias, the sessions tracked on the answering replica, how many stand on each tier, how many are held and how many requests came without a session. API: `GET /api/v1/admin/routing-status`, field `trajectory`. - **Test a conversation:** in the model editor, **Test routing** takes a Chat Completions conversation as JSON. Through the API, `POST /api/v1/admin/auto-routes/test` with `{"model":"agent","messages":[...]}` returns the tier, the confidence, the signals (counts such as `errors ×2`, never tool names or output), the override or the reason nothing was decided. Add `"position":"complex","hold":1` to test a turn as a held session would see it. The test writes no session state; a judge, when it runs, is metered. ### Limits - The rules are fixed and readable, not learned. Whether a routed pair gives the quality you need at a lower cost depends on your agents and models: measure it on your traffic with the metrics above before relying on it. The gateway publishes no saving figure for it. - The state is advanced when the request is routed, so a turn that is then refused or fails at the provider still counted. Sending that same turn again does not count a second time. - A canary shadow copy of a routed request goes to the alias that served the original; it is not decided again and counts no turn. - Two replicas serving the same session between two syncs each see the hold as of the last sync; a hold can therefore last a request or two longer, never shorter than on one replica. - Text heuristics are in English, like the tools' own output. ## Limits - Chat Completions, Messages and Responses only, as the alias declares. Embeddings and other operations on an `auto_route` alias respond 422, and so does a Responses request with stored state. - The router never promotes the key to a model it cannot use: a route or tier without permission falls back to `default`. ## See also - [Cost, occupancy, tags and fallbacks](/docs/features/routing-strategies/). - [Usage valuation](/docs/features/usage-valuation/): where the cost compared with the baseline comes from. ## Complete console policy editing The existing model routing editor also exposes prompt-character limits (default 2,000, up to 20,000), semantic route descriptions (up to 500 UTF-8 bytes), complexity boundaries, keyword rules, classifier options and stall escalation. They use the same typed `auto_route` contract and model override transaction as YAML/API; this adds no routing strategy or automatic classifier/provider call. Existing helper aliases and caller permissions are still validated. Complexity boundary defaults are `0.15`, `0.35` and `0.60`, strictly increasing. Keyword rules select the minimum tier when a configured word is present. One-per-line controls retain a typed newline while sending only nonempty entries, and rebuilding the strategy clears the previous strategy's draft boxes. Invalid snapshots are refused before publishing; explicit preview/testing retains its existing authorization and upstream-call behavior. ## Shared policy definitions The automatic router retains its typed strategy, tier, reference and cross-field rules. Required aliases and examples belong to the routing policy. Thresholds keep their existing field-specific defaults; an omitted or zero semantic route threshold selects `0.5`. These policy values are not credentials or a universal routing default. Shared [parameter definitions](/docs/reference/parameter-registry/) describe consumed constraints without authorizing a helper model, changing the scoring formula or bypassing the team and organization ceilings. A form creation preset remains separate from the effective backend default. Semantic route thresholds and near-boundary classifier margins must be finite numbers. YAML `NaN` and infinities are rejected, retaining the existing finite ranges and zero-to-default behavior. The console accepts continuous finite threshold/margin/boundary values without rounding to an input step. Complexity boundaries must still increase strictly within `(0, 1]`. Raw zero remains available for existing default selectors: prompt characters, classifier timeout and stall window/repetition threshold. The backend still rejects invalid nonzero timeout ranges and inconsistent stall settings. # Latency routing **Last updated:** 2026-11-21T09:54:10-03:00 (UTC-3) With two targets for the same model, the gateway can prefer the one that is responding faster right now. It learns from its own traffic: it measures how long each target takes to return the response headers and sends the next request to the fastest one. It creates no extra calls and no paid health checks. Flag: `latency_routing`. ## How to turn it on ```yaml features: latency_routing: true models: - id: text-balanced capabilities: [chat] latency_routing: max_age: 1m # a sample older than this is forgotten probe_every: 10 # every 10 choices, try a target in rotation targets: - {provider: first-connection, model: upstream-model} - {provider: second-connection, model: upstream-model} ``` | Field | Values | What it does | | --- | --- | --- | | `latency_routing.max_age` | 1 s to 15 min | A latency sample older than this is forgotten: the target becomes unknown, not fast | | `latency_routing.probe_every` | 2 to 1,000 | Every this many choices, one target is tried in rotation with the client's request, so a slow target that recovered is seen again | The policy applies to aliases with two or more targets and the `chat`, `embeddings`, `moderations` or `rerank` capability. In the console, it lives in the model editor; the API is the same as for [versioned aliases](/docs/features/routing-and-admission/#how-to-turn-it-on). The configuration is validated even with the flag off. ## How it works - **What is measured:** the time between sending to the provider and the arrival of the response headers (or the transport failure). It does not include the gateway's queue, reading the body or the time to the first token. It is neither TTFT nor an SLO. - **Moving average:** `score = 0.8 × previous + 0.2 × new`. The first valid sample starts the average. - **Penalty:** a transport failure, 429 or 5xx adds 30 seconds to the sample. Other 4xx responses and cancellations do not touch the score. - **Forgetting:** a sample older than `max_age` becomes "unknown", not zero. - **Exploration:** every `probe_every` choices, a target is picked in rotation, using the client's own request. If all are unknown, the rotation decides. Otherwise, the lowest average wins. - **Fallback:** the other targets remain as fallbacks, in the previous order. Real fallbacks also feed the average. - **Narrowed requests:** when [tag-based routing](/docs/features/routing-strategies/#by-tags) or a pinned continuation leaves a request only some of the alias's targets, only those compete and the rotation skips the others. The averages belong to the alias's targets, so such a request neither resets nor shifts them. - A rejection due to capacity or the circuit breaker is not a send and produces no sample. The key's authorization and the team policy are applied before the choice. ## What is left out To avoid learning from requests that are not comparable, the strategy only applies to: - **Chat** with text messages (`system`, `user`, `assistant`), without stream, without tools, media or unknown fields; - **Embeddings and moderations** with a text or a list of texts; - **Rerank** with a text query and text documents. Requests outside this profile use the normal order and do not feed the average. Responses, Messages, Gemini and MCP do not use the strategy. ## How to monitor it **Providers → Routing & destination capacity → Passive latency observations** shows each target's average latency, for global sessions with `providers:read`. A target without a valid sample shows `known: false` and `header_latency_ms: null`. The number of observations does not prove the target is available right now. ## Limits - **Per replica by default.** Each process has its own samples and choices and nothing is persisted. With `shared_routing_state` on, replicas also use the samples the others observed, averaged by sample count and as old as one sync interval; see [shared routing state](/docs/features/routing-and-admission/#shared-routing-state-across-replicas). - **State reset.** Changing the configuration or rotating the provider's credential resets that target's observations. - **Ceiling:** 4,096 eligible alias/capability pairs across the whole configuration; above that, the configuration is rejected. - It does not combine with weights on the same alias. - It adds no retry and does not change stream behavior. Turning off the flag or removing the policy goes back to the previous selection immediately, without a migration. ## See also - [Adaptive routing](/docs/features/adaptive-routing/): ordering by provider and key health, not latency alone. - [Weights and capacity per target](/docs/features/routing-and-admission/). - [Circuit breaker](/docs/features/resilience/). - Reference: [Envoy's Peak EWMA](https://www.envoyproxy.io/docs/envoy/v1.38.6/api-v3/config/contrib/load_balancing_policies/peak_ewma/peak_ewma). The gateway implements neither P2C nor Peak EWMA; it uses the passive profile described here. ## Shared policy definitions The [parameter registry](/docs/reference/parameter-registry/) shares the existing sample-age and probe-interval bounds with Go validation and console controls. Both members are required when the policy exists. The form’s 1m and 10-selection values are creation presets, not backend defaults and not an automatically enabled strategy. Existing capability/target restrictions, flags and versioned model editing remain unchanged. # Adaptive routing **Last updated:** 2026-11-17T17:10:39-03:00 (UTC-3) With two or more targets for one alias, the gateway can order them by how healthy each provider connection and its keys have been on its own recent traffic: recent failures, a cooldown after consecutive failures, a credential pool with every key cooling, requests in flight and response-header latency. It learns only from real requests and never sends one of its own, so there are no paid health checks. Flag: `adaptive_routing` (off by default). It goes further than [latency routing](/docs/features/latency-routing/), which compares only header latency: adaptive routing reacts to errors and rate limits, keeps a bounded history and a decision log, and honors key-pool health. ## How to turn it on ```yaml features: adaptive_routing: true models: - id: chat capabilities: [chat] adaptive_routing: history: 50 # outcomes kept per target failure_threshold: 3 # consecutive failures before cooldown cooldown: 30s # how long a cooled target goes last targets: - {provider: primary, model: gpt-4.1-mini} - {provider: secondary, model: gpt-4.1-mini} ``` | Field | Values | Meaning | | --- | --- | --- | | `history` | 10 to 1,000 | How many recent outcomes each target keeps; older ones fall out of the failure share | | `failure_threshold` | 1 to 100 | Consecutive failures that put a target in cooldown | | `cooldown` | 1s to 10m | How long a cooled target goes last; afterwards one real request may try it again | All three fields are required when the policy exists; the console offers 50, 3 and 30s when you add it. The policy applies to aliases with two or more targets and the `chat`, `embeddings`, `moderations`, `rerank`, `messages`, `responses` or `generate_content` capability (the last three only order requests with `adaptive_routing_native`, below). It does not combine with target weights, `latency_routing`, `auto_route` or a `routing_strategy` other than `ordered`. In the console it lives in the model editor (**Model catalog → Edit routing → Adaptive routing**); the API is the versioned model `PUT` with the `adaptive_routing` object. The configuration is validated even with the flag off, and the flag is classified as a model-policy feature for plan entitlements. ## Native Messages, Responses and generateContent With the operator flag `adaptive_routing_native` (off by default, requires `adaptive_routing`), the same policy also orders the native routes of the alias: Anthropic `POST /v1/messages`, OpenAI `POST /v1/responses` and Gemini `POST /v1beta/models/{alias}:generateContent` (and `:streamGenerateContent`), when the alias routes them across two or more targets. ```yaml features: adaptive_routing: true adaptive_routing_native: true models: - id: claude capabilities: [messages] adaptive_routing: {history: 50, failure_threshold: 3, cooldown: 30s} targets: - {provider: anthropic-primary, model: claude-sonnet-4-5} - {provider: anthropic-secondary, model: claude-sonnet-4-5} ``` The guards are the same as on Chat: the decision reads the configuration snapshot of the request, a cooled target goes last until one recovery trial, the destination `admission.max_concurrency` ceiling and circuit breakers still refuse before send, and only real traffic is observed. One health history per alias is shared by its capabilities, so a Messages failure also demotes that target for the alias's Chat requests. Calls that must stay on one target keep their order: a Responses request that is not replayable (`previous_response_id`, `conversation`, a stored `prompt`, `background`, hosted tools or encrypted reasoning items), and Messages with native skills; their outcomes still count. With the flag off these routes keep the declared order and record nothing. ## How it decides Each request orders the targets it may use by, most significant first: 1. **Available before cooling.** A target goes last while it is in cooldown, while another request is trying it after a cooldown (recovery trial), or, for Chat, while its [credential pool](/docs/features/provider-credentials/) has every key cooling (key health, as recorded by the pool's last selection; other capabilities send with the primary key and ignore the pool's state). 2. **Recovery trial first.** A target whose cooldown just ended goes ahead of the others for one request, so it can prove it recovered even while a peer stays healthy. 3. **Lower failure share** over the target's bounded history. An outcome counts for ten cooldowns (5 minutes with `cooldown: 30s`) and then is forgiven, so one transient error does not demote a target for good. 4. **Fewer requests in flight** to that destination on this replica. 5. **Lower header latency**, a moving average (`0.8 × previous + 0.2 × new`) of the time to the answer of buffered successful calls (for translated protocols this includes reading and translating the answer). A target with no sample yet sorts first, so a new or reset target gets real traffic. 6. **Declared order** breaks any remaining tie. The order covers the fallbacks too: the next target tried is the next in this ranking. The decision is a pure function of the observed state; there is no randomness, so the same history always gives the same order. **What counts as an outcome.** A transport failure, `401`, `403`, `408`, `429` and `5xx` count as failures of the target (its provider or its key), and so does a gateway deadline (the model's request timeout or a stream clock) that expires before the target answers. For Chat through a credential pool, `401`, `403` and `429` belong to one key, which the pool cools by itself, and do not count against the target. Successful answers count as successes; a successful answer the gateway then fails to translate counts as a failure. Other `4xx` answers belong to the client and are not counted. A client that disconnects and refusals before send (capacity, circuit breaker, credential pool with no key, network policy) are not outcomes. Streams count by their status; only buffered answers feed the latency average. **Cooldown and recovery.** After `failure_threshold` consecutive failures a target goes last for `cooldown`. When the cooldown ends, the next request puts it first as its recovery trial, and other requests keep treating it as cooling until that trial's result arrives (counted or not) or another cooldown passes; a trial refused before send leaves it cooling for that cooldown. A success clears the cooldown; a failure starts a new one. There is no probe: the trial is a client's own request. **Pinned and narrowed requests.** A pinned continuation or [tag routing](/docs/features/routing-strategies/#by-tags) narrows the candidates; only those compete, and the state of the others is neither read nor reset. Stateful calls (Responses with server state, native skills) keep their declared order. The [circuit breaker](/docs/features/resilience/), admission limits, quotas and retries apply as before; adaptive routing only changes the order. ## How to monitor it **Providers → Routing & destination capacity → Adaptive routing observations** shows, for each alias, the decisions made, and for each target its outcomes and failures in the window, consecutive failures, cooldown or recovery trial, whether every key of its pool is cooling, requests in flight, header latency and how often it was the first choice, plus the latest decisions with their reason (`best_health`, `unobserved`, `recovery_trial`, `all_cooling`). The same data is in `GET /api/v1/admin/routing-status` under `adaptive` (`adaptive_routing` tells whether the flag is on), for global sessions with `providers:read`. The last 64 decisions are kept per alias. ## Limits - **Per replica.** Each process has its own history and decisions; there is no consensus across replicas and no persistence. A restart starts every target unobserved. - **State reset.** Any edit of the alias or of one of its target providers, or rotating a target's credential, resets that alias's state. Aliases removed from the configuration drop their state. A wildcard alias cannot use the policy. - **Ceiling:** 4,096 adaptive aliases across the configuration. - It adds no retry and no request. Turning the flag off or removing the policy goes back to the declared order immediately, without a migration. # Canary routing **Last updated:** 2026-11-26T03:21:52-03:00 (UTC-3) A canary sends a share of an alias's traffic to one new target while the rest stays on the targets you trust, keeps each key or session on its side, can copy traffic to a shadow target whose answers are thrown away, rolls back automatically when the canary misbehaves, and keeps every saved version of the alias so you can roll back in one click. Promotion is always a human save. Four flags, all off by default: | Flag | Kind | What it turns on | | --- | --- | --- | | `canary_routing` | model policy (plan right) | The split of an alias with a `canary` policy | | `canary_shadow` | operator, requires `canary_routing` | Shadow copies (`canary.shadow`) | | `canary_auto_rollback` | operator, requires `canary_routing` | Automatic rollback (`canary.auto_rollback`) | | `routing_versions` | operator, requires `admin_model_editor` and PostgreSQL | Versioned alias configuration with rollback | This is the gateway's own canary between provider targets. Canaries of the gateway release itself (Argo Rollouts, Flagger, a mesh) stay with your delivery tool; the [N-1/N upgrade test](/docs/operate/upgrade-n1-n/) covers two releases on one database. ## How to turn it on ```yaml features: canary_routing: true canary_shadow: true canary_auto_rollback: true routing_versions: true models: - id: chat capabilities: [chat] targets: - {provider: primary, model: gpt-4.1-mini} # 0: stable - {provider: primary, model: gpt-5-mini} # 1: canary - {provider: lab, model: candidate-2026-11} # 2: shadow canary: target: 1 percent: 10 sticky: key # key (default), session or request shadow: target: 2 percent: 50 max_concurrency: 4 auto_rollback: min_requests: 20 max_error_rate: 0.2 max_latency: 4s window: 5m ``` | Field | Values | Default | | --- | --- | --- | | `canary.target` | index of the canary target in `targets` | required | | `canary.percent` | 0 to 100: the share of keys, sessions or requests on the canary side | required | | `canary.sticky` | `key`, `session` (the session header, else the key) or `request` (a new draw each request) | `key` | | `canary.header` | session header (sticky `session` only): 1 to 64 letters, digits or dashes, never a credential or hop-by-hop header | `X-Gateway-Session-Id` | | `canary.shadow.target` | index of the shadow target, not the canary | required with `shadow` | | `canary.shadow.percent` | 1 to 100: share of eligible requests copied | 100 | | `canary.shadow.max_concurrency` | 1 to 64 copies in flight for the alias, per replica (64 for every alias together) | 4 | | `canary.auto_rollback.min_requests` | 5 to 10,000 canary outcomes in the window before a decision | 20 | | `canary.auto_rollback.max_error_rate` | 0.01 to 1 | 0.5 | | `canary.auto_rollback.max_latency` | 1ms to 10m mean header latency of buffered answers; unset means latency never triggers | unset | | `canary.auto_rollback.window` | 1m to 1h | 5m | At least one target must stay stable (neither canary nor shadow), and the canary and shadow targets need a provider and model that no other target of the alias uses (routing tells targets apart by provider and model, so a "same model, new parameters" canary needs its own provider connection). The policy cannot combine with `auto_route`, `passthrough` or a wildcard alias. In the console it lives in the model editor (**Model catalog → Edit routing → Canary**); the API is the model `PUT` with the `canary` object. The policy is validated even with the flags off. ## How the split works - **The side is drawn once.** With `sticky: key` (or `session`), the side comes from an HMAC of the organization, team, key, alias and session value, keyed by the deployment (see [keyed pin IDs](/docs/features/routing-and-admission/#sticky-routing-affinity)): every replica draws the same side for the same key, with no shared state. A key stays on its side while the percent holds; raising the percent only moves more keys to the canary. With `sticky: request` each request is drawn at random. - **The stable side never reaches the canary or the shadow.** The split removes those targets from the candidates before any strategy runs, the way tag routing does: weights, latency routing, adaptive order and affinity work inside the side as usual. - **The canary side tries the canary first**, then falls back to the stable targets in their usual order. Fallback, retries, circuit breakers, admission limits and budgets are unchanged. - **A continuation** (a Responses request with `previous_response_id` or a conversation) is not split, whatever the flag: it keeps every target except the shadow, so it reaches the provider holding its state; when that provider is not a candidate the answer is `409 continuation_target_unavailable`. Other single-send calls (native skills, hosted tools) are split like any request. - **With `canary_routing` off**, an alias with a policy routes to its stable targets only. Turning the flag off is the kill switch. - If tag routing or target conditions leave no target on the request's side, the answer is `503 no_eligible_target`. Applies to Chat Completions and the routes translated through it, the native operation routes (Messages, Responses, embeddings, moderations, rerank, images and the others) and native Gemini `generateContent`. ## Shadow copies With `canary_shadow`, a sample of eligible requests is copied in the background to the shadow target: - **Eligible:** stateless Chat Completions, embeddings, moderations, rerank, Messages and Responses sent by a client; Responses only with `"store": false`, so no stored response is left at the shadow provider. No copy starts while the replica drains. Never stateful calls (continued Responses, native skills), images, audio, video, files, batches or realtime, and never the gateway's own internal calls. - **The copy is the client's body**, sent as the same key to the same route, with only the `anthropic-version`, `anthropic-beta` and `openai-beta` headers; no idempotency key, session or tag header. It runs the alias pipeline again (guardrails, budgets, quota) and reaches only the shadow target, once. - **Never affects the caller.** It starts after the caller's request was admitted and routed, runs on its own context with the alias's request timeout (at most 10 minutes), and its answer is discarded. It reads and writes no exact, semantic or chat answer cache, makes no fallback, capture or affinity pin, and is not counted against the caller's RPM. - **Charged and logged as shadow.** Its usage is recorded and charged to the same key, team and attributed customer, with the usage tag `shadow=true` (source `gateway` with tag provenance) and the request ID `-shadow`. It counts against budgets, TPM and TPD like any request of the key (only RPM and per-model rate limits leave it out), so a key near its token limit should not be shadowed at a high `percent`. The gateway's own nested calls of a copy (guardrails, summaries) are ordinary internal calls. - **Bounded.** Past `max_concurrency` copies of the alias (or 64 in all) a copy is dropped and counted. ## Automatic rollback With `canary_auto_rollback`, every outcome of the canary target counts: transport failures, `401`, `403`, `408`, `429` and `5xx` are failures (as for [adaptive routing](/docs/features/adaptive-routing/)), and buffered successful answers give a header latency. Once the window holds `min_requests` outcomes, a failure share above `max_error_rate` or a mean latency above `max_latency` rolls the canary back: 1. On that replica the canary percent becomes 0 at once: new requests go to the stable side. 2. With `routing_versions` and PostgreSQL, the gateway saves the alias with `percent: 0` as a routing version (`source: auto_rollback`, actor `system:canary_auto_rollback`, audit action `model.auto_rollback`), so every replica and the console follow. The write uses the configuration version, so a concurrent human save or another replica's rollback wins and this one stops (`rollback_stored`: `stored` once the live alias shows percent 0, `superseded`, `conflict`, `failed`, `file_owned` when the GitOps file owns the alias, or `local` without the store). Raising the percent again, or making the canary the stable target, is a normal save by a person. A team can also roll the canary back on **quality**: a [route experiment](/docs/features/route-experiments/) with guarded rollback scores both sides with one of its evaluators and uses this same rollback (reason `evaluation_pass_rate`) when the canary's pass rate falls more than `max_drop` points below stable. It only acts on an alias that has `auto_rollback` here and lists the experiment's team in `auto_rollback.evaluation_teams` (at most 64 team IDs; empty, no team may). ## Routing versions and rollback With `routing_versions`, every console or API save of an alias records the saved model as an immutable version (migration 187, `gateway_routing_versions`), in the same transaction as the save. The first versioned save of an alias also records the model it replaced as version 1 (`baseline`). The newest 50 versions are kept per alias. - `GET /api/v1/admin/models/{id}/routing-versions` (`models:read`) lists them, newest first: version, source (`baseline`, `save`, `rollback`, `auto_rollback`), actor, request ID, configuration version, time and the stored model. - `POST /api/v1/admin/models/{id}/routing-versions/{version}/rollback` with `{"version": }` (`models:manage`, CSRF) saves that version's model again as a new version (`source: rollback`, `rolled_back_from`). It goes through every check of a model save: permissions, license, GitOps file ownership, validation and the configuration version (`409` when it changed). The audit action is `model.rollback`. - In the console: **Model catalog → Edit routing → Routing versions**, with **Roll back to vN** on each earlier version. ## How to monitor it `GET /api/v1/admin/routing-status` (global `providers:read`) adds `canary_routing` and `canary`: per alias, the configured and effective percent, stickiness, stable and canary outcomes and failures, the window's outcomes, failures and mean latency, whether it rolled back (when, why, whether it was stored), and the shadow counters (sent, answered, failed, dropped at the bound, sampled out, not eligible, in flight). The console shows them in **Providers → Routing & destination capacity → Canary routing**. With Prometheus, `/metrics` adds `gateway_canary_requests_total{side="stable"|"canary"}`, `gateway_canary_rolled_back` and `gateway_canary_shadow_total{result="sent"|"dropped"|"failed"}`, with no alias, key or tenant label. ## Limits - Counters, the rollback window and shadow bounds are per replica. The side of a key is the same on every replica that shares the provider encryption key (or the session signing key); without either key each replica draws its own sides, and during a provider-key rotation replicas on the old and new key can disagree until all restarted. - Routing versions record console and API saves and rollbacks while `routing_versions` is on; deletes, GitOps applies and saves made with the flag off are not versions, so the version before the newest is not always the state right before it. Rolling back a deleted alias creates it again. - A rollback is replayed through the model `PUT`, so it appears as two requests in the request log and metrics. - A local rollback without the store lasts until the policy changes. - Rotating the provider encryption key redraws every key's side once. - Shadow copies add load and cost on the shadow target and run the guardrails again; size `percent` and `max_concurrency` accordingly. ## Upgrade notes Migration 187 adds `gateway_routing_versions`. An older binary ignores the table and refuses the `canary` field and the four flags: remove the canary policies and the flags before rolling back. # Destination health and circuit breakers **Last updated:** 2026-11-24T09:25:00-03:00 (UTC-3) Use passive circuits to stop repeatedly calling a failing destination. Add explicit active checks when a provider supplies a suitable health or metadata endpoint. Both can share observations through the existing PostgreSQL database; Redis is not required. These controls restrict eligible destinations. They grant no model access, add no retry and never replay a response after its first byte. Authentication, team/model permissions, conditions, financial admission and captured provider transport remain authoritative. ## Defaults and flags | Flag | Default | Behavior | | --- | --- | --- | | `circuit_breaker` | Enabled in the bundled configuration | Existing passive circuit around Chat, operations, native Gemini, passthrough and video attempts | | `active_health_checks` | Disabled | Background checks only for targets with an explicit `health_check` | | `health_based_routing` | Disabled | Restricts new alias work using checks; requires `active_health_checks` | | `shared_circuit_breaker` | Disabled | Uses PostgreSQL admission/completion instead of process-local passive state; requires `circuit_breaker` | | `resilience_management` | Enabled in the bundled configuration | Existing versioned API/console policy editor | With the new flags disabled, circuits remain process-local. A replica restart or configuration replacement resets that local state. Up to 4,096 destinations are admitted; the gateway rejects additional destinations rather than evicting an open circuit. ## Configure passive circuits ```yaml features: circuit_breaker: true shared_circuit_breaker: true resiliency: circuit_breaker: failure_threshold: 3 open_duration: 30s shared_circuit: half_open_lease: 30s ``` | Field | Default | Meaning | | --- | --- | --- | | `failure_threshold` | `3` | Consecutive transport/429/5xx failures before opening; 1–100 | | `open_duration` | `30s` | Time before a half-open attempt; 1s–10m | | `shared_circuit.half_open_lease` | `30s` | Database-clock exclusive claim for a shared half-open attempt;1s–10m; late completions are token-fenced | Closed admits requests and counts consecutive failures. Open excludes the destination until its deadline. Half-open admits one test while its claim is valid. A success or ordinary client error closes it; another failure reopens it. Canceled requests and requests known not to have been sent are neutral and release their claim. The passive result is recorded at response headers, before copying a stream. A later stream interruption never introduces a retry, but it counts: when the provider cuts an answer that had already started (the client reads a `stream_interrupted` error event), the destination gets one more failure, and an answer that merely starts no longer clears failures left by cut streams; an answer relayed whole does. A destination that accepts requests and drops their streams therefore opens its circuit at `failure_threshold` cut answers in a row, and a half-open probe whose own answer is cut reopens it at once. A client that hangs up, a deadline of the request and an administrative stop are not counted. With `shared_circuit_breaker` the same holds across replicas: the cut and the pending mark are kept in the shared row (migration 205), so cut answers seen by different replicas add up. Native stateful Responses preserves its existing pinning and fallback rules. Realtime and unrelated resource helpers do not acquire a new passive circuit merely because shared state is enabled. ## Configure active checks Declare a fixed read-only provider-relative endpoint on each target that should be monitored. The endpoint must actually exist for that provider; the following `/models` example is appropriate only when that account/API supports it. ```yaml features: active_health_checks: true health_based_routing: true resiliency: health_checks: interval: 30s timeout: 5s stale_after: 90s max_concurrent: 4 failure_threshold: 2 success_threshold: 1 unknown_policy: deny models: - id: chat-primary capabilities: [chat] targets: - provider: openai model: gpt-5.4-nano health_check: path: /models method: GET success_statuses: [200] ``` `path` is required and joins the configured provider BaseURL. It cannot select another host, add a query/fragment, traverse directories or use ambiguous path escapes. `method` defaults to GET; HEAD is the other supported method. Expected statuses default to `[200]`, with one to sixteen distinct 2xx codes. | Target key | Default | What it does | | --- | --- | --- | | `health_check.path` | required | Path of the probe, joined to the provider's base URL | | `health_check.method` | `GET` | `GET` or `HEAD` | | `health_check.success_statuses` | `[200]` | The answers that count as healthy: 1–16 distinct 2xx codes; any other status is a failed observation | The check uses the provider's primary credential and captured CA/mTLS/proxy settings. It forwards no client payload or bearer credential. The response body is not retained, logged or interpreted as inference usage. A successful metadata endpoint proves only that endpoint/authentication: it does **not** certify model inference, remaining quota or every member of a credential pool. No automatic paid inference probe is performed, and a successful probe never closes a passive circuit. | Global health setting | Default | Behavior | | --- | --- | --- | | `interval` | `30s` | Cadence for an eligible target check;1s–1h | | `timeout` | `5s` | Bound on one check;100ms–1m; timeout is a failed observation | | `stale_after` | `90s` | Freshness limit, at least interval plus timeout, at most24h | | `max_concurrent` | `4` | Bounded worker concurrency;1–64 | | `failure_threshold` | `2` | Consecutive failed checks before unhealthy;1–100 | | `success_threshold` | `1` | Consecutive successes before healthy;1–100 | | `unknown_policy` | `deny` | Explicit `deny` or `allow` for a configured check with no fresh result | Targets without a configured check remain eligible. With health routing enabled, unhealthy destinations are excluded; unknown or stale results follow `unknown_policy`. If every candidate is excluded, the request fails before dispatch; the gateway does not silently override the policy. Background shutdown/cancellation is neutral. Removing a target or replacing its captured identity/policy fences old results. ## Shared state and failure behavior PostgreSQL coordinates probe claims, freshness and optional shared circuits across replicas. Destinations are namespaced by captured account/credential-pool/network and policy identity. Current-version rows are bounded; obsolete completions cannot restore a replaced generation. `resiliency.state_retention` defaults to24h (10m–30d, at least freshness/lease/open duration). Database-clock idle cleanup excludes active leases and removes unused material namespaces after rolling credential/network changes. Status shows the responding replica’s captured namespaces; it never claims an opaque material identity is newer than another. Lease exclusivity lasts until the database deadline. A stalled old network call can overlap a new owner after lease expiration; its stale token cannot overwrite the new result. This is not an exactly-once network execution promise. `resiliency.state_timeout` bounds one shared-state action (default2s,100ms–1m, whole milliseconds); it is distinct from PostgreSQL pool acquisition and per-statement timeouts. A shared admission database error fails closed with 503 before provider dispatch. A completion-write error is logged with request/trace correlation and does not replace a valid provider response. Health probes have their own correlated metadata events; they are not billed inference events. Observability exporters do not gate traffic. Health eligibility applies to new alias work. Reads, polling and deletion of existing owned objects retain their original provider; an unhealthy destination never reroutes an object to another account. Signed continuation unavailability is reported as unavailability, without pretending the signed ID is invalid. ## Monitor and edit **Providers → Resilience** shows policy separately from observations, with local/shared scope, freshness, unknown/unhealthy results and in-flight claims. Refresh reads observations; it does not run inference. Global viewers read; authorized administrators/operators edit, subject to operational flags and license ceilings. See [policy management](/docs/features/resilience-management/). `GET /api/v1/admin/resilience?version=2` selects the new observation contract. Default/version1 retains the historical process projection. `GET /api/v1/admin/resiliency?version=2` selects the new policy projection. Older clients remain on their existing response shape; they cannot infer shared health from a process-only view. Upgrade all replicas before enabling the new flags or persisting target policies. Back up PostgreSQL and follow the [migration procedure](/docs/operate/operations/). Keep earlier writers stopped while applying a newer schema; downgrading requires the documented backup/configuration procedure. Configuration changes apply to new attempts; admitted streams retain their captured state. ## See also - [Policy management](/docs/features/resilience-management/) - [Routing and admission](/docs/features/routing-and-admission/) - [Provider network profiles](/docs/features/provider-network/) - [Kubernetes availability](/docs/operate/kubernetes-availability/) # Circuit breaker policy management **Last updated:** 2026-11-13T10:22:13-03:00 (UTC-3) Adjust the [circuit breaker](/docs/features/resilience/) threshold and duration from the console or the API, without editing YAML or restarting. The change applies to all replicas. Flag: `resilience_management`, which requires `circuit_breaker`, the interface and PostgreSQL. ## How it works The YAML (`resiliency.circuit_breaker`) is the baseline. An edit from the console writes an override to PostgreSQL, which wins until it is removed. Removing the override goes back to the YAML. With nothing declared, 3 failures and 30 seconds apply. | Field | Values | | --- | --- | | `failure_threshold` | 1 to 100 | | `open_duration` | 1 s to 10 min | The policy is shared by the replicas through PostgreSQL. Failure observations remain local unless `shared_circuit_breaker` is explicitly enabled; see [shared state and checks](/docs/features/resilience/). Applying a new policy replaces the applicable observation generation. ## How to use it **In the console:** **Providers → Circuit breaker policy**. Admin and operator edit and revert; viewer only reads. **Through the API:** | Method | Permission | What it does | | --- | --- | --- | | `GET /api/v1/admin/resiliency` | `resilience:read` (global admin, viewer, operator) | Version, source (YAML or override) and the values in effect | | `PUT /api/v1/admin/resiliency` | `resilience:manage` (admin, operator) | Writes the override; requires `version` and both fields | | `DELETE /api/v1/admin/resiliency` | `resilience:manage` | Removes the override and goes back to the YAML; 404 if there is no override | Writes require a console session on the same origin and a CSRF token, and are recorded in the audit trail. ## Concurrent edits Every write carries the `version` you read. If someone else saved first, yours gets a 409 and the console keeps your draft for you to review or discard; a background refresh never overwrites a newer configuration. If the write was confirmed but the following sync failed, the response is a 503 indicating that the commit happened. Check the state before trying again. ## Defaults and field origins With the existing `boot_settings_view` flag, `GET /api/v1/admin/resiliency` adds an optional two-row `settings` projection. The circuit policy card shows each effective policy value separately from its field default (3 failures and 30 seconds), origin and change requirement. Omitted/null threshold and omitted/empty duration use defaults; explicit values equal to a default still have YAML origin. A managed override has Console origin for both fields. Reverting restores the original YAML origins. Untrusted programmatic origins remain **Unavailable**; this does not infer an installed circuit or provider health. Default/YAML rows describe file changes, which require a rollout. Console rows describe the existing hot override. The same versioned API can replace a YAML-based policy without a restart; each replica applies it through its normal control refresh. Local observations reset when the new policy is applied; optional shared observations use fenced PostgreSQL generations. Late completions cannot restore an obsolete circuit state. The existing stream-timeout editor separately receives an optional `defaults` map under the boot view: first byte 60s, idle 120s, maximum duration 30m and client write stall 60s. Equivalent Go duration formatting is expected. These are field defaults, not every operation's effective deadlines: model/runtime overrides can differ, and existing streams keep their captured clocks. Disabling the view removes only the new metadata; management permissions and enforcement remain unchanged. Inference retries remain explicit per-model consent. Values suggested when creating a retry policy are editor presets, not an automatic retry policy; no new retry permission or replay after a response begins is introduced here. The editor rejects malformed policy snapshots without echoing arbitrary values. An observed 401/403 or disabled endpoint clears its snapshot and draft; permission/flag loss invalidates pending replies. A later authorized load can restore the reader. Conflict or validation errors retain the correction draft and its captured version, including version zero; a reload never silently rebases it. ## Limits - Team roles neither see nor edit the global policy. - Reading the policy says nothing about the provider's health. - Shared failure counters require the explicit shared-circuit flag. No policy adds retries or guarantees zero errors during a rollout. ## See also - [Circuit breaker](/docs/features/resilience/). - [Configuration parity](/docs/reference/configuration-parity/): what can be edited in the console and what stays in the YAML. ## Shared policy definitions The [parameter registry](/docs/reference/parameter-registry/) owns the existing failure threshold and open-duration defaults and constraints used by Go policy validation, safe metadata and console controls. This does not report circuit health or add a mutation path. File changes require rollout; the existing managed override, authorization, version checks, audit and replica refresh retain their behavior. ## Active checks and shared circuits (V2) The new typed console controls require `boot_settings_view` so their parameter definitions are available. It is enabled in the bundled profile; if it is disabled or metadata is incompatible, the new controls remain read-only rather than guessing constraints. Enable the view and reload the console. YAML/API use remains available for headless operation. The console explicitly requests `GET /api/v1/admin/resiliency?version=2`. This adds the raw optional `health_checks` and `shared_circuit` profiles, their resolved defaults, per-field sources, operational flags and live edit rights. Default/version1 keeps its historical circuit-only projection. Parameter catalog V23 adds the two typed policy definitions without changing versions1–22. Edit active-check cadence, timeout, freshness, concurrency, failure/recovery thresholds and unknown-result policy in the existing resilience card. Edit the half-open lease when using shared circuits. Common `state_retention` and `state_timeout` controls expose idle cleanup and one shared-state action deadline, including effective values, defaults and sources. Configure an individual check in the model's target editor. The [health guide](/docs/features/resilience/) explains each default and the difference between metadata reachability and inference health. All writes retain the global version, live role, CSRF, whole-candidate validation and audit boundary. An old PUT that omits new profiles preserves their authoritative values; explicit `null` removes the named optional profile, subject to before/after permissions and license checks. Reverting also checks the profile being removed and the YAML profile being restored. A default-valued explicit object remains a real configuration choice. Health-profile writes require the applicable rights for both active checks and health routing; shared-profile writes require the shared-circuit right. The API exposes these edit capabilities without granting them. A reader can inspect effective configuration while an expired or restricted license makes the affected editor read-only. Operational flags remain independent of authorization. The V2 observation panel labels process-local circuits, PostgreSQL shared circuits and active checks separately. An empty or stale observation is not a healthy deployment. Shared mode does not add passive circuit coverage to unrelated realtime/resource helper paths, and a probe success never closes a passive circuit. Existing object retrieval remains pinned. # Stream timeouts **Last updated:** 2026-11-27T12:02:53-03:00 (UTC-3) Bound a streaming operation without cutting a healthy answer at the ordinary request timeout. The `stream_timeouts` flag is disabled by default. Enable it explicitly; otherwise streaming keeps the existing `request_timeout` deadline and these four clocks are inactive. ## Four clocks | Clock | Default | Allowed | | --- | --- | --- | | First byte | `60s` | `100ms`–`30m` | | Idle | `120s` | `0s`–`30m` | | Maximum | `30m` | `1s`–`24h` | | Client write | `60s` | `100ms`–`30m` | - **First byte** (`network.stream_first_byte_timeout`): each attempt's response headers to its first body byte. The response-header timeout remains separate. - **Idle** (`network.stream_idle_timeout`): a blocked read waiting for the provider's next byte. `0s` disables this clock. Keepalive comments count as traffic; time blocked writing to the client does not. - **Maximum** (`network.stream_max_duration`): the whole streaming operation, including queues, permitted attempts and response consumption. Retries do not receive a fresh duration budget. - **Client write** (`network.client_write_stall_timeout`): a downstream write and flush. A client that stops reading must release the operation's resources. With [`stream_settle_on_disconnect`](/docs/features/stream-usage/#when-the-client-disconnects) the gateway stops writing and reads the provider's answer to its end, still bounded by the idle and maximum clocks. The maximum starts at the provider-operation boundary, after bounded input parsing and preflight; it is not an upload or whole-listener deadline. The caller's earlier deadline or cancellation still wins. HTTP headers, upload/admission, async jobs and Realtime/WebSocket sessions retain their separate controls. Buffered answers and internal calls that return JSON still use the ordinary request deadline; being called by a stream does not turn them into streams. Cached SSE replay has no provider first-byte or read-idle clock. With stream clocks enabled, its replay uses the applicable maximum and downstream write bound. Cache lookup and embedding preparation retain their existing deadline policy; cache attribution stays separate from newly billed provider usage. A semantic lookup may call its configured embedding model: a hit avoids a new generation, not necessarily every provider operation. The enabled request-timeout header is validated on a cache hit too. A timeout before any downstream bytes follows the route's existing fallback policy. It does not enable retries for routes that prohibit them. After streaming starts, the gateway never replays the request or fabricates a successful terminal event. An incomplete usage proof remains unknown under the [quota](/docs/features/quota-protocols/) and [receipt](/docs/features/durable-usage/) contracts. ## Keepalive comments to the client A load balancer or proxy between the client and the gateway usually closes a connection that carries no bytes for some time (60 seconds is a common default). A reasoning model can think longer than that before its first token, or between two parts of an answer, and the client then loses a stream that was still working. The gateway can send an SSE comment to the client while the provider is silent: ```yaml network: client_keepalive_interval: 15s # off when empty or 0s (the default) ``` | Parameter | Default | Accepted values | When it applies | | --- | --- | --- | --- | | `network.client_keepalive_interval` | empty: off | empty or `0s` (off), `1s` to `5m` | At startup; restart each replica | After the interval passes with nothing written to the client, the gateway writes this comment and flushes it: ```text : keepalive ``` A line that starts with a colon is a comment in the [SSE format](https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation): parsers ignore it, and the blank line after it dispatches nothing, so the official OpenAI, Anthropic and Gemini SDKs and browser `EventSource` see no event. What it does and does not do: - It applies to every successful (`200`) `text/event-stream` answer on the inference API (`/v1/*` and `/v1beta/*`): Chat Completions, Responses, Messages, `streamGenerateContent` and translated streams alike, never to the console, the admin API, JSON answers or errors. - It starts when the gateway sends the client its response headers, which is when the provider's response starts. With keepalive on, a streamed answer's headers go out at once instead of with its first event, so the comment also covers the silence before the first token. A consequence for translated streams (Messages, Responses or Gemini clients on another provider): a stream that ends before its first byte now reaches the client as a `200` stream with an SSE error event, instead of a `502` JSON error, because the status is already sent. The wait for the provider's own response headers (`network.response_header_timeout`), and the wait for a first byte held for a retry policy, happen before that and are not covered. - It is written only between events: before the first byte, or after the blank line that ends an event. If the provider stops in the middle of an event, no comment is written until that event ends, so a line or an event is never split. - Each write of the answer restarts the interval, so a busy stream gets no comments. - It is written under everything else the gateway does with the stream: usage metering, budgets and TPM, the [stream usage filter](/docs/features/stream-usage/), the answer cache, translation, content capture, request logs and the time to first byte never see it. It does not reset the provider-side clocks above: a provider silent beyond `stream_idle_timeout` still ends the stream. - It stops when the answer ends, before the request is recorded, and when the client goes away. A comment blocked by a client that stopped reading fails with the stream's next write deadline (`client_write_stall_timeout`, with stream clocks on); one still blocked when the request ends is abandoned after one second. **Why it is off by default.** The comment is valid SSE, but it changes the bytes the client receives: a hand-written client that treats every block as JSON would fail on it. Turn it on when a load balancer in the path has an idle timeout shorter than your longest silence, and set the interval well below that timeout (for example `15s` for a 60-second idle timeout). Raising the load balancer's idle timeout is the alternative. **Inspect it.** **Settings & sources → Infrastructure → Inference HTTP** and `GET /api/v1/admin/config` (`infrastructure.inference_http.client_keepalive`) show the applied interval and its source. **Upgrade.** Nothing changes until you set the interval. Before rolling back to an older binary, remove `network.client_keepalive_interval`, because its strict YAML refuses it. ## Declarative configuration ```yaml features: stream_timeouts: true request_timeout_header: true # Requires the console and PostgreSQL, in addition to stream_timeouts: stream_timeout_management: true network: request_timeout: 120s stream_first_byte_timeout: 60s stream_idle_timeout: 120s stream_max_duration: 30m client_write_stall_timeout: 60s ``` The four network values use their defaults when omitted. A model can override individual clocks with `models[].stream_timeouts`, using `first_byte`, `idle`, `max_duration` and `write_stall`. An empty field inherits the effective network value; explicit `idle: "0s"` disables idle detection for that model. Clock configuration is retained but inactive when `stream_timeouts` is off. The existing versioned Model catalog editor/API owns model overrides. The independent flag `request_timeout_header` is enabled in the base profile. With it enabled, `X-Gateway-Timeout-Ms` accepts a whole number from 1 to 86400000. It can only lower the buffered/legacy deadline or the four enabled stream ceilings, never extend them. It also bounds an idle clock otherwise disabled with `0s`. Invalid values return `400`; when the flag is disabled the header is ignored, valid or invalid. The gateway does not forward this control header to the provider. ## Runtime editor Enable `stream_timeout_management` to edit the network clocks in **Providers → Resilience**. It defaults off and requires `stream_timeouts`, the console and PostgreSQL. It does not enable the separate [relay-admission](/docs/operate/network-configuration/#stream-relay-admission) feature or resize its boot limits. - `GET /api/v1/admin/stream-timeouts` requires `resilience:read`: returns the global version, optional override, four effective values and their sources. - `PUT /api/v1/admin/stream-timeouts` requires `resilience:manage`: send `version` plus `stream_timeouts` with at least one clock. Empty fields inherit YAML/default values. - `DELETE /api/v1/admin/stream-timeouts` requires `resilience:manage`: send `version` only. It removes the override and restores YAML/default values; no override returns `404`. Mutation JSON uses exact field names: `version` and `stream_timeouts` for PUT, and only `version` for DELETE. Case aliases, duplicate fields, null required values and trailing JSON are rejected before a configuration change; version `0` and explicit idle `"0s"` remain valid. Writes require the same-origin signed session and CSRF token, and record actor and request ID in the administrative audit. Team roles cannot read or edit global clocks. **API access** supplies complete examples with the current configuration version; the [OpenAPI](/docs/api/) is the request/response contract. The precedence for each network clock is default → YAML → console override; a model override then wins for its stream. API and console report the effective network values and `default`, `yaml` or `console` source. When the parent flag is off, Infrastructure shows Disabled and inactive values are null, with an empty source map. Missing or malformed active data is not shown as a default. Each operation keeps the snapshot it began with. Edits synchronize across replicas and affect new operations after their configuration refresh; an existing stream keeps its previous clocks. A stale version returns `409` and preserves the draft for review. If a write committed but refresh failed, read the current state before retrying; do not assume `503` means the write was rolled back. ## Diagnose an interruption Use `request_id` and `trace_id` in **Request logs**, structured logs and OTLP. `timeout_kind` identifies the clock that ended the operation: `first_byte`, `idle`, `max_duration`, `client_stall`, `request`, or `attempt` when the last provider attempt exceeded the alias's [attempt timeout](/docs/operate/network-configuration/#attempt-timeout) and no target was left. Empty means no timeout was established. A failed attempt followed by a successful fallback does not turn the successful operation into a timeout; inspect its child attempt for the earlier failure. Historical timeout values remain readable under the same permissions after a flag is disabled. Before headers, administrative stop remains `503 gateway_panic` and client cancellation remains `499`. Neither becomes a provider timeout. After headers, wire and recorded status preserve what was already sent, often `200`, including interrupted delivery; inspect termination, timeout kind, usage coverage and receipt state rather than status alone. A timeout label does not prove that a provider charged or authorize releasing an unknown financial reservation. ## Runbook 1. Choose clocks for the provider/model and the caller's deadlines; keep load balancer, ingress and orchestrator limits compatible with the expected stream lifetime. 2. Enable the parent flag, and optionally the runtime editor. Check effective values and sources in Infrastructure; admission sizes still require rollout. 3. Verify a successful stream, a silent provider, keepalives and a client that stops reading in an isolated environment. Check IDs and resource release after cancellation. 4. Change one clock and confirm the old stream keeps its snapshot while a new stream sees the new value on each replica. Test viewer denial, stale-version conflict and revert. 5. On rollback, revert the override/flags and verify new operations. Reverting clocks does not replay requests or change already-running operations. ## See also - [Network and admission](/docs/operate/network-configuration/), [console](/docs/features/console/) and [configuration parity](/docs/reference/configuration-parity/). - [Observability](/docs/features/observability/), [durable receipts](/docs/features/durable-usage/) and [resilience](/docs/features/resilience/). ## Shared policy definitions The [parameter registry](/docs/reference/parameter-registry/) supplies the existing four network-clock defaults and bounds and the four model-clock inheritance rules to Go validation, default resolution and trusted console constraints. Clock text retains its existing 16-byte UTF-8 limit. Idle zero remains an actual off switch; an empty model clock inherits the effective network clock. These definitions do not start a clock, change the parent or management flags, or grant editing permission. YAML changes need a rollout. The existing versioned runtime editor affects new operations after refresh, while each admitted operation keeps its snapshot. # Inference retries **Last updated:** 2026-11-27T01:08:49-03:00 (UTC-3) A transient 429 or 503 does not have to become an error for the client. For chat, Messages, Responses, embeddings, moderations and rerank, the gateway can repeat the call a few times on the same target, with a growing, randomized wait, respecting the provider's `Retry-After`. Flag: `inference_retries`. ## How to enable it ```yaml features: inference_retries: true models: - id: assistant capabilities: [chat, messages, responses] retry: max_attempts: 2 # per target, counting the first send initial_backoff: 100ms max_backoff: 2s targets: - {provider: openai, model: gpt-4.1-mini} - {provider: gemini, model: gemini-2.5-flash} ``` | Field | Values | | --- | --- | | `max_attempts` | 2 or 3 sends per target in total, including the first one. Required | | `initial_backoff` | 10 ms to 1 s. Required | | `max_backoff` | between `initial_backoff` and 10 s. Required | The policy applies to aliases with at least one target and one of the capabilities `chat`, `messages`, `responses`, `embeddings`, `moderations` or `rerank` (an alias without `capabilities` serves chat). In the console: **Model catalog → Edit routing → Bounded inference retries**, with versioning, audit and revert to YAML. Without `retry`, nothing changes. The API is `PUT /api/v1/admin/models/{id}` with the same `retry` object. ## Retry first, then fall back On an alias with several targets, **each target gets its own `max_attempts` before the alias falls back to the next target**, in the alias order. With two targets and `max_attempts: 2`, a request sends at most four times: two to the first target, two to the second. Why this order: a 429 or 503 is usually a short, local condition of one destination (a rate window, a busy replica). Retrying it first keeps traffic on the target the operator put first, usually the cheaper or preferred one, and only a target that stays unavailable passes the request on. A failure that retrying cannot fix moves on at once: - A `500` and other 5xx outside the list below are not retried; the alias falls back to the next target, as it does without a policy. - A refused admission (no destination slot) or an open circuit breaker does not wait for another attempt; the alias falls back, or answers 503 on the last target. - A target that cannot express the request in its protocol is skipped without any send (see [fallback across translation refusals](/docs/features/feature-routing/#fallback-across-translation-refusals)). ## How it works - **Retries only on:** transport failure, 429, 502, 503 and 504. A 500 is not retried. - **Wait:** exponential with full jitter. The ceiling doubles on each attempt up to `max_backoff`, and the actual wait is a random value between zero and that ceiling. - **`Retry-After`:** when the provider sends it, it becomes the minimum wait (seconds or an HTTP date). If it is invalid or larger than `max_backoff`, the gateway does not retry that target and moves on as if the attempts were spent: the next target, or the original response, `Retry-After` included, on the last one. - **Total deadline:** the configured operation deadline covers the whole call, including waits and response consumption. `models[].request_timeout` overrides `network.request_timeout`; the compiled network default is two minutes. A wait that would end after the deadline is not taken; the gateway keeps the answer it has. Canceling the request interrupts the wait (499). - **Attempt timeout:** with `attempt_timeouts` on, the alias's [`attempt_timeout`](/docs/operate/network-configuration/#attempt-timeout) bounds how long each attempt may wait for the provider to start answering. An attempt it ends is not repeated on the same target: the next target is tried, or the client gets 504. - **Capacity and circuit breaker:** the target's slot is released during the wait and requested again on each attempt; the circuit breaker can block an attempt. - **Tracing:** each send has its own span and an `upstream_attempt` log, with the same request ID. Under a policy the log record also carries `attempt` (1, 2, 3) and `max_attempts`. ## Before the first byte, never after A send is repeated only while nothing has reached the client. - **JSON answers.** The decision is made on the provider's status line, before any header or byte is sent to the client. - **Streams.** With a policy, the gateway holds a streamed answer until its **first byte** before it starts the client's stream, while another send (a retry or a next target) remains. A provider whose stream closes or fails before that first byte is retried like a transport failure. Once the first byte has been relayed the stream belongs to that send: a later break is reported to the client as an interrupted stream and is never repeated. The client's response headers wait for that first byte; without a policy streams are relayed at once, as before. - **Translated streams.** For a target the gateway translates (Anthropic, Gemini, Bedrock, Cohere, OCI, or an OpenAI target with `api: responses`, or `api: auto` when it chose Responses), a provider stream that breaks before its first event becomes an in-band error event of the translated stream, which is the first byte: it is relayed and not retried. A failure before the provider's response headers is still retried. - **Stream clocks.** A [stream timeout](/docs/features/stream-timeouts/) that fires (`first_byte`, `idle`, `max_duration`) is not retried on the same target: the provider accepted the request and was still working on it, so a second send would pay for the same generation twice. It still falls back to the next target, as without a policy. - **Answers already served.** A body the gateway could not read or translate after the provider answered, and a buffered JSON answer to a stream request (`provider_did_not_stream`), are not retried: the provider did the work. ## Native Gemini generateContent `gemini_retries` (off by default; requires `inference_retries`) lets an alias's retry policy also repeat native Gemini `POST /v1beta/models/{model}:generateContent` and `:streamGenerateContent` (T168), with the same attempts, backoff and `Retry-After` floor: a retryable status (429, 502, 503, 504) or a transport failure is repeated on the same target, before the next target, and only before any byte reaches the client. A request with `cachedContent` or a provider-hosted tool is sent once per target. The flag also gates the translated `generateContent` ingress (a `generate_content` alias served by another provider). The console offers the policy on a `generate_content` alias only with the flag on. ## What is never retried Each case is something a second send could duplicate or break. | Request | Retried | Why | | --- | --- | --- | | Chat Completions, with or without function tools | Yes | The provider keeps no conversation state; the client resends the history and runs its own tools | | Chat with a hosted tool (a `tools[].type` other than `function` or `custom`, or `web_search_options`) | No | The tool runs at the provider; its effect or charge could happen twice | | Messages | Yes | Same as chat | | Messages with `container`, `mcp_servers` or a server tool (any `tools[].type` other than `custom`) | No | Code execution, remote MCP calls and server tools act at the provider | | Responses, stateless | Yes | Same as chat | | Responses with `store: true` | Yes | The client only ever receives the ID of the send that succeeded. A failed send may still leave a stored response at the provider (for example after a transport failure), but nothing references it | | Responses with `previous_response_id` or `conversation` | No | The state lives at one provider; the continuation stays pinned there | | Responses with `background`, a stored `prompt`, an `item_reference` input, a reasoning item without `encrypted_content`, a `file_id` content part or a hosted tool (code interpreter containers, file or web search, MCP, image generation, computer use) | No | Each continues or creates provider state, reads a stored object, or acts from the provider | | Embeddings, moderations, rerank with `stream`, `tools`, `tool_choice`, `functions`, `function_call`, `previous_response_id`, `conversation` or `background` | No | Unknown extensions that could select streams, tools or state never inherit permission to replay | | Native Gemini `:generateContent` and `:streamGenerateContent`, with `gemini_retries` | Yes | Stateless like chat, with or without client function declarations (`tools[].functionDeclarations`); before the first byte only | | Gemini with `cachedContent` (or `cached_content`) or a hosted tool (`googleSearch`, `codeExecution`, `urlContext`, ...) | No | The cached context lives at one provider; hosted tools act from it | | Gemini without `gemini_retries`, decisions, MCP tools, audio, image, video | No | Not covered by this policy | The same rules decide [Responses fallback](/docs/features/feature-routing/#responses-fallback): a request that is not retried is not sent to another target either. ## Things to watch for - **Billing.** Repeating a POST can lead to a new charge at the provider, for example when a transport failure happened after the provider started the work. Turn it on only where that is acceptable. - **Estimated cost.** The reported usage comes from the last response; when there was more than one send, valuation marks the cost as unknown. The receipt represents the client's request, not each send. - **Budgets and TPM.** A quota reservation covers one send to one target. When a budget or TPM policy covers the alias, a request to an alias with a retry policy is refused with 422 before any provider call, as one to an alias with more than one target is. ## Limits - At most `max_attempts × targets` sends per request, all inside the request deadline. - The decision is per process; retries are not coordinated across replicas. - Turning the flag off stops retries on new requests; requests already admitted keep the configuration they were admitted with. ## Upgrade notes - The single-target rule is gone: a `retry` policy is valid on an alias with any number of targets, and on `chat`, `messages` and `responses` aliases. Existing embeddings, moderations and rerank policies behave as before on a single target, with two refinements: a transport-failure retry now also needs its wait to fit the deadline, and an answer the gateway received but could not read (an adapter's normalization error) is no longer sent again. - An alias with chat that already had no `retry` is unchanged. Adding `retry` to a chat alias delays the client's stream headers until the provider's first byte. ## See also - [Routing and resilience](/docs/features/feature-routing/), including fallback across translation refusals and Responses fallback. - [Circuit breaker](/docs/features/resilience/). - [Weights and capacity per target](/docs/features/routing-and-admission/). - References: [Retry-After in RFC 9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-retry-after). ## Shared policy definitions The [parameter registry](/docs/reference/parameter-registry/) shares the existing retry bounds with Go validation and console controls. All three members are required when a retry policy is configured; omitting the policy adds no retries. The form’s initial values (2 total attempts, 100ms initial backoff and 2s maximum) are creation presets, not backend defaults. Maximum backoff must also be at least the configured initial backoff. # Request parameter policy **Last updated:** 2026-11-27T01:59:36-03:00 (UTC-3) An alias often needs the same request parameters on every call: a reasoning model that should think at `minimal` effort unless the app asks for more, a cheaper `service_tier`, `store: false` for every call to a provider that keeps conversations by default, or a ceiling on output tokens so one request cannot run up the bill. Without the gateway, every application has to know and send these values, and a client that sends a parameter one provider rejects fails on that provider only. The request parameter policy sets these per target, in the gateway, so applications stay unchanged and each fallback target gets the parameters it needs. Flag: `request_parameter_policy` (off by default). ## How to enable it ```yaml features: request_parameter_policy: true models: - id: gpt-5-mini unsupported_parameters: refuse # or drop (see below); default refuse targets: - provider: openai model: gpt-5-mini request_defaults: # only when the client did not send them reasoning_effort: minimal service_tier: flex request_overrides: # always, replacing the client's value store: false max_output_tokens: 4096 # ceiling on the output limit drop_parameters: [temperature] # removed before this target is called # A path removes a member below a top-level field: # drop_parameters: [temperature, "tools[*].function.strict", metadata.user_id] - provider: anthropic # fallback: its own policy, or none model: claude-sonnet-4-5 request_defaults: {temperature: 0.2} ``` With the flag off, the fields stay stored and validated but nothing is applied: requests go out exactly as before. Turning the flag on or off takes effect on the next request (it is a runtime flag, editable in **Settings → Features**). ## Fields All fields are optional. They belong to one target (`models[].targets[]`), except `unsupported_parameters`, which belongs to the alias. | Field | Default | Values | | --- | --- | --- | | `models[].targets[].request_defaults` | none | Map of allowlisted parameter → value. Set only when the client did not send the parameter, or sent `null`. | | `models[].targets[].request_overrides` | none | Same allowlist. Always set, replacing what the client sent. A name cannot be in both maps. | | `models[].targets[].max_output_tokens` | none (no ceiling) | Whole number from 1 to 10,000,000. | | `models[].targets[].drop_parameters` | none | Up to 32 distinct entries. An entry is a top-level field name (lowercase letters, digits and `_`) or a [path below one](#paths-in-drop_parameters), such as `tools[*].input_examples`. `model`, `messages`, `input`, `contents` and `stream` cannot be dropped, nor anything below them, nor `store` (without it a Responses provider keeps the conversation, its default) or `stream_options` (without it a stream loses the usage the gateway meters). The cost of that protection: a compatible backend that rejects either field cannot be helped by dropping it here. A name cannot also be set by `request_defaults` or `request_overrides`. Names are those of the body the target receives: see [which names apply](#drop_parameters-names). | | `models[].targets[].drop_presets` | none | `[sampling]`: a ready-made list added to `drop_parameters`. See [drop presets](#drop-presets). | | `models[].targets[].unsupported_parameters` (alias) | `refuse` | `refuse` or `drop`. | The policy applies to aliases whose capabilities are `chat`, `messages`, `responses` or `generate_content`; a policy on an embeddings, images or other alias is refused when the configuration loads. ### The parameter allowlist `request_defaults` and `request_overrides` accept only these names, by their Chat Completions name. An unknown name or a value of the wrong type is refused when the configuration loads or when the console or API saves the model, never at request time. | Parameter | Value | | --- | --- | | `reasoning_effort` | A word such as `minimal`, `low`, `medium` or `high`, or an object `{effort, summary}` | | `service_tier` | A word such as `auto`, `default`, `flex` or `priority` | | `temperature` | Number from 0 to 2 | | `top_p` | Number from 0 to 1 | | `max_tokens`, `max_completion_tokens` | Whole number from 1 to 10,000,000; at most one of the two per map, and not above `max_output_tokens` | | `verbosity` | `low`, `medium` or `high` | | `parallel_tool_calls` | `true` or `false` | | `seed` | Whole number | | `presence_penalty`, `frequency_penalty` | Number from -2 to 2 | | `store` | `true` or `false` | | `reasoning_summary` | `auto`, `concise` or `detailed`: asks the provider for a summary of its reasoning. See [reasoning summaries](#reasoning-summaries) | The list is closed on purpose: these are the parameters that change cost, latency or retention without changing what the conversation means. Fields that do (`messages`, `tools`, `response_format`) are left to the application. **`reasoning_effort` as an object.** Some values exist only in the Responses API, such as a reasoning summary. The object form carries them: `reasoning_effort: {effort: high, summary: auto}` reaches a Responses API target as `reasoning: {effort: high, summary: auto}`. Any other target receives only `effort` (`"high"`); an object without `effort` is not applied to it. A client may not send the object form itself: on Chat Completions it is still refused with 422, as before this feature. On an [`api: auto`](/docs/features/protocol-translation/#api-auto-the-api-chosen-per-request) target the policy runs before the API is chosen, so an object effort, or a policy effort together with the client's function tools, sends that attempt to the Responses API; a default or override the chosen API has no field for (`seed` on Responses) is reported in `parameters_not_applicable`. ### Reasoning summaries A reasoning model does not always return what it thought. The OpenAI Responses API returns a reasoning summary only when the request asks for one (`reasoning.summary`), and recent Claude models return an empty thinking block unless the request sets `thinking.display` to `summarized`. A client that shows the reasoning to its user then shows nothing, and the fix belongs in every application. `reasoning_summary` asks for the summary in the gateway, per target: ```yaml models: - id: claude capabilities: [messages] targets: - provider: anthropic model: claude-sonnet-4-6 request_defaults: reasoning_summary: auto # only when the client did not choose ``` | Target receives | What is set | When | | --- | --- | --- | | Anthropic Messages, native `/v1/messages` | `thinking.display: "summarized"` | Only when the request's `thinking.type` is `enabled` or `adaptive`. A request without thinking is not changed. | | Anthropic Messages, translated from Chat Completions | `thinking.display: "summarized"` | Only when the request has a `reasoning_effort`, which is what turns thinking on. | | OpenAI Responses API, native `/v1/responses` or translated | `reasoning.summary` with the configured value | On every request to the target, like the object form of `reasoning_effort`. Use it only on a reasoning model: any other model refuses the field. | | Chat Completions on an `openai` provider, Gemini, Bedrock, Cohere, OCI | Nothing | The protocol has no field for a summary. The entry is named in `parameters_not_applicable`. | - **As a default** (`request_defaults`), the client's own choice wins: a request that already says `thinking.display: "omitted"` or `reasoning.summary: "concise"` goes out as the client wrote it. - **As an override** (`request_overrides`), the configured value replaces the client's. Use it when the operator, not the application, decides that summaries are returned. - Anthropic has one summary level, so `auto`, `concise` and `detailed` all become `summarized` there. To hide the thinking instead, drop the client's choice with `drop_parameters: [thinking.display]` on a model whose default is `omitted`. - A summary is billed as output tokens by the provider. That is why it is off unless configured. - On an [`api: auto`](/docs/features/protocol-translation/#api-auto-the-api-chosen-per-request) target, `reasoning_summary` sends the attempt to the Responses API, like the object form of `reasoning_effort`: Chat Completions has no field for it. - The summary is applied after the other defaults and overrides, so it is kept when the policy also sets `reasoning_effort`. - The attempt is logged with `parameters_defaulted` or `parameters_overridden` naming `reasoning_summary`, only when it changed the request. **`max_tokens` and `max_completion_tokens` are one parameter.** A default for either applies only when the client sent neither; an override replaces whichever the client sent, so the request never carries both. ## What happens to a request For each attempt, the gateway builds the body that target receives, starting from the client's body every time, in this order: 1. `drop_parameters` removes the listed fields. 2. `request_defaults` fills the parameters the client left out. A default or override this target's protocol cannot carry (for example `seed` or `verbosity` on Anthropic, `seed` on the Responses API) is not added: it is named in `parameters_not_applicable` instead, so a policy never makes a request fail, or report a drop, for a field the client did not send. 3. `request_overrides` sets its parameters, replacing the client's. An override the target's protocol cannot carry is skipped and logged in `parameters_not_applicable`; the client's own value for that field then follows the `unsupported_parameters` mode (dropped or refused), never the override. 4. `max_output_tokens` lowers a larger `max_tokens` or `max_completion_tokens`. Any JSON number with a whole value counts (`500`, `500.0` and `5e2` are all lowered); a limit that is not a positive whole number (`10.5`, `"500"`, `0`) is refused with 422 before any provider call, because the ceiling cannot be enforced on it. When the request has no limit, or only `null` limits, `max_completion_tokens` is set to the ceiling and the null keys are removed. 5. With `unsupported_parameters: drop`, fields the target's protocol declares unsupported are removed (see below). 6. Translation to the target's protocol (Anthropic Messages, Gemini, Bedrock Converse, Cohere, OCI, the Responses API). Because the body is rebuilt per attempt, a fallback target never inherits the previous target's defaults or drops. The client's own body, the semantic cache key and guardrail checks see the request as the client sent it. Example: with the configuration above, the client sends ```json {"model": "gpt-5-mini", "messages": [{"role": "user", "content": "Hi"}], "temperature": 0.5, "max_completion_tokens": 9000, "store": true} ``` and OpenAI receives ```json {"model": "gpt-5-mini", "messages": [{"role": "user", "content": "Hi"}], "max_completion_tokens": 4096, "store": false, "reasoning_effort": "minimal", "service_tier": "flex"} ``` The answer carries `X-Gateway-Dropped-Parameters: temperature`. ### Unsupported parameters: refuse or drop A translated target supports a known set of fields. Anthropic Messages has no `seed` or `logprobs`, for example, and Gemini has no `logprobs`. By default (`refuse`), such a target cannot take the request: when the alias has another target, the refusing one is skipped without a call and the next target is tried ([fallback across translation refusals](/docs/features/feature-routing/#fallback-across-translation-refusals)); when no target accepts it, the request is answered `422 unsupported_on_provider` before any provider call, naming the field. This is the behavior without this feature. With `unsupported_parameters: drop`, those fields are removed for that target instead, and the request goes through. This is for clients that send parameters their own default provider understands and that the operator accepts to lose on another one. - Only whole fields the translation declares unsupported are dropped. A value the target cannot honor is still refused: `reasoning_effort: minimal` on Anthropic, or a `max_tokens` below the thinking budget, still answers 422. - `store: false` on a native protocol is met without being sent and is not reported as a drop. - Targets that receive the body as it is (Chat Completions on an `openai` provider, SageMaker) declare nothing, so nothing is dropped there. A field an OpenAI model refuses (for example `temperature` on a reasoning model, which answers 400) is removed with `drop_parameters` on that target. - A dropped field can change the answer (`n`, `logprobs`) or its cost. That is why every drop is reported, never silent. ## What each route applies | Route | Applied | Notes | | --- | --- | --- | | `/v1/chat/completions` | Everything | In Chat Completions names. | | `/v1/messages`, `/v1/responses`, Gemini `generateContent` **translated** to another provider | Everything | The request goes through the chat pipeline, so the names are Chat Completions names (`max_completion_tokens`, `reasoning_effort`). `X-Gateway-Dropped-Parameters` uses the client's names (`max_tokens`, `metadata.user_id`, `reasoning.effort`). | | `/v1/messages` **native** (every target Anthropic) | `temperature`, `top_p`, `service_tier`, the output limit (`max_tokens`) and `max_output_tokens`; `reasoning_summary` as `thinking.display`; `drop_parameters` in Messages names | `reasoning_effort` (thinking needs a token budget), `seed`, the penalties, `store`, `verbosity` and `parallel_tool_calls` have no Messages field and are not applied. | | `/v1/responses` **native** (OpenAI Responses API) | `temperature`, `top_p`, `service_tier`, `store`, `parallel_tool_calls`; the output limit as `max_output_tokens`; `reasoning_effort` as `reasoning` (string → `reasoning.effort`, object → its members); `reasoning_summary` as `reasoning.summary`; `verbosity` as `text.verbosity`; `drop_parameters` in Responses names | A default fills only the members of `reasoning` or `text` the client left out. `seed` and the penalties do not exist in Responses and are not applied. `unsupported_parameters` does not apply: the body is not translated. | | Gemini `generateContent` **native** (every target Gemini) | Nothing | The request is passed through unchanged; the `upstream_attempt` log names every policy entry of the target in `parameters_not_applicable`, so it does not look applied. The same alias's `/v1/chat/completions` route does apply the policy. | | Embeddings, images, audio and the other routes | Nothing | A policy on such an alias is refused when the configuration loads. | A policy entry that does not apply to the route is named in `parameters_not_applicable` of the request log, so a missing effect is visible. ### `drop_parameters` names `drop_parameters` removes top-level fields of the body this target receives, before translation, so the names depend on the path the request takes, not on the route the client called: - `/v1/chat/completions` and every **translated** route (Messages, Responses or GenerateContent to another provider): Chat Completions names. On a Messages request, `metadata.user_id` is `user` and `max_tokens` is `max_completion_tokens`. - Native `/v1/messages` and `/v1/responses`: that dialect's own names (for example `metadata` or `top_k` on Messages, `metadata` or `include` on Responses). An alias that changes from native to translated (adding a target of another provider) therefore changes which fields its names match. Review `drop_parameters` when you change an alias's providers; a name that does not occur in the body removes nothing. ### Drop presets Some lists are the same on every target of a kind. The Claude models from Opus 4.7 on refuse the sampling parameters (`temperature`, `top_p`, `top_k`) with a `400`, and every client that still sends one fails on them. Instead of writing the three names on each such target: ```yaml targets: - provider: anthropic model: claude-opus-4-8 drop_presets: [sampling] ``` | Preset | Removes | | --- | --- | | `sampling` | `temperature`, `top_p`, `top_k` | - A preset is exactly its list, added after `drop_parameters`; a name in both is removed once. What it removes is reported by name in `X-Gateway-Dropped-Parameters` and `parameters_dropped`, only when the request carried it. - It is off unless the target lists it, and applies under the same flag and on the same routes as `drop_parameters`. - A name a preset removes cannot also be set by `request_defaults` or `request_overrides` on that target. - The list is closed. A preset never grows a name between releases without a line in the changelog, because a dropped parameter can change an answer. - It removes the parameter whatever its value. A model that accepts the default value only (`temperature: 1`) loses nothing by it. ### Paths in `drop_parameters` Some fields a provider refuses are not at the top of the body. A Bedrock or Vertex Claude target refuses `input_examples` inside a tool definition, a compatible server refuses `strict` inside a function, and neither can be removed by dropping the whole `tools` list. A path removes only that member: | Entry | Removes | | --- | --- | | `temperature` | The top-level field. | | `metadata.user_id` | The member `user_id` of the object `metadata`. | | `tools[*].input_examples` | `input_examples` from every element of the list `tools`. | | `tools[*].function.strict` | `strict` from the `function` object of every tool. | | `response_format.json_schema.strict` | A member three objects deep. | - A dot enters an object. `[*]` enters every element of a list. There are no indexes (`[0]`), no quoting and no recursive search, on purpose: a path says exactly where it reaches. - The first step is a top-level field name, with the same rule as a plain name. The steps after it may use upper case, `_`, `$` and `-`, because member names inside schemas do. A path has at most 8 steps (`[*]` counts as one) and 200 characters, and always ends in a member name: a path removes members, never the elements of a list. - A path whose first step is `model`, `messages`, `input`, `contents`, `stream`, `store` or `stream_options` is refused at load. The conversation is not edited by this policy. - Only the member is removed. The object that held it stays, even when it becomes empty: `metadata.user_id` on `{"user_id": "u1"}` leaves `"metadata": {}`. Drop `metadata` itself when the provider refuses an empty object. - Where the body has another shape (a string where the path expects an object), or the member is absent, nothing is removed and nothing is reported. - Members keep the client's order, and every value that is not on the path keeps its bytes, so a provider's prompt cache keeps matching the parts that did not change. Only the objects and lists the path walks through are written again, compactly (without the client's spaces between members). When a member name occurs twice in one object, every occurrence is removed. - A removed path is reported like a name: `X-Gateway-Dropped-Parameters: tools[*].input_examples` and `parameters_dropped` in the attempt log, only when it removed something. A path is reported as it is configured; it is not rewritten to the client's names on a translated route. - A client field whose own name looks like a path (a top-level field literally called `metadata.user_id`) is not what a path entry names, and is left alone. - The [context window check](/docs/features/context-window-check/) estimates the body the target receives: what a path removes (a long tool description, for example) is not counted for that target, whether or not the policy flag is on, as with a field dropped by name. - On a translated route the path is applied to the Chat Completions body, before translation, so it uses Chat Completions shapes (`tools[*].function.strict`). On native `/v1/messages` and `/v1/responses` it uses that dialect's shapes (`tools[*].input_examples`). ## Response header and logs `X-Gateway-Dropped-Parameters` lists, comma-separated, the fields the answering attempt removed (`drop_parameters` and `unsupported_parameters: drop`). It is absent when nothing was removed. After a fallback, it describes the target that answered. Each `upstream_attempt` log record of an attempt that changed something adds these attributes, with parameter names only, never values or content: | Attribute | Meaning | | --- | --- | | `parameters_defaulted` | Defaults applied | | `parameters_overridden` | Overrides applied | | `parameters_capped` | Output limit lowered or set by `max_output_tokens` | | `parameters_dropped` | Removed by `drop_parameters` | | `parameters_unsupported_dropped` | Removed by `unsupported_parameters: drop` | | `parameters_not_applicable` | Policy entries this route has no field for | ```json {"msg":"upstream_attempt","provider":"openai","model":"gpt-5-mini","status":200,"parameters_defaulted":"reasoning_effort,service_tier","parameters_dropped":"temperature"} ``` ## Budgets and TPM Budgets and TPM reserve tokens from the request before the call, and only single-target aliases are protected. With the policy on, the reservation is computed from the body the target will receive, so a lower `max_output_tokens` lowers the reservation and an override that raises the limit raises it. A policy that adds a parameter the quota profile does not accept (`service_tier`, `verbosity`) is treated exactly as if the client had sent that parameter: under a budget or TPM policy the request is refused, because its cost cannot be reserved. ## Console and API **Model catalog → Edit routing**: each target has a **Request parameters** block (defaults, overrides, maximum output tokens and drop parameters) and the alias has **Unsupported request parameters**. The model API (`PUT /api/v1/admin/models/{id}`) takes the same fields as the YAML, with the same validation; a model saved from the console is versioned and audited like any other model change. With the flag off, a stored policy stays visible and removable, marked inactive. ## Limits - An unreadable output limit (for example `max_tokens: 10.5`) is refused when the attempt that has a `max_output_tokens` ceiling is reached, not before the first target is tried; an earlier target without a ceiling may already have been called. - Defaults and overrides set only top-level parameters; nested fields (`tool_choice` members) are not set. `drop_parameters` removes nested members by [path](#paths-in-drop_parameters), except below the protected fields (`stream_options`, `messages`). Asking a stream for its usage is a separate alias setting, [`stream_usage: inject`](/docs/features/stream-usage/#ask-for-the-usage-on-the-clients-behalf), applied to each attempt after this policy and independent of its flag. - Native Gemini `generateContent`, batch files and the other routes are not covered (native `generateContent` logs that it did not apply). - `drop_parameters` names are not checked against the dialect at load: a name that does not occur in the body removes nothing. - The semantic cache keeps answers made with and without the policy apart: turning the flag on or off on an alias with a policy does not serve the other state's answers. - The ceiling is set as `max_completion_tokens` when the client sent no limit. An OpenAI-compatible server that reads only `max_tokens` should get `request_defaults: {max_tokens: N}` as well, so the client-less case sends `max_tokens` and the ceiling lowers it. - `service_tier` and `reasoning_effort` values are checked for shape, not against each provider's current list: a value the provider rejects comes back as the provider's 400. ## Upgrade Nothing changes until the flag is turned on and a policy is declared. Existing aliases keep `refuse`, the previous behavior. # Costs and pricing **Last updated:** 2026-11-15T08:07:18-03:00 (UTC-3) Without controls, AI cost only shows up on the next month's invoice. The gateway finds each model's price on its own, estimates the cost of each call and can stop spending before it happens. ## What exists | Feature | What it does | Flag | Learn more | |---|---|---|---| | **Automatic pricing** | Reads each model's price from public catalogs (community cost map, models.dev, OpenRouter, DeepInfra), with voting across sources; media per image, character or second | `automatic_price_catalog`, `price_source_cost_map`, `price_source_modelsdev` | [Automatic pricing](/docs/features/automatic-pricing/) | | **Advisory cost calculator** | Exact selected-source/target base quote, source freshness and per-request/day/30-day projections; unknown/partial stays explicit | `advisory_cost_calculator` | [Calculator](/docs/features/cost-calculator/) | | **Per-call valuation** | Estimated cost of each request, with the price at that moment frozen | `usage_valuation` | [Valuation](/docs/features/usage-valuation/) | | **Service-tier pricing** | Prices each answer at the tier the provider reports (priority, flex, batch); an unpriced tier stays unknown | follows `usage_valuation`, `budget_limits` | [Service tiers](/docs/features/service-tier-pricing/) | | **Discounts and margins** | Discount negotiated with the provider and pass-through margin | `cost_adjustments` | [Valuation](/docs/features/usage-valuation/) | | **Budgets** | Dollar limit per day or month, per key, team, model, user, project, organization or end user. The reservation is made before sending | `budget_limits`, `end_user_budgets` | [Budgets and TPM](/docs/features/budgets-and-tpm/) | | **TPM and TPD** | Tokens-per-minute and tokens-per-day limits | `tpm_limits`, `tpd_limits` | [Budgets and TPM](/docs/features/budgets-and-tpm/) | | **RPM** | Requests-per-minute limit, per key, team or end user | `rate_limits`, `end_user_rate_limits` | [Access control](/docs/features/access-control/) | | **Concurrency caps** | Inference requests a key, or a team's keys together, may have in flight at once, counted per replica; over it 429 at once | `concurrency_limits` | [Access control](/docs/features/access-control/#concurrent-requests-per-key-and-team) | | **Required attribution** | A team or key requires every inference request to declare an end user and usage tags, so end-user and tag limits cannot be skipped; refused before any provider call | `attribution_requirements` | [Budgets and TPM](/docs/features/budgets-and-tpm/#require-the-end-user-and-tags) | | **Cost tags** | Finite metadata (environment, project) to group cost | `usage_tags` | [Tags](/docs/features/usage-tags/) | | **Cost optimization** | Shows where switching models or using the cache would save money | `cost_optimization` | [Console](/docs/features/console/) | | **Native billing** | Imports OpenAI and Anthropic invoices and reconciles them with measured usage | `quota_finance` | [Native billing](/docs/features/native-billing-imports/) | | **Manual price book** | Manual price only for what no catalog publishes | `manual_price_catalog` | [Price book](/docs/features/pricing/) | | **GPT Image token pricing** | GPT Image aliases valued per token by category (text and image input, image output) from each answer's usage | `image_token_pricing` | [Valuation](/docs/features/usage-valuation/#gpt-image-tokens) | ## An estimate, not an invoice Valuation is advisory: it uses the public price and the tokens the provider reported. It helps you decide and stop overspending, but it does not replace the provider's invoice. The [billing imports](/docs/features/native-billing-imports/) do the reconciliation. # Advisory cost calculator **Last updated:** 2026-11-23T10:59:54-03:00 (UTC-3) Estimate the base model rate for a stated quantity before sending a request. The calculator performs no inference, reserves no budget, writes no ledger and never changes historical spend. It identifies the rate and coverage behind the result; an estimate is not an invoice. ## Enable and open ```yaml features: external_model_catalog: true advisory_cost_calculator: true # Also needed only for configured-target quotes: automatic_price_catalog: true ``` The new flag defaults to false and is runtime-mutable through the normal feature API and Settings & sources. It is a global operator/catalog surface; global readers with `catalog:read` can calculate, while scoped team roles cannot see private global pricing. Flags do not grant permissions. Open **Model catalog**, choose a discovered model or an exact configured target, and select **Estimate cost**. The anonymous Hub remains metadata-only. ## Quantities and units Choose one profile; the API rejects mixed fields rather than guessing conversions. | Profile | Request fields | Published unit | | --- | --- | --- | | Text | `input_tokens`, `output_tokens` as canonical integer strings; at least one supplied, omitted other defaults to0 | USD per million text tokens | | Media | Decimal-string `quantity` plus matching explicit `unit` | Per image, character, audio second or video second only when the source publishes that supported unit | Counts accept up to18 integer digits; media quantity additionally accepts up to9 fractional digits. No signs, exponents, whitespace, nulls or JavaScript numeric coercion. Optional `requests_per_day` is an integer string defaulting to1. Daily and **30-day** planning amounts are exact server-derived values, not a calendar-month bill. The server uses rational arithmetic and renders exact decimal USD strings. For an illustrative rate of1.50/6.00 USD per million input/output tokens, 1,000,000 input and250,000 output tokens cost3 USD at the base rate; ten such requests/day give30 USD/day and900 USD/30days. These are worked arithmetic values, not a claim about any provider's current price. ## Source identity and review POST `/api/v1/admin/pricing/estimate` selects one exact public source (`openrouter`, `deepinfra`, `cost_map`, `modelsdev`) plus its exact `model_id`, or `source:configured` plus `alias`, `provider_id` and `model_id`. The latter reuses automatic resolution/voting and the enabled manual price book, whose entry in effect wins (`manual_fallback: true`, plus `override: true` when it replaced an available automatic price). Identifiers are bounded to4096 UTF-8 bytes inside a16KiB JSON body. The server accepts no client price or URL and uses only approved catalog origins. The response echoes selection `source`, identifies actual `rate_source` when relevant, preserves source URL/time/staleness/confidence, and provides `basis_id`. An optional `expected_basis_id` returns409 when that reviewed rate basis changes; it does not authenticate a payment or approve budget admission. Quantities and projections do not change rate identity. A new quote can be reviewed explicitly after a conflict. Use API access for the complete session-authenticated curl example. With an existing private cookie jar and an exact selected published model: ```sh BASE_URL='http://localhost:8080' : "${COOKIE_JAR:?Use the existing administrative session cookie jar}" : "${MODEL_ID:?Choose the exact model ID from the selected source}" jq -n --arg id "$MODEL_ID" '{source:"openrouter",model_id:$id,input_tokens:"1000000",output_tokens:"250000",requests_per_day:"10"}' | curl --fail-with-body -sS -b "$COOKIE_JAR" -H 'Content-Type: application/json' \ --data-binary @- "$BASE_URL/api/v1/admin/pricing/estimate" ``` No provider API key is needed for these public-source reads. Existing snapshots retain the bounded cache policy; the calculator does not bypass TTL or fetch from arbitrary input URLs. For a direct public source with no usable snapshot,503 is an error rather than a zero quote. Configured targets preserve the resolver's unknown/conflict status unless an enabled manual price prices them; unresolved configured sources return200 with an unknown result and no invented total. ## Coverage and unknowns - **Available:** all applicable requested quantities have supported rates; exact totals and projections are shown. This describes numeric quote coverage, not provider/account/model availability. - **Partial:** known components have an explicit known subtotal; missing coverage never becomes a grand total. - **Unknown:** missing/unsupported rates remain unknown, including uncorroborated all-zero community rows under the existing policy. - **Conflict:** a configured rate-source disagreement remains visible and is not silently averaged. First-party published zero and corroborated/manual rates retain their existing provenance rules. A stale snapshot may support a clearly labeled reference quote; it never proves the current charge. Public single-source quotes are not a voting/corroboration guarantee. Text quotes accept optional `service_tier` (`default`, `priority`, `flex`, `batch`; `fast` is read as `priority`): the quote then prices that tier's published rate with its own source, echoes `service_tier`, and stays unknown (`service_tier_unpriced`) when no source publishes the tier. Warnings name the tier covered (`standard_service_tier_only` or `service_tier__only`); see [service-tier pricing](/docs/features/service-tier-pricing/). Coverage excludes cache discounts, context tiers, image-token dimensions, hosted tools, contract discounts, taxes, provider minimum billable durations/rounding and other extras. The calculator does not tokenize a prompt or infer missing quantities. Use measured usage, approved enforcement prices and [billing reconciliation](/docs/features/native-billing-imports/) for their separate financial purposes. Selection/identity/permission changes clear held UI results; the browser never recomputes money with binary floats. See [registry](/docs/features/model-registry/), [automatic pricing](/docs/features/automatic-pricing/), [manual price book](/docs/features/pricing/) and [valuation](/docs/features/usage-valuation/). ## Public same-workload planning The separate [public workload calculator](/docs/features/workload-comparison/) uses original source offers under `model_registry_cost_comparison`, independently of this protected interface. It reuses exact arithmetic but has no configured/manual source input, private alias or price-book disclosure. Public all-known-zero text sets remain uncorroborated/unknown, and published bounds/partial coverage control ranking. This page's private configured/manual normalization and authority are unchanged. # Automatic pricing **Last updated:** 2026-11-23T10:59:54-03:00 (UTC-3) You don't need to enter the price of every model. The gateway reads the public catalogs (the community cost map, models.dev, OpenRouter, DeepInfra), cross-checks the sources and shows, for each target of each alias, what a million input and output tokens cost, along with the published context and parameters. That price feeds [valuation](/docs/features/usage-valuation/), the [cost strategy](/docs/features/routing-strategies/) and `/v1/model/info`. ## How to turn it on ```yaml features: external_model_catalog: true automatic_price_catalog: true # requires external_model_catalog price_source_cost_map: true # optional price_source_modelsdev: true # optional ``` You can turn sources on and off in the console under **Settings & sources**, without restarting. To approve every catalog price before it applies, turn on [catalog review](/docs/features/catalog-review/) (`catalog_review`). The result appears in **Model catalog** and in `GET /api/v1/admin/pricing`, for anyone who can read the global catalog. ## Discover metadata in the console **Model catalog → Discover available models** reads OpenRouter, DeepInfra, the community cost map and models.dev under `external_model_catalog`. The same sources are available through `GET /api/v1/admin/catalog/models?source=...` (use `modelsdev` for models.dev). This is the privileged discovery inventory; it is separate from the models a client key may call and from public model publication. Source selectors for valuation do not turn an advisory catalog read into an approved billing rate. Each API snapshot includes `source`, `source_url`, the original successful `fetched_at`, and explicit `stale`. On a failed refresh, an expired successful snapshot is returned with `stale:true` and Warning110; the timestamp is not advanced. Missing freshness on an older server is shown as unknown. The combined public view keeps every source's timestamp and freshness, including unavailable sources; partial success is visibly partial. Reload rereads the existing bounded cache and does not bypass its fifteen-minute TTL. No public catalog read sends a provider key. The console shows only published context, parameters, input/output modalities and lifecycle facts. An expiration, deprecation, shutdown or replacement is advisory: a successor ID never retargets an alias, and missing metadata never guarantees availability. Search and filters apply before pagination. models.dev text rates are already USD per million tokens; other sources retain their own explicit units and raw price details. Community aggregation sources do not automatically prepare routable aliases. ## Where the price comes from | Source | Role | How the model is found | | --- | --- | --- | | The provider's own catalog: OpenRouter (`/api/v1/models`) and DeepInfra (`/models/list`) | Wins when it publishes the rate | Literal ID | | Community cost map (`model_prices_and_context_window.json`, maintained by the community) | Vote | The preset's provider and exact ID, or `provider/ID` | | [models.dev](https://models.dev/api.json) | Vote | The preset's provider and exact ID; Vertex's `google/` prefix is normalized | | Custom or self-hosted target | No source | Stays `unknown`, with the reason | | Sources on | Result | | --- | --- | | None | Only the provider's own catalog and the [manual price book](/docs/features/pricing/) | | One | That source's rate | | Both | A vote between them | **Voting:** - two sources agreeing within 1% give `confidence: corroborated`; - a single source gives `single_source`; - diverging sources give `status: conflict` (`sources_disagree`), and the price does not enter valuation until you set a manual price. The divergence warning stays visible; - an isolated zero price must be confirmed by another source. The response includes `votes`, with each source's value. BytePlus ModelArk is read from models.dev only, the one catalog that lists it under the preset's own base URL. Six presets have no catalog entry anywhere (`cometapi`, `kluster`, `maritaca`, `parasail`, `azure_mistral_ocr`, and `anthropic_openai`, whose answers omit the prompt-cache usage the catalog prices); use the manual price book for them. ## How the target is identified The price is looked up by **provider connection + exact upstream model ID**. The connection is recognized by its [preset](/docs/features/providers/), and the preset only counts while the `base_url` points to the provider's official host. A provider without a preset is recognized by its exact official URL, or, for a cloud preset whose URL carries a region or resource (Bedrock, Azure, Vertex), by a URL that fills that template. This prevents a wrong price by mistake: - the name you gave the connection proves nothing; - similar URLs, ports, query strings, credentials in the URL or the wrong scheme do not count as a known origin; - the OpenRouter rate is never applied to OpenAI, DeepInfra, Groq or any other intermediary; - OpenAI's `/models` API is not a price source. ## Refresh - Each source is cached for 15 minutes. With [valuation](/docs/features/usage-valuation/) on, a background process keeps the sources of active targets warm. - **Reload**, in the console, rereads the result and refreshes the source when the 15-minute window has expired. - Sources are queried in parallel, with up to six seconds in total and five per source. Redirects are not followed. - If the refresh fails, the last valid result keeps being served with `stale: true` and its original date. With no result at all, the target stays `unknown` with the reason. - **Inference never fetches prices over the network.** It uses only what is already cached. - Price fetching uses only public feeds and never sends the provider credential. ## Normalization - Text rates become **USD per million tokens**, in exact decimal (no binary rounding). OpenRouter and the community map publish per token; DeepInfra publishes cents per token and is used only for `text-generation` models. - Negative, missing or sentinel values become unknown, never zero. - Published cache pricing, context tiers, conditions and limits go into `published_pricing` and `metadata`. Context and parameters appear only when the source reports them, and they do not change capabilities or routing. - On OpenRouter, the query uses `output_modalities=all` to include models that do not generate only text. - Limits per catalog: 16 MiB, 20 pages, 5,000 entries for provider catalogs (10,000 records in the community map and 20,000 in models.dev). An incomplete catalog is never published halfway. ## Service tiers The cost map also publishes priority, flex and batch prices for many models (`input_cost_per_token_priority`, `output_cost_per_token_flex`, `cache_read_input_token_cost_batches` and so on). When the cost map priced the standard rate, its tier prices appear under `service_tiers` in `GET /api/v1/admin/pricing` and in the model catalog, each with its source and fetch time, and the tier the provider reports in an answer selects them. A tier no source publishes stays unknown. See [service-tier pricing](/docs/features/service-tier-pricing/). ## Media Image, speech, transcription and video aliases get a per-unit price from the community cost map: per image, per character, per second of audio or per second of video (`unit` and `unit_price`). Valuation counts the unit in the request or response itself. Without a count, the cost stays unknown, never zero. With the `image_token_pricing` flag (off by default; requires `price_source_cost_map`), a GPT Image model such as `gpt-image-1` is priced per token by category instead, from the cost map row that publishes `input_cost_per_token`, `input_cost_per_image_token` and `output_cost_per_image_token` (and `output_cost_per_token` when the model bills text output). The item then has `unit: per_million_image_tokens` and an `image_tokens` object, and no text rates, so cost routing and `/v1/model/info` never read it as a chat price: ```json {"alias": "images", "provider_id": "openai", "model_id": "gpt-image-1", "status": "available", "unit": "per_million_image_tokens", "source": "cost_map", "confidence": "single_source", "image_tokens": {"text_input_per_million": "5", "image_input_per_million": "10", "image_output_per_million": "40"}} ``` Valuation reads the usage each answer reports; see [usage valuation](/docs/features/usage-valuation/#gpt-image-tokens). A row missing one of the three prices, or carrying a context-tiered price, is not read, and the model keeps `media_unit_unpublished`. The advisory cost calculator does not quote these aliases (`image_token_quote_unsupported`): their cost depends on four counts only the answer reports. A media model no catalog prices in its unit, such as a Replicate image model, takes a [manual media price](/docs/features/pricing/#media-models-no-catalog-prices) in the same unit, shown with `source: manual` and `manual_fallback: true`. ## Manual pricing For what no catalog publishes, such as a self-hosted open-source model, or a rate you negotiated, use the [manual price book](/docs/features/pricing/) (`manual_price_catalog`). **A manual entry in effect wins over the automatic price** for the model it names, including entries saved through [price book management](/docs/features/price-book-management/); a model without an entry keeps the automatic price. The response shows `source: manual` and `manual_fallback: true`, plus `override: true` when an automatic price was available and the entry replaced it; the catalogs' votes stay listed. Each valued request names the price it used: in its valuation (`rate.source`, `rate.manual_fallback`, `rate.override`) and, with the [span store](/docs/features/traces/), on its spans (`price.source`, `price.override`). To return a model to its automatic price, remove its entry. The `metadata_source`, `metadata_source_url`, `metadata_fetched_at` and `metadata_stale` fields appear only when a feed actually provided the metadata. ## For clients: `/v1/model/info` With the `model_info` flag, a key with `route:models` reads from `GET /v1/model/info` the mode, capabilities, context and per-token cost of each alias it can use. The format is the one Open WebUI and several SDKs already understand. Providers, URLs and upstream names do not appear. ## Limits - The price is a reference: it does not prove what the provider will charge your account. Contract discounts come in through [discounts and margins](/docs/features/usage-valuation/#discounts-and-margins); the real invoice comes in through [billing imports](/docs/features/native-billing-imports/). - The community cost map is identified as `source: cost_map` and is not a contracted rate. ## See also - [Costs and pricing](/docs/features/feature-costs/): overview. - [Valuation](/docs/features/usage-valuation/): the estimated cost of each call. - [Manual price book](/docs/features/pricing/) and [price book management](/docs/features/price-book-management/). ## Quote a stated workload The optional [cost calculator](/docs/features/cost-calculator/) uses the same identified public/target rates without changing valuation or budget admission. It computes exact declared base quantities and daily/30-day projections, with separate known subtotals when coverage is partial. It does not simulate routing, retries, fallback, classifier/helper calls or provider billing extras; one configured quote covers the selected exact target. # Service-tier pricing **Last updated:** 2026-11-23T10:59:54-03:00 (UTC-3) OpenAI bills one request at the price of the **service tier** that served it. The same model costs a different amount at the standard (`default`) tier, at `priority` (renamed Fast mode on the official pricing page), at `flex` and through the Batch API. On current models priority costs exactly twice the standard price in every token class (input, cached input, output), and flex half. A gateway that values every answer at the standard price undercounts priority traffic by half. The gateway prices each answer at the tier **the provider reports** in it, from the same identified price sources as the standard rate. A tier no source prices stays `unknown`, never valued at the standard price. This applies to [valuation](/docs/features/usage-valuation/), to [budgets and TPM](/docs/features/budgets-and-tpm/) and to the [advisory calculator](/docs/features/cost-calculator/). There is no separate flag: it follows `usage_valuation`, `budget_limits` and `advisory_cost_calculator`. ## Which tier prices an answer | What the provider reports | Price applied | | --- | --- | | `service_tier: "default"`, `"auto"`, no tier, or `null` | Standard rate | | `service_tier: "priority"`, `"flex"` | That tier's price, when a source publishes it | | A tier no source prices (`scale`, a new name) | `unknown`, reason `service_tier_unpriced` | | A value that is not a tier name (a number, an object, `""`), or `provisioned`, which is a Gemini tier | `unknown`, reason `billing_tier_unresolved` | | Two different tiers in one stream | `unknown`, reason `service_tier_conflict` | - **The reported tier wins over the requested one.** A request that asks for `priority` and is served at `default` (the provider had no priority capacity) is valued at the standard price. - **A non-standard tier asked for and not reported** proves neither price: the cost is `unknown` (`service_tier_unreported`). Asking for `auto`, or for nothing, and getting no tier back is valued at the standard price. - Where the tier is read: the top-level `service_tier` of a Chat Completions answer and of every streamed chunk; the terminal response (`response.completed`, `response.incomplete`) of a Responses answer or stream. While a Responses stream is in progress (`response.created`, `response.in_progress`) the object echoes the tier the request asked for; that echo is ignored. A chat route translated to the Responses API reads the tier from the provider's own terminal response. - Gemini names the tier in `usageMetadata`: `serviceTier` (`standard`, `flex`, `priority`) or `trafficType` (`ON_DEMAND` standard, `ON_DEMAND_FLEX` and `FLEX` flex, `ON_DEMAND_PRIORITY` priority, `BATCH` batch, `PROVISIONED_THROUGHPUT` provisioned). See [Gemini tiers, media and totals](/docs/features/usage-valuation/#gemini-tiers-media-and-totals). - Messages (Anthropic `usage.service_tier`) and Bedrock (`serviceTier`) keep their earlier rule: anything other than the standard tier stays `unknown` (valuation) or held (budgets). - A request may send `service_tier` itself, or the operator can force it per target with a [request override](/docs/features/request-parameter-policy/) (`request_overrides: {service_tier: priority}`). Either way the answer's tier prices it. ## Where tier prices come from **Community cost map.** The cost map publishes, beside a model's standard prices, the same fields with a suffix: `input_cost_per_token_priority`, `output_cost_per_token_priority`, `cache_read_input_token_cost_priority`, `cache_creation_input_token_cost_priority`, the `_flex` and `_batches` variants, and long-context prices such as `input_cost_per_token_above_272k_tokens_priority`. The gateway reads them only from the cost map entry that priced the standard rate (with `price_source_cost_map` on, the cost map won the vote), converts them to exact USD per million tokens and keeps the source, URL and fetch time with each tier. models.dev, OpenRouter and DeepInfra publish no service tiers, so a target priced by them has no tier prices. A tier is used only when the source publishes both its input and output prices. A tier field the gateway cannot place (a second context threshold, a cache duration other than one hour) drops that tier rather than pricing it partially; so does a tier priced zero for both input and output, as an uncorroborated zero standard price is. A tier without a cache-read price values a cache read in that tier as `unknown` (`cache_price_unavailable`), never at the standard cache price. A tier without its own long-context price values an input above the standard long-context threshold as `unknown` (`service_tier_long_context_unpriced`). Batch is the Batch API price (`_batches` fields). It appears in the catalog and the price book as `batch`; it prices an answer only when the provider reports `service_tier: "batch"` (or Gemini `trafficType: BATCH`). **Provisioned throughput** (Gemini `trafficType: PROVISIONED_THROUGHPUT`) is the `provisioned` tier. No catalog publishes it: set it in the price book or on an approved budget rate, zero or the committed rate. An answer served there without a `provisioned` price is valued at the standard price with the reason `provisioned_estimated`, and settles a budget at the standard price, instead of staying unknown or held. **Manual price book.** An entry of the [manual price book](/docs/features/pricing/) can carry `service_tiers`. A tier it names wins over the catalog's price for that tier (marked `override: true` when the catalog published one, even in a shape the gateway cannot read); a tier it leaves out keeps the catalog's price. ```yaml price_book: - provider_id: openai model_id: example-model input_per_million: "0.75" output_per_million: "4.5" effective_from: "2026-11-01T00:00:00Z" source_url: https://example.com/pricing service_tiers: priority: input_per_million: "1.5" # required output_per_million: "9" # required cache_read_per_million: "0.15" # optional, this tier only cache_write_per_million: "1.875" # optional, this tier only ``` | Field | Default | Rule | | --- | --- | --- | | `service_tiers` | absent (no tier prices) | Keys `priority`, `flex`, `batch`, `provisioned` only | | `input_per_million`, `output_per_million` | required in each tier | Nonnegative decimal string, up to 9 integer and 9 fractional digits, USD per million text tokens | | `cache_read_per_million`, `cache_write_per_million` | absent | Same format; apply to that tier only | The tier shares the entry's `source_url` and `effective_from`. In the console, **Settings & sources → Manual price book revisions → Edit rates** has optional priority, flex and batch inputs for each rate; the API is the same `PUT /api/v1/admin/price-book` with `service_tiers` in each price. The numbers above are an example: take the values from the provider's official page. ## Valuation The frozen rate of each event records the tier that priced it: `service_tier` and that tier's prices and source replace the standard ones in the stored snapshot, so the snapshot proves the price used. The usage event records the tier the provider reported (`service_tier` in the request log and `GET /api/v1/admin/logs`), with or without valuation. **Analytics → Estimated cost** shows the tier beside each request and the tier of the price applied. Example, measured against the OpenAI API on 2026-11-08 with `gpt-5.4-mini` (12 input and 4 output tokens each), prices from the cost map and checked against the [official pricing page](https://developers.openai.com/api/docs/pricing) (standard 0.75 / 4.50, priority 1.50 / 9.00 USD per million): | Reported tier | Valued cost (USD) | | --- | --- | | `default` | 0.000027 | | `priority` | 0.000054 | ## Budgets and TPM Approved quota rates (`quotas.rates`) carry their own `service_tiers`, approved by the operator like every other enforcement price: ```yaml quotas: rates: - provider_id: openai model: example-model connection: input_usd_per_million: "0.75" output_usd_per_million: "4.5" cache_read_usd_per_million: "0.075" revision: rev-2 service_tiers: priority: input_usd_per_million: "1.5" output_usd_per_million: "9" cache_read_usd_per_million: "0.15" ``` Each tier accepts `input_usd_per_million` and `output_usd_per_million` (required) and the optional `cache_read_usd_per_million`, `cache_write_usd_per_million` and `cache_write_1h_usd_per_million`, with the same bounds as the base prices (up to 10,000 USD per million, at most six decimal places). Keys are `priority`, `flex`, `batch` or `provisioned`; text rates only. The field is absent by default and omitted from the approval fingerprint when absent, so existing approvals stay valid. | Request | Reservation | | --- | --- | | `service_tier: "default"` | Standard prices | | No `service_tier`, or `"auto"` | The highest of the standard prices and every approved tier's: the provider may apply the tier its project is set to, which the gateway cannot see | | `"priority"`, `"flex"`, `"batch"` | The highest of the standard and that tier's prices; refused with `422 quota_profile_unsupported` (reason `service_tier_not_approved`) when the rate does not approve the tier, or when the input estimate is above the rate's `long_context` threshold | | `"fast"` | Reserved as `priority`: OpenAI answers and reports a `fast` request as `priority` (measured 2026-11-08) | | Anything else (a number, `""`, an unknown name) | Refused before the provider is called | A Gemini `generateContent` request reserves at the tier its `serviceTier` names (`standard` is `default`; any case), with the same rules; a name Gemini does not document is refused (`unsupported_service_tier`). Settlement uses the tier the provider reported, Gemini's included (its usage, or the `x-gemini-service-tier` header of a JSON answer whose usage names none); a Gemini stream whose chunks name two tiers keeps its reservation. Provisioned throughput without an approved `provisioned` price settles at the standard price. An answer in another tier the rate does not approve, a non-standard tier asked for and not reported, or a category the tier does not price (a cache read without the tier's cache price, an input above the long-context threshold) **keeps its reservation** instead of settling at the standard price. The immutable measurement proof records the tier, so a later [reconciliation](/docs/features/quota-finance/) settles at the same tier price. A TPM-only policy counts tokens whatever the tier. A request still served at a more expensive tier than reserved is debited in full and raises the usual overrun alert. In the console, **Budget & TPM → Approved rates** shows each tier's prices; the JSON rate editor accepts `service_tiers`. ## Advisory calculator `POST /api/v1/admin/pricing/estimate` accepts `service_tier` (`default`, `priority`, `flex`, `batch`; `fast` is read as `priority`) for text quotes. The quote then prices the tier's published rate, with the tier's own source (`rate_source`, `confidence: single_source` or `manual`) and `service_tier` echoed; a tier no source publishes gives `unknown` (`service_tier_unpriced`) with no total. Warnings name the tier the quote covers (`standard_service_tier_only` or `service_tier__only`). The console calculator has a **Service tier** selector. ## Upgrade notes - Migration 110 adds the nullable `gateway_usage_events.service_tier`. Events recorded before keep `NULL`. - Answers that reported `priority` or `flex` used to be `unknown` (`billing_tier_unresolved`) in valuation and held in budgets; they are now valued and settled when the tier is priced. - T077.005: Gemini answers with a `serviceTier` or `trafficType` other than the standard used to be `unknown` (`specialized_usage_unresolved`) and held; they are now valued and settled at the tier the rate prices, and provisioned throughput at the standard price unless a `provisioned` tier is approved. Budget requests with `service_tier` used to be refused (`unsupported_parameter`); they are admitted under the rules above. - With `service_tiers` approved on a rate, a request without `service_tier` reserves at the highest approved tier price. Send `service_tier: "default"` to reserve at the standard price alone. ## Limits - The OpenAI dialect (Chat Completions, Responses) and Gemini read the tier. Anthropic and Bedrock tiers stay unknown or held. Gemini's `x-gemini-service-tier` header is read on JSON answers only, as the tier of a usage that names none. - A chat route translated to Gemini does not forward `service_tier`: a request that asks for one there is served at the standard tier and stays unknown (`service_tier_unreported`) or held. - A tier price is single-source: only the cost map publishes it, so it is never corroborated by a second catalog. - `scale` and the newer Ultrafast tier have no published per-token price in the cost map; their answers stay unknown. - The usage CSV export does not include the tier column yet; the request log API does. - The price is a reference, not an invoice; see [billing imports](/docs/features/native-billing-imports/). ## See also - [Automatic pricing](/docs/features/automatic-pricing/) · [Valuation](/docs/features/usage-valuation/) · [Budgets and TPM](/docs/features/budgets-and-tpm/) · [Manual price book](/docs/features/pricing/) · [Advisory calculator](/docs/features/cost-calculator/) · [Request parameter policy](/docs/features/request-parameter-policy/) # Valuation: the cost of each call **Last updated:** 2026-11-27T08:38:27-03:00 (UTC-3) Each recorded request gets an estimated cost in dollars, calculated with the price at that moment and the tokens the provider reported. The price is frozen in the event: if the price changes tomorrow, today's cost does not change. The result appears in **Analytics → Estimated cost**, by model, team and provider, over time. ## How to turn it on ```yaml features: usage_analytics: true usage_valuation: true # requires usage_analytics cost_adjustments: true # optional: discounts and margins ``` The price comes from the [manual price book](/docs/features/pricing/) when it has an entry in effect for the connection and model, and otherwise from [automatic pricing](/docs/features/automatic-pricing/). The rate stored with each event says which: `source`, `manual_fallback: true` for a manual price, and `override: true` when that manual price replaced an available automatic one. ## How to read the result Each event has a state: | State | Meaning | Counts in the total? | | --- | --- | --- | | `known` | The provider reported both token counters, a usable price exists and the call type is supported | Yes | | `partial` | Only one counter came; that component appears, but the event total is `null` | No | | `unknown` | The price is missing or the call has something the gateway cannot price safely | No | | `unvalued` | Event recorded before the flag was turned on | No | **The total sums only `known` events.** With no known event, the total is `null`, never zero. A zero cost only appears when the counters and the rate prove zero. The coverage (how many events in each state) comes along, so you know how much of the traffic the number represents. ## What is valued | Call type | Valuation | | --- | --- | | Chat, Messages, Responses and Gemini, in JSON or streamed | Per token | | System One decisions, in JSON | Per token; the current decision profile has no streaming | | Image, speech, transcription and Runway video | Per unit: image, character, second of audio, second of video | | GPT Image (`gpt-image-1` and its family), with `image_token_pricing` | Per token by category, from the answer's usage | | Embeddings, in JSON | Per input token, from the answer's `usage.prompt_tokens`; an embedding has no output tokens, so the output counts as zero. Give the rate an `output_per_million` (`"0"` for a model with no output price): a rate without one stays `unknown` (`unsupported_rate`) | | Rerank | Not valued yet | | MCP tool calls and listings | Not valued: they call no model provider, so their request log rows have no valuation (`not_valued` in reports), zero model tokens and no provider | **Streams** are valued from the counters the provider reports at the end, only when the [stream usage](/docs/features/stream-usage/) observer proves a complete answer: every event must fit the supported profile, with a matching model, complete usage and usable prices for the categories reported. A stream cut before its end has no counters and stays `unknown`. A Chat Completions stream whose client did not ask for the usage has no counters either, unless its alias sets [`stream_usage: inject`](/docs/features/stream-usage/#ask-for-the-usage-on-the-clients-behalf). A Responses answer can echo the request's `tools` and `reasoning` settings in the answer or stream events; with function tools only, that echo is configuration, not a billed category, and the model nested under `response` is checked against the rate like any other. **Prompt caching** is valued by category, the same way budgets measure it: the usage is split per dialect (an OpenAI prompt and a Gemini prompt include their cache reads, an Anthropic input excludes them, Bedrock reports reads and writes beside its input), and cache reads, five-minute writes and one-hour writes are valued at the cache prices the source publishes (the cost map's `cache_read_input_token_cost`, `cache_creation_input_token_cost` and `cache_creation_input_token_cost_above_1hr`, OpenRouter's `input_cache_read` and `input_cache_write`, models.dev's `cache_read` and `cache_write`), the rest of the input at the input price. A request that marks its own cache points (`cache_control` of type `ephemeral` with `ttl` `5m` or `1h`, on a block, a part, a message or a tool) is valued the same way when the target is Claude (Anthropic or Claude on Bedrock), since that answer reports what was written and read by time to live; a mark sent to any other target (an OpenAI Chat Completions passthrough, whose writes carry no time to live) and any other mark stay `unknown` (`non_text_or_stateful_profile`). See [prompt caching](/docs/features/prompt-caching/). **Claude thinking on the Messages API** has no price of its own: the tokens Claude thinks are billed as output tokens and are inside the answer's `output_tokens`, whatever the request's `display` shows, and `usage.output_tokens_details.thinking_tokens` names how many of the output they were. So a `/v1/messages` request that sets `thinking` (`adaptive`, `enabled` with `budget_tokens`, or `disabled`, with an optional `display`), the thinking blocks of an answer or of an earlier turn sent back, and a usage whose only detail is `thinking_tokens` (never above `output_tokens`) are valued like any text call. Any other `thinking` field, any other usage detail, and a `thinking` field on another route stay `unknown`. The current Claude models think by default and Claude Code names the setting on every call, so before this rule none of those calls had a cost. The budget measures the same way (see [budget profiles](/docs/features/quota-protocols/)), so a thinking answer settles its reservation at the same tokens the valuation prices. The usage rule also serves a Chat Completions `reasoning_effort` translated to Claude, whose answers report the same detail. It applies to every provider of protocol `anthropic`: the price you approve for an Anthropic-compatible endpoint that is not Anthropic's asserts that its thinking is inside `output_tokens` too. **Long context:** when the source publishes a higher tier (the cost map's `*_above_k_tokens` prices, models.dev's `context_over_k`), a request whose input (cache included) exceeds the threshold is valued entirely at the tier. **Service tiers:** the tier the provider reports in the answer (`service_tier` of a Chat Completions answer or chunk, the terminal Responses object) selects the price: `default` or `auto` the standard rate, `priority` or `flex` that tier's published price; the frozen rate then holds the tier's prices and source. A tier no source prices stays `unknown` (`service_tier_unpriced`), a non-standard tier asked for and not reported too (`service_tier_unreported`). Gemini names its tier inside `usageMetadata` (`serviceTier`, `trafficType`); see [Gemini tiers, media and totals](#gemini-tiers-media-and-totals). See [service-tier pricing](/docs/features/service-tier-pricing/). **Translated answers** (Bedrock, Anthropic, Gemini, Cohere or a Responses-API target behind another route) are valued from the provider's own usage, which the adapter reads and proves before translating, with the provider's billed model checked against the priced one. **Function tools** the client runs itself (Chat and Responses `type: function`, Messages tools with an `input_schema`, Gemini function declarations), the calls the model writes and the results sent back are text, valued per token like any other. **Image input** is valued like text when the provider bills image tokens as input tokens at the input price and counts them in its prompt counter, the same proof a budget settles on: OpenAI, Anthropic (also through Bedrock and its OpenAI-compatible endpoint), Gemini (API and Vertex AI) and Amazon Nova on Bedrock, on those providers' own hosts only (a third-party host speaking the same protocol bills by its own rules). Only images the gateway can inspect count (bytes that match their type, https URLs in image fields), and the source must not publish an image price of its own. These stay `unknown`, with the reason: - prompt-cache reads or writes when the price source publishes no cache price for them (`cache_price_unavailable`); audio, which has its own price; a service tier no source prices (`service_tier_unpriced`), a tier that is not a name (`billing_tier_unresolved`), two tiers in one stream (`service_tier_conflict`) and Messages or Bedrock tiers other than standard; Gemini media tokens without a published per-token price (`media_token_unpriced`) or that the usage does not count (`media_usage_unreported`); image input where the provider does not bill it as input tokens or the source prices images apart (`image_price_unresolved`); reasoning too, unless the provider proves it is part of the output (`completion_tokens_details.reasoning_tokens` within `completion_tokens` and `total_tokens` equal to input plus output), in which case it is valued as output; - hosted tools (web search, code execution, server tools), detected from the declared tools, the hosted-tool counters and any hosted call or server tool result in the answer, a Responses stored prompt (`prompt`, which may carry hosted tools), conversation context and error responses; - answers the gateway translates from another provider's format whose own usage the adapter could not prove (`provider_usage_unproven`), or whose billed model differs from the priced one (`response_model_mismatch`); - a long-context tier the price source publishes in a shape the gateway cannot read, or more than one tier for the same model (`tiered_rate_unresolved`); the cost map's one-hour cache write price (`cache_creation_input_token_cost_above_1hr`) is a cache price, not a tier; - **more than one attempt** sent to the provider (`multiple_upstream_attempts`): the last response does not state the cost of the earlier ones. With `attempt_charge_lines` each send is valued on its own instead; see [charge lines per provider send](#charge-lines-per-provider-send); - **model swapped** in the response (`response_model_mismatch`): the requested model's price is not applied to another. A dated snapshot of the requested model (OpenAI answers `gpt-4o-mini` as `gpt-4o-mini-2024-07-18`) is valued at the snapshot's own published price when the source lists it, never at the alias's; another suffix, or a snapshot the source does not price, stays unknown; - prompt cache without explicit counters (`cache_usage_unreported`), when the source publishes a cache price. Gemini omits zero-valued counters, so a Gemini usage that counts the prompt reports a cache read of zero by leaving `cachedContentTokenCount` out. There is no token estimate with a local tokenizer: the number comes from the provider. ## Gemini tiers, media and totals A Gemini answer (native `generateContent`, JSON or streamed) reports what it billed in `usageMetadata`, and the valuation prices every documented field instead of leaving it unknown. There is no separate flag: it follows `usage_valuation`. **Tier.** `serviceTier` and `trafficType` select the price set, like `service_tier` does for OpenAI: | Reported | Price | | --- | --- | | no tier, `serviceTier: standard`, `trafficType: ON_DEMAND` | Standard rate | | `serviceTier: flex`, `trafficType: ON_DEMAND_FLEX` or `FLEX` | The `flex` tier price | | `serviceTier: priority`, `trafficType: ON_DEMAND_PRIORITY` | The `priority` tier price | | `trafficType: BATCH` | The `batch` tier price | | `trafficType: PROVISIONED_THROUGHPUT` | The `provisioned` tier price when one is approved; otherwise the standard price, reason `provisioned_estimated` | | An unknown name, or a `serviceTier` and a `trafficType` that disagree | `unknown` (`specialized_usage_unresolved`) | `ON_DEMAND` is pay-as-you-go whatever its tier, so `ON_DEMAND` with `serviceTier: flex` is flex. Names are read case-insensitively. A tier the rate does not price stays `unknown` (`service_tier_unpriced`), as for every dialect. A request that names `serviceTier` itself and gets an answer that reports none stays `unknown` (`service_tier_unreported`). The request log shows the reported tier (for a stream, when valuation is on). The API names a requested tier in `usageMetadata.serviceTier` in JSON and streamed answers (measured on 2026-11-15 with `gemini-3.5-flash-lite`), and sends an `x-gemini-service-tier` response header on JSON answers only. The header is a fallback: it names the tier of a JSON answer whose usage names none, and a header that contradicts the usage's own tier, names a tier this gateway does not map, or is sent twice with different values, leaves the answer `unknown` (`service_tier_conflict`, `billing_tier_unresolved`). Every chunk of a stream carries its usage: two chunks that name different tiers prove neither price (`service_tier_conflict`); a chunk that names no tier does not clash, and a tier an earlier chunk named still prices a final usage that names none. **Provisioned throughput** is capacity paid in advance, which no catalog prices per token. An operator can approve the rate it should be valued at, zero or the committed rate, as a `provisioned` tier in the [manual price book](/docs/features/pricing/) or on an approved budget rate ([service-tier pricing](/docs/features/service-tier-pricing/)). Without one, the answer is valued at the standard price with the reason `provisioned_estimated`, shown in **Analytics → Estimated cost** as an estimate: it is counted in the total, and it is not what the provider invoices. **Media.** `promptTokensDetails`, `candidatesTokensDetails` and `cacheTokensDetails` split the counts by modality. Audio, video and image input and image and audio output are priced at their own per-token price from the cost map entry that priced the rate (`input_cost_per_audio_token`, `input_cost_per_video_token`, `input_cost_per_image_token`, `output_cost_per_image_token`, `output_cost_per_audio_token`); the frozen rate stores them as `audio_input_per_million`, `video_input_per_million`, `image_input_per_million`, `image_output_per_million` and `audio_output_per_million`, and the reason of a valued answer is `media_token_estimate`. A modality the answer uses without a published price stays `unknown` (`media_token_unpriced`), never priced as text; so does media in a non-standard tier or above the long-context threshold, whose catalog media prices this version does not read. Images under the [image input](#what-is-valued) rule keep billing as text input, as before. A request with inline audio, video or image parts (`inlineData`) or with `responseModalities` IMAGE or AUDIO is no longer refused outright: the gateway checks that the rate prices those categories (`media_token_unpriced` otherwise) and that the answer's usage counts them. An answer whose usage reads as text while the request sent media, or while it returned an inline image or audio part, stays `unknown` (`media_usage_unreported`). With `gemini_file_inputs`, a file part with a declared type (`fileData` or `inlineData` with `mimeType`, with or without its slice: `documentMetadata`, `spreadsheetMetadata`, `videoMetadata`, `mediaResolution`) is valued the same way, on GenerateContent, on Chat Completions and Responses translated to a Gemini target, and on the Interactions API: a document's pages, a spreadsheet's `VISUAL` layer and images are image tokens (input at the input price where images bill as input, as on the Gemini API and Vertex AI; the image input price elsewhere), text layers are text, audio and video have their own price. A file part with no declared type, any file part while the flag is off, and video output stay outside the profile. See [file inputs](/docs/features/file-inputs/#what-a-file-request-costs). **Totals.** The text share is derived from the details: a breakdown without a `TEXT` entry leaves the text as the count minus the other modalities; a zero count Gemini omits is zero, and `totalTokenCount` must equal the prompt, candidates and thoughts. Only impossible numbers stay `unknown` (`specialized_usage_unresolved`): a negative or malformed count, details that exceed their count, a `TEXT` entry that does not add up with the others, one modality listed twice, a total that does not add up, cached audio or video, or cache reads not named as `TEXT` beside non-text input. Example with a rate of 0.30 USD per million text input tokens, 1.00 per million audio input tokens and 2.50 per million output tokens: a prompt of 1,000 tokens of which 600 are `AUDIO`, and 100 output tokens, costs 400 × 0.30 + 600 × 1.00 + 100 × 2.50 = 970 per million, 0.00097 USD. **Large media answers.** A generated image or audio clip arrives inline as base64 in `inlineData.data`, often megabytes, above the observation bounds (64 KiB of a JSON answer without a budget, 256 KiB per streamed event). The observer drops the contents of each `inlineData.data` string as the bytes go by, keeping the quotes, so it reads the same answer with an empty blob and its usage prices the media; the client still receives every byte. A blob that would not decode (a control character, an invalid escape) is observed as undecodable too, so emptying it never turns a malformed answer into a valued one. Only a key spelled exactly `data` directly inside an object under a key spelled exactly `inlineData` is emptied; nesting deeper than 64 levels is observed whole. The whole stream is still bounded at 32 MiB of observed bytes; above that it stays `unknown`. **Translated routes.** A chat route translated to Gemini is measured by the adapter, which reads tiers, derived totals and tier changes, and refuses media. That is not a gap the meter can close: the chat-to-Gemini translator sends only text and inline images (no audio or video input, no `responseModalities`, no `serviceTier`), images bill as input tokens under the [image input](#what-is-valued) rule, and a chat answer has no field for a generated image. A media modality reported on a translated route therefore means the translated request was not what was sent, and it stays `unknown` (`provider_usage_unproven`). **Budgets** read Gemini the same way: a request's `serviceTier` (`standard`, `flex`, `priority`, `batch`, any case) reserves at that tier like a chat request's `service_tier` (an explicit `standard` at the standard prices alone, no tier at the highest approved tier, a tier the rate does not approve refused with `service_tier_not_approved`, another name refused with `unsupported_service_tier`), the answer settles at the tier it reports (or the JSON header names), a tier asked for and not reported keeps the reservation, and a tier change between chunks keeps it too. Provisioned throughput settles at the standard price unless approved. Media tokens keep the reservation: the measurement budgets store has no media split. ## GPT Image tokens With `image_token_pricing` on (off by default; requires `price_source_cost_map`) and a cost map row priced per token (see [automatic pricing](/docs/features/automatic-pricing/#media)), an `/v1/images/generations` or `/v1/images/edits` answer is valued from its `usage` object, as the Images API reference documents it (an edit at the same prices as a generation of the model; see [image generation and edits](/docs/features/image-generation/)): ```json "usage": { "input_tokens": 50, "input_tokens_details": {"text_tokens": 50, "image_tokens": 0}, "output_tokens": 4160, "total_tokens": 4210 } ``` Text input tokens are valued at the text input price, image input tokens at the image input price and output tokens at the image output price. At `gpt-image-1`'s cost map prices (US$ 5, 10 and 40 per million) this answer costs `0.00025 + 0.1664 = 0.16665` USD. When the answer splits its output (`output_tokens_details` with `text_tokens` and `image_tokens`), each part is valued at its own price; a model whose row publishes a text output price (`output_cost_per_token`, as `gpt-image-1.5` does) needs that split, and stays `unknown` without it (`image_output_split_unreported`). The usage follows the images, which are base64 strings of megabytes, so the gateway reads the whole relayed answer for it and keeps only the top-level `usage` (bounded to 8 KiB), never an image byte. The answer reaches the client unchanged. These stay `unknown`: - a streamed request (`stream: true`, `image_stream_unpriced`) and a service tier other than the default (`billing_tier_unresolved`); - an answer that is not one complete, well-formed JSON object, has an `error` or a second usage block such as `svg_usage`, repeats a member (in the answer or in its usage) or spells a top-level one with escapes, has more than 64 top-level members or nests deeper than 64 levels, or was cut before its end (`image_usage_unresolved`); - a usage whose counts do not add up (`input_tokens` equal to its text plus image tokens, `total_tokens` equal to input plus output), or that carries any other nonzero field, such as a cached count the documented object does not have (`image_usage_unresolved`); no usage at all (`usage_unreported`); - text output with no text output price (`text_output_unpriced`). The documented usage object has no cached-token count, so the input is valued at uncached prices even though the cost map also publishes cached prices for these models: if the provider applied a cache discount it did not report, the estimate is above the bill, never below it. A provider's invoice comes in through [billing imports](/docs/features/native-billing-imports/). Budgets and token limits admit GPT Image requests with `quota_image_tokens` and an approved image token rate, and settle from the same usage; see [GPT Image budgets](/docs/features/quota-protocols/#gpt-image-budgets). Without the flag they are refused before the provider (`image_token_pricing_requires_separate_profile`). ## Charge lines per provider send A request the gateway [retried](/docs/features/resilience/) or sent to a fallback target reached the provider more than once. Without the flag it is `unknown` as a whole. With `attempt_charge_lines` (operator control, off by default, requires `usage_valuation`), each send becomes its own immutable **charge line** under the request's usage event, recorded in the same transaction (with the [durable receipt](/docs/features/durable-usage/) when that is on): | Field | Meaning | | --- | --- | | `attempt` | Send order, from 1 | | `provider`, `model` | The target of that send | | `outcome` | `answered`; `provider_error` (the provider answered an error status, valued as below); `transport_failure` (no answer: a timeout or a dropped connection); `unmeasured_answer` (an answer the gateway refused or could not measure, such as a buffered body to a stream request) | | `status` | The provider's HTTP status, when it answered | | `final` | The send whose answer the client got | | `state`, `reason`, `amount_usd` | The line's own valuation, with its frozen price (`rate`) | | `input_tokens`, `output_tokens` | The reported counters of the final send | How each line is valued: - the **final send** is valued exactly like a request with one send; - an earlier **provider refusal** is `known` at `0` (`provider_error_not_billed`): a 4xx status other than 408, or 503 or 529 (unavailable, overloaded), which the provider answers before doing work; - any other earlier **provider error status** (500, 502, 504, 408 and the rest) is `unknown` (`provider_error_unproven`): the model may have generated before it; - an earlier send with **no answer** is `unknown` (`attempt_outcome_unknown`), and an earlier **answer the gateway did not measure** is `unknown` (`answer_not_measured`): the provider may have billed them, so they are never estimated. The request is `known` at the sum of its lines when every line is known; `partial` with reason `attempt_unknown` (and no amount) when the final send is known but an earlier one is not, the lines keeping what is known; and the final send's own state otherwise. A request with a single send has no lines and is valued as before. A request past 99 earlier sends is `unknown` as a whole (`multiple_upstream_attempts`), as without the flag, so a send is never left out of a total that reads known. Lines add to spend: every report that sums valuations (cost estimates, attribution groups, finance reconciliation, the customer portal) counts the request's total, which includes them. They never count as requests: the request is still one usage event. Protected routes under a [budget or token limit](/docs/features/budgets-and-tpm/) admit one target without retries, so a protected request has one send and its budget settles from that one measurement, as before. `GET /api/v1/admin/valuation` adds `charge_lines` to the items that have them; team roles get them without the rate. The console lists them under the request's estimated amount in **Usage → Cost estimates**. With the flag off, nothing changes: earlier lines are not recorded or returned. Migration 167 adds the `gateway_usage_charge_lines` table; deleting a usage event deletes its lines. ## Budget charge beside the estimate A request under a [budget](/docs/features/budgets-and-tpm/) has two numbers, by design: the **budget charge**, settled at the operator-approved quota rate captured when the request was admitted (or, after a [provider-charge reconciliation](/docs/features/quota-finance/), the invoice amount), and the **estimated cost** on this page, priced from the price book or catalog with discounts and margins. With `budget_charge_reports` (operator control, off by default, requires `usage_valuation` and `budget_limits`), the reports show both, side by side, and say why they differ. The budget side comes from the reservation the request's usage event names, which [single charge](/docs/features/durable-usage/#single-charge) (`single_charge_settlement`) records; events recorded without it have no link and are counted as `unlinked`. The budget side of one event has a state: | `state` | Budget charge | | --- | --- | | `settled` | Settled at the approved rate: `amount_usd` | | `reconciled` | Moved to the provider's invoice by a charge reconciliation: `amount_usd` | | `released` | No provider attempt started: `0` | | `held` | Reserved or `unknown`: the reserved amount (`held_usd`) stays charged until a reconciliation; never summed as known | | `tokens_only` | A token ceiling without a USD rate | | `archived` | Its ledger row was archived | | `unlinked` | No reservation linked | Where it appears: - **Cost estimates** (`GET /api/v1/admin/valuation`): a `budget_charge` summary (`charged_usd`, `charged`, `held`) over the same filtered events, and `budget_charge` on each request. The console shows **Charged against budget** under the known amount and a **Budget** line on each request. - **Per-window consistency check** (`GET /api/v1/admin/valuation/consistency`, `analytics:read`, same filters and team scope as the valuation report, hours through 7 days and days above): per window and in total, how many requests have both sides known and agree within `charge_accounting.consistency_tolerance_usd` (default `0.000001`, echoed in the report as `charge_accounting.consistency_tolerance_usd`), and how many differ, by cause: `reconciliation` (the budget took the invoice), `margin` (a discount or margin changed the estimate) or `rate` (the price book or catalog price is not the approved rate). It also counts `only_budget_known` (with the valuation reasons, such as `rate_unavailable`), `only_estimate_known` (the reservation is held), `neither_known`, `unlinked`, `archived` and `tokens_only`, and sums both sides where both are known. The console lists the windows with a difference under **Charged against budget vs estimated cost**. - **[Attribution groups](/docs/features/attribution-groups/)** and the **[customer portal](/docs/features/customer-portal/)** usage (and the self-service customer view): each row adds `budget_charge`; their CSV exports add `budget_charged_usd`, `budget_charged` and `budget_held`; the console adds a **Charged against budget** column. - **[Financial reconciliation](/docs/features/billing-connectors/)** already shows `ledger_settled_usd` (the budget side) beside `gateway_estimated_usd`. - **The [analytics store copy](/docs/features/analytics-store/)** carries each event's `quota_reservation_id`, `valuation_state`, `estimated_usd`, `budget_charge_state` and `budget_charge_units` (1e-12 USD). ```yaml charge_accounting: consistency_tolerance_usd: "0.000001" # 0-1 USD, at most six decimal places; restart to apply ``` With the flag off, the reports, exports and the copy read as before, and the consistency route answers `404`. ## Discounts and margins With `cost_adjustments`, per-provider or global discounts and margins (percentages or a fixed amount per request) go into each event's frozen price: discount first, then margin. Useful to reflect a negotiated contract or a pass-through charge to internal customers. ```yaml cost_adjustments: discounts: global: 0.05 # 5% off every provider openai: 0.12 # replaces the global entry for this provider margins: global: {percent: 0.10, fixed_usd: 0.002} ``` | Key | Default | What it does | | --- | --- | --- | | `cost_adjustments.discounts` | `{}` | Map of a provider ID, or `global`, to the negotiated discount as a fraction (0.05 is 5%), from 0 to below 1; a provider entry replaces the global one | | `cost_adjustments.margins` | `{}` | Map of a provider ID, or `global`, to the margin added after the discount | | `cost_adjustments.margins..percent` | `0` | Margin as a fraction of the discounted cost, 0 to 10 | | `cost_adjustments.margins..fixed_usd` | `0` | Fixed amount in USD added to each request, 0 to 10 | The block requires `usage_valuation`; the console and the API can override it at runtime (below). ## What the frozen price stores Connection (as a hash of protocol, URL and version), provider, exact model ID, currency, unit, rates, source and date. It does not store secrets, private URLs, prompts or responses. Changing the configuration or the price later does not recalculate old events. ## Pricing coverage The state above says whether a cost is known. **Pricing coverage** (`pricing_coverage`, an operator flag, off by default; requires `usage_valuation`) says, for every answered model call, why it is or is not, in four statuses a dashboard can alert on: | Status | When | Valuation states and reasons | | --- | --- | --- | | `complete` | The cost is known, a valid zero included (an exact-cache hit) | `known` | | `partial` | The final usage did not arrive whole, or a cached-token category has no published price | `partial`; `unknown` with `partial_counters`, `usage_unreported`, `cache_usage_unreported`, `cache_price_unavailable`, `image_output_split_unreported` or `service_tier_unreported` | | `inconsistent` | The reported counters are negative or do not add up (cached tokens above the input) | `unknown` with `invalid_counters`; on the metric, also a known amount that does not equal its parts | | `unavailable` | No price applies | every other reason (`rate_unavailable`, `unsupported_rate`, a model the rate does not name, ...) and a call with no valuation row | ```yaml features: usage_valuation: true pricing_coverage: true ``` It never changes a cost. With it on: - `/metrics` and the OTLP metrics push carry `gateway_pricing_coverage_total{provider,model,status}`, one count per answered call (a 2xx answer) as it ends ([inference series](/docs/features/observability/#inference-series)). A failed call has nothing to price and is not counted; a window without samples is unknown coverage. - `/analytics/query` takes the dimension `pricing_status` (group, filter, `non_empty`) over the stored valuations (their state and reason: a call whose durable outcome was not settled when it ended, `partial` on the metric, reads as its stored valuation here), for example `group_by=pricing_status&metrics=calls&non_empty=pricing_status`; a call that was not answered reads as an empty status. It is a dimension of requests, not of evaluation results. - **Usage → Cost estimates** shows **Pricing coverage**: the calls of the selection in each status and their share. Turning it on counts calls from then on; the analytics dimension reads every stored valuation, older ones included. Off, the series stops growing and the dimension is refused with `feature_disabled`. ## API `GET /api/v1/admin/valuation`, with the `analytics:read` permission: - **Teams and organizations:** `team` is a team's requests of the organization it is in now; `organization` is what was recorded in that organization. A team that moved keeps its earlier cost in the former organization's report ([when a team moves](/docs/features/organizations/#when-a-team-moves)). - **Filters:** `from` and `to` (RFC3339, up to 90 days), `principal`, `model`, `team`, `provider`, `key_id`, `operation`, and `origin` with [evaluation tracing](/docs/features/evaluation-tracing/#the-origin-of-a-request) on, narrowed to one helper sub-kind with `helper_kind` (with `origin=helper`). The same filters apply to usage analytics and the CSV. - **Page:** 50 events, with `has_more` and `next_offset` (`offset` up to 100,000). - **Aggregates** over all filtered events, not just the page: - `timeline`: `{time, coverage, known_amount_usd}`, in 1-hour buckets (up to 7 days) or 1-day buckets; - `by_model`, `by_team`, `by_provider`: `{name, coverage, known_amount_usd}`, up to 20 groups (`truncated_dimensions` flags the cutoff); - `by_origin`, with evaluation tracing on: the same shape by how the requests entered (`app`, `evaluation`, `experiment`, `playground`, `helper`, ...), so evaluation, Playground and helper spend are their own lines (**Spend by origin** in the console's Cost estimates); - `by_helper_kind`, with evaluation tracing on: the helper spend by sub-kind (`guardrail`, `classifier`, `summary`, `ask_ai` for m7 ai, `cache_embedding`, `tool_search`, `vector_store`, `model_test`), each feature's [helper calls](/docs/features/evaluation-tracing/#helper-calls) billed to the team and organization that caused them; shown under `helper` in **Spend by origin**. - **Cost per request** (`cost_request_insights`, operator flag, off by default; requires `usage_valuation`): `per_request` is `{priced, unpriced, p50_usd, p95_usd, p99_usd, max_usd, avg_usd}` over the known cost of each filtered request (each percentile is the cost of an actual request, never interpolated; the mean is rounded to 12 decimals; unknown and partial events are left out and counted in `unpriced`, and every amount is `null` when no request has a known cost), and `most_expensive` the costliest requests of the selection, largest first, each with `request_id`, `trace_id`, `at`, `team`, `key_id`, `model`, `provider`, `operation`, `origin`, `amount_usd` and the reported `input_tokens` and `output_tokens`. `top_requests` sets how many (1 to 50, default 10). The same predicate and team scope as the rest of the report apply, in the same read. These two have a time limit of their own (2 s): on a selection too large for it the report is still answered, without them, and with `per_request_unavailable: true` (the console says so); narrow the range or the filters. In the console, **Cost estimates** shows **Cost per request** (median, p95, p99, largest, mean) and **Most expensive requests**, each request opening its trace on the Traces screen (its request log entry without the trace explorer); with `customer_portal` on it adds **Spend by customer organization**, read from the [structured usage query](/docs/features/ask-ai/#the-structured-usage-query) (`group_by=customer_org`). The same percentiles by any dimension are the `*_cost_usd` metrics of that query. - **Every call is a cost line.** A helper call and a request-level fallback attempt each have their own event and valuation, also when a later attempt answered the client, so what the provider billed is never lost; Usage counts the client's request once (see [how requests are counted](/docs/features/evaluation-tracing/#how-requests-are-counted)). `coverage.events` counts these calls. - Values as decimal strings or `null`. Response with `Cache-Control: private, no-store`. **Who sees what:** - `team_admin`, `team_viewer` and `user` see only the teams they belong to, with amount, state, reason and price hash, without the rate and target details. - global admin and viewer see the full provenance; - operator has no access to analytics. ## Limits - **An estimate, not an invoice.** It is not a financial ledger, reconciliation or budget. To stop spending, use [budgets](/docs/features/budgets-and-tpm/); to compare with the invoice, the [billing imports](/docs/features/native-billing-imports/). - Recording is separate from the response: a failure to record is logged and does not change the delivered response. Coverage shows what reached the database; it does not prove nothing was lost. - Turning off the flag stops valuation and hides the panel; what was already recorded stays. - Deleting a usage event deletes its valuation; the frozen prices stay. The flag does not create its own retention policy. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `GET /api/v1/admin/cost-adjustments` | The discounts and margins in force, their YAML base, source and control version | | `PUT /api/v1/admin/cost-adjustments` | Replaces the discounts and margins with a versioned console override | | `DELETE /api/v1/admin/cost-adjustments` | Removes the console override and restores the YAML block | ## See also - [Automatic pricing](/docs/features/automatic-pricing/). - [Analytics experience](/docs/features/analytics-experience/). - References: [usage accounting](https://openrouter.ai/docs/use-cases/usage-accounting) and [prompt caching](https://openrouter.ai/docs/guides/best-practices/prompt-caching) on OpenRouter. ## Manage provider discounts and margins Under `cost_adjustments`, **Settings & sources → Discounts and margins** and `GET /api/v1/admin/cost-adjustments` show the YAML base, current advisory policy, control version and source. Global readers require `prices:read`; changes require `prices:manage`, PostgreSQL, same-origin CSRF and the current version. Operators gain no finance permission from the flag-catalog reader. `PUT /api/v1/admin/cost-adjustments` replaces the whole block with an audited override; `DELETE` with the current version restores YAML. A stale version returns 409, invalid semantic policy 422, and malformed/noncanonical JSON 400. Members use exact lowercase names; duplicates, null numeric values and nonfinite discounts/margins are refused. Discounts are fractions from zero to below one; margin fractions and fixed USD fees range from zero to ten. Provider-specific entries replace global entries, including explicit zero exemptions. The editor preserves numeric precision through decimal-text percentage conversion and uses own properties for provider IDs. Observed denial discards private drafts and late replies; authorized conflict/validation drafts remain editable. Both the stored override and its audit survive normal refreshes and replicas converge on the versioned snapshot. If an override names a provider removed from the YAML, its known entries continue to apply and a warning identifies ignored entries; the stored block is retained until an explicit save/revert. An otherwise invalid override falls back to the valid YAML policy with a warning; malformed persisted JSON is a refresh failure, retaining the last valid snapshot. Adjustments affect future advisory valuations only. Existing event rate snapshots and amounts are not rewritten; approved budget rates/reservations are unchanged. The existing canonical schema migration 93 already provides this override table: this feature reuses it without a new migration or renumbering. Older binaries that do not implement the control reader ignore the override; upgrade all replicas before relying on it, and review the YAML fallback before a downgrade. This is not a provider invoice reconciliation or mixed-version valuation certification. ## Valuation policy constraints Shared [parameter definitions](/docs/reference/parameter-registry/) preserve the cost-adjustment domains: a discount is a finite fraction from zero inclusive to one exclusive, and margin fractions and fixed USD fees are finite values from zero through ten inclusive. Provider entries replace the corresponding global entry; the discount is applied before the margin. These valuation settings do not approve enforcement rates or turn incomplete usage into a known charge. Required provider/model identities and published prices never receive invented defaults. ## Write integrity Valuation writes retain exact finite decimal amounts; nonfinite accounting values are refused before persistence. The immutable proof hashes the original event/valuation DTO, before SQL normalizes decimal spelling or timestamp precision. Numerically equal spellings can therefore remain different retry proofs. Captured rate bytes and their content hash are preserved independently of database JSON formatting. An event and its valuation are atomic; a receipt finalization additionally owns its final state in that same transaction. The shared valuation calculator and typed write boundary do not select a new engine or alter these public contracts. PostgreSQL remains the general regression database; accepted optional-adapter evidence is reused rather than repeating feature suites. ## Display currency With `fx_display`, the valuation response adds `display_currency` and `known_amount_display`, converted with the daily ECB reference rate and labelled with its date; `known_amount_usd` and every other USD field are unchanged. See [display currency](/docs/features/display-currency/). # Display currency **Last updated:** 2026-11-22T06:50:00-03:00 (UTC-3) The gateway counts, budgets and enforces in USD, always. With `fx_display`, the console and the report and analytics responses can also **show** amounts in another currency, converted with the daily reference rate of the European Central Bank (ECB) and always labelled with that rate's date. A budget typed in another currency is converted to USD once, when you save it, and stored in USD with the rate used. ## How to turn it on ```yaml features: fx_display: true # off by default; requires PostgreSQL (migration 184) fx: default_display_currency: USD # gateway default; USD, EUR or an ECB reference currency refresh_interval: 6h # 1h to 24h; how often each replica fetches the ECB file stale_after: 96h # 24h to 336h; an older rate shows USD with a notice ``` | Key | Default | What it does | | --- | --- | --- | | `fx.default_display_currency` | `USD` | The currency amounts are shown in when neither the user nor the organization chose one | | `fx.refresh_interval` | `6h` | How often each replica fetches the ECB reference rates, 1h–24h | | `fx.stale_after` | `96h` | How old the latest rate date may be before amounts fall back to USD with a notice, 24h–336h; the default spans a weekend plus a holiday | `fx_display` is an operator flag; it can be switched in the console. The `fx` settings are read on every cycle and request. ## Where the rates come from - A background job on every replica fetches `https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml` every `refresh_interval` (and at start). No account or key is needed, and no request ever waits for it. - The file gives units per euro. The gateway stores units **per USD**: `rate(X) / rate(USD)`, and for the euro `1 / rate(USD)`, computed exactly and rounded half to even at 10 decimals. Each row keeps its source (`ecb`), the rate date and when it was fetched. A day already stored is never rewritten. - A failed fetch keeps the last stored day. Its date then ages; once it is older than `stale_after` (counted from the end of the rate date), amounts are shown in USD with a notice. A rate is never guessed or carried forward silently. Currencies: USD, EUR, JPY, CZK, DKK, GBP, HUF, PLN, RON, SEK, CHF, ISK, NOK, TRY, AUD, BRL, CAD, CNY, HKD, IDR, ILS, INR, KRW, MXN, MYR, NZD, PHP, SGD, THB, ZAR and BGN (when the ECB publishes it). ## Choosing the display currency The effective currency is, in order: the user's own choice, then the user's organization, then `fx.default_display_currency`. **In the console:** **Settings & sources → Display currency**. A named console user picks **My display currency**; a global admin, or an organization admin for its own organization, picks the **Organization display currency**. The panel shows the latest rate date and any notice, and, read-only, the effective `fx.refresh_interval` and `fx.stale_after` (restart required to change them). `GET /api/v1/admin/fx` returns the three `fx.*` settings under their YAML names: `default_display_currency`, `refresh_interval` and `stale_after`. **Through the API:** ```bash curl -sS -b "$COOKIE_FILE" "$BASE_URL/api/v1/admin/fx" curl -sS -b "$COOKIE_FILE" -H "X-CSRF-Token: $CSRF" -H 'Content-Type: application/json' \ -X PUT -d '{"scope":"user","currency":"EUR"}' "$BASE_URL/api/v1/admin/fx/preference" ``` For an organization: `{"scope":"organization","organization_id":"org_research","currency":"BRL"}`. A global admin names the organization; an organization admin may omit it and always sets its own. An empty `currency` clears the choice. The shared admin and viewer tokens have no personal preference (`422`) and use the organization or gateway default. Every change is audited as `fx.preference`. ## What is converted Responses keep every `*_usd` field unchanged and add a `display_currency` object: ```json "display_currency": {"currency": "EUR", "status": "ok", "per_usd": "0.91000091", "rate_date": "2026-11-17", "source": "ecb", "chosen": "EUR", "from": "user"} ``` `status` is `usd` (nothing to convert), `ok`, `stale` or `missing`; only `ok` converts, and then `currency` is the display currency. Otherwise `currency` is `USD` and `notice` says why. | Response | Added | | --- | --- | | `GET /api/v1/admin/valuation` | `display_currency`, and `known_amount_display` when `ok` | | `GET /api/v1/admin/analytics/query` with `cost_usd` | `display_currency`, and a `cost_display` column after the others when `ok` | | Console: **Estimated cost** (valuation) | "≈ 9.10 EUR · ECB rate of 2026-11-17" under the USD amount, or the notice | Converted amounts are rounded half to even to the currency's minor units (0 decimals for JPY, ISK and KRW, 2 for the others). They are display values: exports, budgets, alerts, invoices and the ledger stay in USD. ## A budget in another currency Send `budget_entered` instead of `policy.budget_usd` when you create or edit a [quota policy](/docs/features/budgets-and-tpm/): ```json PUT /api/v1/admin/quota-policies/team_research_monthly {"version": 12, "base_fingerprint": "...", "policy": {"id": "team_research_monthly", "subject": "team", "subject_id": "research", "budget_period": "month"}, "budget_entered": {"amount": "500", "currency": "EUR"}} ``` - The amount is converted once, at the latest fresh rate: `amount / per_usd`, rounded half to even at 6 decimals, and saved as `budget_usd`. From then on the budget is that USD value; later rate changes do not move it. - The answer includes `budget_entered` with the amount, the currency, the rate and its date; `GET /api/v1/admin/fx/budget-conversions?policy_id=...` (global admin) lists them. - With a missing or stale rate the request answers `409 fx_rate_unavailable` and nothing is saved. Sending both `budget_usd` and `budget_entered` is `400`. ## Limits and upgrade notes - If the conversion record cannot be written after the policy is saved, the answer is `503`: the budget is saved in USD; read it back before retrying. - Rates are ECB reference rates for information, not transaction rates. - An older binary ignores the rates and preferences and refuses `budget_entered`: remove `fx` and the flag from YAML before rolling back. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `GET /api/v1/admin/fx` | The default, user and organization display currencies, the effective one and the latest stored rates | | `PUT /api/v1/admin/fx/preference` | Sets or clears the display currency of the session user, or of an organization | ## See also - [Usage valuation](/docs/features/usage-valuation/) · [Budgets and TPM](/docs/features/budgets-and-tpm/) · [Finance](/docs/features/quota-finance/) # Prompt compression **Last updated:** 2026-11-17T13:29:36-03:00 (UTC-3) An alias can compact the Chat prompts it receives before they reach the provider, conservatively: extra empty lines in prose and exact repeated messages. It is opt-in per alias, deterministic and never summarizes: no word or line is rewritten, no instruction dropped, no model called. Flag: `prompt_compression` (off by default, classified as a model-policy feature for plan entitlements). ## How to turn it on ```yaml features: prompt_compression: true models: - id: chat capabilities: [chat] prompt_compression: mode: structural min_chars: 4000 # optional: leave smaller requests alone targets: - {provider: openai, model: gpt-4.1-mini} ``` | Field | Default | Values | | --- | --- | --- | | `mode` | required | `structural`, the only mode | | `min_chars` | `0` (every eligible request) | 0 to 10,000,000: a request whose `messages` array, as JSON bytes sent by the client, is smaller is left alone | The policy needs the `chat` capability and is validated even with the flag off. In the console it lives in the model editor (**Model catalog → Edit routing → Prompt compression**); the API is the versioned model `PUT` with the `prompt_compression` object. ## What it removes Only in `user` and `assistant` messages made of `role` and a string `content`, and deliberately little: - runs of two or more **empty** lines (lines with no character at all) inside the text, kept as one empty line, so paragraphs stay separated; - a message that repeats, byte for byte after the rule above, the message just before it with the same role (for example an agent loop that sends `continue` three times in a row keeps one). A line with any character, even a single space, is never changed: trailing spaces stay (Markdown hard line breaks, empty TSV columns, diff context lines), and so does indentation. A message whose text contains a code fence (` ``` ` or `~~~` anywhere), a line indented with a tab or four spaces (code, YAML), or a diff hunk (`@@ `, `diff --git`) is left whole, because its empty lines may be significant. The one empty-line case it can still change is a YAML or other block value indented by fewer than four spaces that holds several empty lines in a row; keep such content in a code fence, or leave the policy off for that traffic. ## What it never touches - `system` and `developer` messages, including a [mandatory system prompt](/docs/features/enforced-system-prompt/); - `tool` and `function` messages, and messages carrying `tool_calls`, `function_call`, `name` or any field besides `role` and `content`; - non-string content: multimodal parts (images, audio, files), thinking blocks and their signatures, `cache_control` blocks; - content that is a JSON value (an object or array); - tool, response-format and other request fields; - requests that arrive through another protocol (Anthropic Messages, Responses, Gemini) and are translated to Chat: their own boundaries stay as sent. Each message is transformed on its own, so once a conversation is above `min_chars` its prefix compresses to the same bytes on every turn and provider prompt caches keep matching. The turn that first crosses `min_chars` rewrites the earlier messages, which costs one cache miss. Compressing twice changes nothing. ## Where it runs and what you see Compression runs after the mandatory system prompt and before guardrails, the quota reservation, exact and semantic caches and the provider call, so all of them work on the same smaller body: a smaller prompt reserves less budget and is the one the provider bills. When anything changed, the answer carries `X-Gateway-Prompt-Compression: ->` (the `messages` array as the client sent it, and as it goes to the provider) and the gateway logs `prompt_compression` with the byte counts, changed messages and dropped repeats, never the content. The header is exposed to browser clients through [CORS](/docs/operate/cors/). A request whose body is compressed is no longer forwarded byte for byte to a same-protocol target. ## Measured effects The effect depends on how much padding and repetition your traffic carries; vendor savings claims are not a measurement of yours. The gateway's own fixtures (a pasted document, a code review with fenced code, an agent loop with repeated turns, and a fixture of protected messages that must not change) are measured by `go test ./internal/gateway -run TestPromptCompressionFixtureEffects`, which recomputes and checks the recorded results in [`internal/gateway/testdata/prompt_compression/effects.json`](https://github.com/m7gtw/gateway/blob/main/internal/gateway/testdata/prompt_compression/effects.json): - **Size:** bytes of the `messages` array before and after, and a pre-token estimate (words, numbers, punctuation and whitespace runs, as a byte-pair tokenizer splits them before merging). The estimate is for comparing before and after, not a provider's token count. Collapsing empty lines saves bytes but, since a whitespace run is about one token, almost no tokens; dropped repeats are where tokens are saved. The agent-loop fixture is built to repeat turns, so its saving is an upper example, not a typical one. - **Quality:** a deterministic check, written independently of the implementation, that each kept message equals exactly the expected transformation of its original (no other character changes), that the only dropped messages are exact repeats of the previous kept message with the same role, and that every other message is byte-equal. - **Latency:** the gateway-side cost is measured by `go test ./internal/gateway -run '^$' -bench BenchmarkPromptCompression`; it is a single pass over the messages with no provider call. Structural compression itself never summarizes: a summarizer needs extra paid calls, adds latency and removes meaning by design. Summarizing is offered only as an explicit opt-in for prompts that exceed the window ([context overflow](#when-the-prompt-exceeds-the-window-context-overflow)). No real-provider answer-quality comparison has been recorded yet; run your own A/B on representative traffic before relying on token savings. ## When the prompt exceeds the window (context overflow) Structural compression never shortens a conversation. A request whose input is larger than the alias's targets accept is a separate decision, per alias, behind the operator flag `context_overflow` (off by default, requires `context_window_check`). By default such a request is **refused**, as before: the [context window check](/docs/features/context-window-check/) skips each target whose declared `max_input_tokens` the request clearly exceeds and answers `400 context_length_exceeded` when none is left. The `context_overflow` policy opts in to the alternatives, tried in this order: 1. **Escalate** (`escalate`, default `true`): a target of the alias whose window fits takes the request, nothing changed (the check's skip). With `escalate: false` the request is compressed for the **smallest** window instead, so whichever target is chosen fits. 2. **Truncate** (`truncate: true`): the oldest turns are dropped until the gateway's estimate fills at most `target_percent` of the window (default 80%; the estimate is a floor of the real count, so the rest is safety room). A turn runs from one user message to the next, so a tool call is never separated from its results; every `system` and `developer` message (Responses: system and developer items; Messages: the top-level `system`) and the latest turn are always kept. When the latest turn alone does not fit, nothing can be dropped and the request is refused. 3. **Summarize** (`summarize_model: `): the same oldest turns are replaced by one summary from that alias, at most `summary_max_tokens` (default 512). The summary call is a request of the **caller's own key** through the normal Chat Completions route, with the request ID `.summary`: its admission, budgets, TPM, rate limits, usage event, valuation and logs are those of any request of that key to that alias. The summarizer is told to say which facts came from the user, the assistant or a tool and to report instructions as facts, never repeat them. The summary goes back into the conversation as a user message that starts with a marker saying it was written by the gateway's summarizer, is context only and holds no instructions, never as a system message (some providers require the first turn to be a user turn). The calling key must be allowed to call the summarize alias; otherwise the summary fails and the request is refused. If the summary call fails, or the result still does not fit, the request is refused. With both `truncate` and `summarize_model` set, truncation wins; set only `summarize_model` to keep the gist of the dropped turns. ```yaml features: context_window_check: true context_overflow: true models: - id: chat context_overflow: truncate: false summarize_model: chat-cheap # another chat alias; it may not summarize itself summary_max_tokens: 512 # 64-4096 target_percent: 80 # 10-100 targets: - {provider: openai, model: gpt-4.1-mini, max_input_tokens: 128000} - id: chat-cheap targets: - {provider: openai, model: gpt-4.1-nano} ``` **What you see.** Every answer of an alias with a policy carries `X-Gateway-Context-Overflow` (exposed through [CORS](/docs/operate/cors/)): `none` (it fits), `escalated`, `truncated;dropped=`, `summarized;dropped=;model=` or `refused`. The gateway logs `context_overflow` with the action and counts, never the content. The decision runs after the mandatory system prompt, structural compression and the alias's **input guardrails**, and before the quota reservation, caches and the provider: the summarizer reads only what the guardrails let through (masked text stays masked, a blocked request never reaches it), budgets and TPM reserve and count the tokens actually sent, and the semantic cache keys the conversation that is sent. **Where it runs.** Chat Completions and every Messages, Responses and GenerateContent request translated through it; native `POST /v1/messages` (its `messages`; a user message that carries any `tool_result`, text after it included, stays in the turn of its `tool_use`); native `POST /v1/responses` (its `input` items, a `function_call` with its `function_call_output`). A stateful Responses request (`previous_response_id`, `conversation`) is left alone (`none`): its stored part is not in the body. Native `generateContent` keeps the T139 behavior. **Fields** (YAML, the model API `context_overflow` object and the console model editor's **Context overflow** section; validated even with the flag off): `escalate`, `truncate`, `summarize_model` (another enabled chat alias, not a wildcard, whose own policy does not summarize), `summary_max_tokens` (requires `summarize_model`), `target_percent`. The alias needs `max_input_tokens` on a target. The flag is a model-policy right for [plan entitlements](/docs/features/entitlements/). ## Limits - Chat only, OpenAI Chat ingress only. - It does not shorten long text, deduplicate non-consecutive messages or touch tool results. - Turning the flag off or removing the policy forwards prompts as sent again, immediately. # Budgets and TPM **Last updated:** 2026-11-27T12:02:53-03:00 (UTC-3) Reserve capacity **before** a call reaches the provider, then settle against the usage it reports: - **Budget:** dollars per UTC day or month, with optional calendar week, quarter, year and nonresetting lifetime. - **TPM:** tokens per minute (UTC). **TPD**, tokens per day, is covered in [attribution and alerts](/docs/features/quota-governance/#tokens-per-day-tpd). The limits apply per key, team, model alias, user, project, organization or your app's end user, and they add up: a request only goes through if it fits within **every** limit that applies to it. Enforcement happens in PostgreSQL, so it covers all replicas together. No limit grants access to a model or route. Each limit has its own counter, charged when a request is admitted. That is what happens when a team moves to another [organization](/docs/features/organizations/#when-a-team-moves): the team's budget keeps running (a team at 90% stays at 90%), the former organization's [tenant ceiling](/docs/features/quota-governance/#tenant-ceiling) keeps what the team spent there, and the new organization's starts counting the team at the move. ## How to turn it on ```yaml features: usage_analytics: true durable_usage: true tpm_limits: true # boot: token limit budget_limits: true # boot: USD limit quota_management: true # edit from the console and the API quotas: settings: max_input_tokens: 2000000 max_items: 1024 max_tools: 128 max_content_parts: 128 overrun_alert_tolerance_percent: 0 overrun_alert_dedupe_seconds: 0 policies: - id: time-acme subject: team subject_id: acme tpm: 200000 budget_usd: "500" budget_period: month alert_thresholds: [80, 100] rates: - provider_id: openai model: gpt-4.1-mini connection: "" input_usd_per_million: "0.40" output_usd_per_million: "1.60" cache_read_usd_per_million: "0.10" # optional: prompt-cache reads revision: rev-1 ``` `tpm_limits` and `budget_limits` are boot flags: they change on restart. They require PostgreSQL and durable usage. All flags start off. | Flag | What it adds | | --- | --- | | `quota_management` | Edit policies and rates in the console and the API, with versioning and audit | | `calendar_budget_periods` | Enable calendar week, quarter and year USD budgets; off by default and requires `budget_limits` | | `lifetime_budget_limits` | Enable a permanent USD budget with no automatic reset; off by default and requires `budget_limits` | | `temporary_budget_increases` | Apply an optional time-limited addition to a policy ceiling; off by default and requires `budget_limits` | | `hierarchical_quotas` | [Per-child templates](#per-child-templates): one ceiling applied independently to every key, user or team of a parent; off by default and requires `budget_limits` or `tpm_limits` | | `quota_streaming` | Streams (SSE); requires `stream_usage` | | `quota_native_protocols` | Native Anthropic Messages and Gemini; translated routes use the chat profile and do not require this native-profile flag | | `quota_embeddings` | Embeddings | | `quota_media` | Image, transcription and rerank, per unit | | `quota_video` | Runway asynchronous video ([details](/docs/features/quota-video/)) | | `quota_finance` | Reconciliation, invoice imports and archiving ([details](/docs/features/quota-finance/)) | | `quota_manual_release` | An administrator with `quota_reservations:release` gives back the holds of an unknown reservation, with a written reason and an audit record; nothing is released automatically ([details](/docs/features/quota-finance/#releasing-an-unknown-reservation-by-hand)); off by default and requires `quota_finance` | What each profile requires is in [protected profiles](/docs/features/quota-protocols/). ## Policies | Field | Values | | --- | --- | | `quotas.policies[].subject` | `key`, `team`, `model`, `user`, `project`, `organization`, `end_user`; `group` with `attribution_groups` ([attribution groups](/docs/features/attribution-groups/)) | | `quotas.policies[].subject_id` | The subject's ID; for `model`, the exact public alias; for `end_user`, the team; for `group`, the attribution group ID | | `quotas.policies[].tpd` | Tokens per UTC day; requires the `tpd_limits` flag | | `quotas.policies[].tpm` | Positive integer | | `quotas.policies[].budget_usd` | Positive decimal as a string, up to six decimal places | | `quotas.policies[].budget_period` | `day`, `month`; `week`, `quarter`, `year` additionally require `calendar_budget_periods`; `lifetime` requires `lifetime_budget_limits` | | `quotas.policies[].soft_budget` | `true` alerts without denying on USD; TPM stays hard | | `quotas.policies[].alert_thresholds` | Up to five unique percentages from 1 to 100 | | `quotas.policies[].disabled` | Keeps the policy without applying it | | `quotas.policies[].child` | Optional [per-child template](#per-child-templates); requires `hierarchical_quotas` | A policy needs at least one of `tpm`, `tpd`, `budget_usd` and `child`. User, project and organization depend on an explicit binding on the managed key, explained in [attribution and alerts](/docs/features/quota-governance/). Up to 128 policies and 256 rates fit. **Per end user.** With `end_user_budgets` (which requires `end_user_tracking` and `budget_limits` or `tpm_limits`), a `subject: end_user` policy whose `subject_id` equals a team applies the limit to **each** end user of that team, identified by the `X-Gateway-End-User` header. The header is declared by the key, not authenticated: it serves to split the quota among your app's users, not as an identity control. ### Amounts in the console **Budget & TPM** prints every amount with the console's one money format: `US$` and the exact decimal the gateway stores, without trailing zeros and with thousands separators, for example `US$0.000008 / UTC calendar day` and `US$0 / US$0.000008` for committed and remaining. Nothing is rounded: `US$0.125000000001` keeps every digit. An amount the gateway cannot read is shown as **Unavailable**, never as `US$0`. The same format is used on the Evals, request log and usage screens, so an amount reads the same everywhere. ## Per-child templates A **per-child template** gives every child of a parent its own ceiling, without one policy per child: every key of team `acme` gets 20,000 TPM and $5 a day, while the team keeps its cumulative $50 a day. New keys are covered the moment they exist. It needs the `hierarchical_quotas` flag (operator control, off by default, requires `budget_limits` or `tpm_limits`) and is available only with the PostgreSQL quota store. ```yaml features: hierarchical_quotas: true quotas: policies: - id: acme-tree subject: team subject_id: acme tpm: 100000 # cumulative parent ceilings (optional) budget_usd: "50" budget_period: day child: selector: key # each key of the team tpm: 20000 budget_usd: "5" # each key, per UTC day (the parent's period) ``` | Field | Default | Values | | --- | --- | --- | | `child.selector` | required | `key` or `user` under a `team`; `team`, `key` or `user` under a `project` or `organization` | | `child.tpm` | none | 1–100,000,000; not above the parent's `tpm` when both are set | | `child.tpd` | none | 1–100,000,000,000 (requires `tpd_limits`); not above the parent's `tpd` | | `child.budget_usd` | none | Positive decimal string, up to six decimal places; not above a hard parent budget of the same period | | `child.budget_period` | the parent's `budget_period` | `day`, `month`; `week`, `quarter`, `year` with `calendar_budget_periods`; `lifetime` with `lifetime_budget_limits` | A template needs at least one of `child.tpm`, `child.tpd` and `child.budget_usd`. The policy's own `tpm`, `tpd` and `budget_usd` stay optional: when set, they are the parent's cumulative ceiling over all of its children. `soft_budget`, alert thresholds and temporary increases apply to the parent ceiling only; child ceilings are always hard. How it is accounted: - **Independent counters.** Each child has its own counters, named after the parent and the child (`team:acme/key:k1`). Two children never share one, so a busy key cannot use a quiet key's room, and two parents never share one either. - **One transaction.** A request reserves its child counters and the parent ceilings together, in the same PostgreSQL transaction as every other applicable policy: it fits all of them or none. Concurrent requests of many children serialize on the counters, so no child passes its own ceiling and, when the policy sets its own `tpm`, `tpd` or `budget_usd`, the children together never pass it. A template without parent limits caps each child only. - **Exact settlement.** Settlement moves the child and the parent by the same measured amount; an unknown outcome keeps both holds, as for any policy. - **Who the child is.** The child is server-owned identity: the request's key, the key's team, or the user bound to the key by [financial attribution](/docs/features/quota-governance/). A request whose child cannot be established (a key with no attributed user under a `user` template, for example) is refused before any provider call with `422 quota_profile_unsupported (child_identity_required)`, never let through without its child ceiling. - **Over the limit.** A child counter that refuses answers `429 quota_exceeded` with the template's policy ID and an extra `X-Gateway-Quota-Scope: child` header; a refusal by the parent's own ceiling has no such header. - **Windows and restarts.** Child counters use the same UTC windows as every other counter (minute, day, calendar periods, lifetime), live in PostgreSQL and survive restarts; expired windows are pruned like the others. - **Flag off.** With an enabled template in the YAML, `hierarchical_quotas` is required at boot; a disabled template may stay without it. If a console-managed template exists and the flag is later turned off, a request whose enforced dimensions the template limits is refused with `503 quota_unavailable` instead of running under the parent ceiling alone. - **Editing.** `PUT /api/v1/admin/quota-policies/{id}` replaces the whole policy: a body without `child` removes the template. Read the policy first and send its `child` back to keep it. `child` and its fields cannot be `null`. - **Realtime.** Each realtime response is reserved like an HTTP request, child counters included; a session whose child cannot be identified opens, and each response is then refused with `quota_profile_unsupported`. - **Two templates, same parent and child kind.** They share the child counters, and the lower ceiling applies, as two policies on the same subject do. `GET /api/v1/admin/quota-policies/{id}/children?limit=100` lists the children of one template with their current use and remaining room (minute, UTC day and the child budget period), highest share of its ceiling first; `limit` is 1–1,000 (default 100) and `truncated` says more children have counters. Children that used nothing in the current windows are not listed. The console shows the same under **Budget & TPM → Per-child usage**, and edits the template in the policy editor's **Per-child template** section. Requires `quotas:read`; editing requires `quota_management` and `quotas:manage`. **Upgrade.** Migration 136 widens the stored charge bound of one reservation from 68 to 132 charges and 64 KiB; it changes no counter or history. A replica of an earlier version does not know `child`: it ignores a template and admits the covered requests without child counters (and a policy write from it drops the block). Upgrade every replica, then enable `hierarchical_quotas` everywhere, and only then add templates. To roll back, remove every `child` block and the flag first. ## Calendar budgets and upgrade Use `week`, `quarter` or `year` for a calendar USD budget. These are exact named periods, not rolling durations: | Period | Inclusive start, UTC | Exclusive reset, UTC | | --- | --- | --- | | `day` | Current date at 00:00 | Next date at 00:00 | | `week` | Monday at 00:00 | Following Monday at 00:00 | | `month` | First day of current month | First day of next month | | `quarter` | January, April, July or October 1 | First day of next quarter | | `year` | January 1 | Following January 1 | Leap years use the actual calendar. For example, on February 29, 2024 the current quarter is `[2024-01-01T00:00Z, 2024-04-01T00:00Z)`, not a 90-day duration. The authoritative clock is PostgreSQL, shared by the replicas. The existing token minute/day periods do not change. ```yaml features: usage_analytics: true durable_usage: true budget_limits: true calendar_budget_periods: true quota_management: true quotas: policies: - id: platform-quarter subject: team subject_id: platform budget_usd: "1500" budget_period: quarter alert_thresholds: [80, 100] ``` Replace `platform` with the actual team ID, not its display name. Add approved connection-specific rates as described above; a public price catalog is not that approval. The same `budget_period` field is editable through **Budget & TPM** and `PUT /api/v1/admin/quota-policies/{id}` using the current quota version and base fingerprint. The new-period editor additionally requires valid V15 metadata and `quota_policy_access.calendar_write`; a catalog or flag never grants administrative permission. Commercial classification is supplied by the build; this feature does not choose a free/enterprise allocation. You may stage a new-period policy while its flag is off. If `budget_limits` is on and that policy applies, inference fails closed with 503 before external work until the flag is enabled or the policy is changed/disabled. The gateway does not silently remove the USD ceiling. Turning off `budget_limits` retains the existing token-only behavior; USD is then not enforced. Check effective status before sending traffic. For every protected USD subject, the gateway records the same reserved/settled amount in all five calendar windows, even when only day/month enforcement is selected. Only the selected period's ceiling denies the request; the other windows preserve consumption for a later period change. These are five views of one reservation, never five provider charges. Unknown usage remains held. A soft budget changes USD denial, not capture, unknown-hold safety or token ceilings. Threshold alerts belong to the selected policy/window. ### Upgrade from a version before calendar budgets Migration120 adopts protected consumption from retained live and archived reservations into the current week, quarter and year. It counts each reservation once per money subject, using the original reservation's day window, and preserves the recorded rate/measurement and immutable archived original. Settled usage contributes its exact settled amount; released reservations contribute zero; unresolved reservations retain their hold, or their proven reconciled USD charge. Open reservations receive the additional current-period capture so later settlement/reconciliation adjusts the same counters correctly. This adoption is **protected gateway history**, not a reconstruction of every provider invoice. Calls that previously ran without USD protection, including token-only calls, have no approved historical money charge to import. Public prices, analytics token estimates and missing proof never become a zero historical cost. The adoption fails atomically on corrupt/conflicting history or accounting overflow; it does not activate partially seeded balances. 1. Drain traffic and stop **all** older gateway replicas and workers that use this database. Keep them stopped through adoption and the coordinated upgrade. An older process already running does not learn the new counter/pruning contract. 2. Take a database backup with the matching encryption/session key material, following [backup and recovery](/docs/operate/operations/). Preserve immutable archives and financial evidence. 3. Run the new version's normal [migration command](/docs/reference/cli/) against that database, with the configured migration timeout appropriate for its retained ledger. Migration120 commits schema and history adoption together, or rolls back. A failure is a reason to investigate the exact data/timeout/capacity problem, not to delete holds or mark the migration applied by hand. 4. Start only the new version, inspect catalog/base adoption and counters, then enable the calendar flag and resume applicable traffic. Do not run mixed old/new financial writers. Validate a protected request and its correlated ledger/status before restoring the full workload. The new-row capture check rejects old-shaped new USD reservations, but is an additional safeguard, not a rolling-upgrade guarantee. Startup's newer-schema guard also does not fence an old process already running. There is no automatic destructive schema downgrade: use the documented coordinated recovery/backup procedure; an old binary must not be pointed at the upgraded database. ### Read current calendar status `GET /api/v1/admin/quota-policies/status?status_version=2` opts into a versioned snapshot: quota version, base fingerprint, database observation time, calendar flag and per-policy window start/reset. It keeps those separate from the global configuration version. The console uses that snapshot and shows UTC boundaries and whether USD enforcement is active/blocked. Missing/stale/malformed status never means zero consumption or unlimited headroom. Omitted status version retains the legacy response for existing clients: day/month USD stays unchanged, while a week/quarter/year policy contributes only its configured TPM/TPD fields. A calendar policy with no token limit is omitted from that legacy projection. Use V2 to inspect calendar budgets; the legacy projection does not imply that those budgets are absent or unenforced. ## Lifetime budgets Use `budget_period: lifetime` for a permanent USD ceiling on an existing financial subject. Enable `lifetime_budget_limits` with `budget_limits`; it is independent of the optional calendar-period flag. The same field is available in YAML, the policy API and **Budget & TPM**. For example, use an actual managed key ID: ```yaml features: usage_analytics: true durable_usage: true budget_limits: true lifetime_budget_limits: true quota_management: true quotas: policies: - id: integration-total subject: key subject_id: key_actual_id budget_usd: "100" budget_period: lifetime ``` Add approved rates for the configured connection as with other budgets. No renewal schedule is created. Changing the policy ID or ceiling, switching periods, deleting a policy and creating it again do not clear a subject’s recorded consumption. A new subject ID is a different financial identity, not a reset of an existing one. There is no spend-reset operation in this profile. Every protected USD reservation records the same obligation in one lifetime view and the five calendar views. These remain six views of one charge. Lifetime includes settled amounts and held unresolved reservations; proven USD reconciliation can replace the money hold without proving tokens. Traffic previously unprotected in USD is not retroactively priced from analytics or public catalogs. You can stage a lifetime policy with its flag off. While USD protection is enabled, an applicable lifetime policy then blocks inference with503 before external work; the gateway never silently drops the ceiling. With the flag enabled, an exhausted hard lifetime ceiling returns429 **without Retry-After**, because waiting does not renew it. Other applicable calendar/token ceilings retain their own truthful reset hints. Soft budgets keep their established alert-only USD behavior and hard token limits. ### Upgrade and retained capacity Migration121 adopts all retained protected live/archive money for each subject, including older years, with exact proofs and existing USD reconciliations. It adds the lifetime capture to every open monetary reservation so later settlement/reconciliation adjusts the permanent counter too. Closed/archive originals and their fingerprints remain unchanged. All older writers/workers must be stopped, a matching database/key backup retained, and the migration must complete atomically before new writers resume; follow the [coordinated upgrade](#upgrade-from-a-version-before-calendar-budgets). Never hand-edit a migration marker or clear counters to force startup. Lifetime counters have no TTL or safe balance-preserving eviction. There is one additional permanent row per distinct protected financial subject, including each declared end user. Provision storage for that retained cardinality. The existing accounting model uses signed64-bit counters in10^-12USD units: each subject/window must fit within9,223,372.036854775807USD, including unselected views. Adoption or accounting overflow fails closed rather than wrapping, saturating or inventing headroom. A capacity failure needs an explicit accounting/migration solution; deleting history is not recovery. ### Read the lifetime status Request `GET /api/v1/admin/quota-policies/status?status_version=3`. It carries the quota version/base fingerprint, database observation, both period flags and exact money. Lifetime rows have explicit null `budget_window_start` and `budget_resets_at`; the console displays **Never resets**. Null does not certify complete provider-invoice coverage. The internal fixed bucket identity is not exposed as a claim that coverage started in1970. StatusV1 keeps day/month money only; V2 adds calendars. Neither publishes an unfamiliar lifetime USD profile: it retains any configured token fields and omits a tokenless lifetime row. V3 is the minimum lifetime-aware profile; temporary allowances require V4. The current console negotiates metadataV18/statusV5 and needs the independent `lifetime_write` capability; selectors1–15 retain calendar-only capability and16 retains calendar/lifetime. Before/after license guards also protect lifetime removal, conversion and YAML adoption. A flag or metadata row does not grant permission. ## Temporary budget increases A temporary increase raises an existing USD ceiling until an absolute expiry; it does not add a spendable credit or reset consumption. Configure one optional profile per policy: ```yaml features: usage_analytics: true durable_usage: true budget_limits: true quota_management: true temporary_budget_increases: true quotas: policies: - id: rollout-allowance subject: key subject_id: key_actual_id budget_usd: "100" budget_period: month temporary_budget_increase: amount_usd: "25" expires_at: "2027-01-01T00:00:00Z" ``` | Key | What it does | | --- | --- | | `quotas.policies[].temporary_budget_increase.amount_usd` | USD added to the policy's ceiling until the expiry, an exact string with up to six decimal places | | `quotas.policies[].temporary_budget_increase.expires_at` | When the increase ends: a complete RFC 3339 timestamp with its time zone | Use an actual key ID, approved rates and your intended expiry. The example’s ceiling is125USD per month until that instant, then100USD; it is not25USD to consume once across months. A lifetime policy raises its same permanent ceiling instead. Amounts are exact strings with up to six decimal places. The configured base plus increase must remain within the existing1000000USD policy-ceiling bound. A positive base is required. There is no stacking or future activation schedule. Expiry is a complete RFC3339 timestamp with an explicit timezone, normalized to UTC; a date alone or a time without a timezone is rejected. Expired profiles may remain as historical configuration. Repeating the same amount/expiry does not move the deadline. In the console, **Budget & TPM** shows base, effective ceiling, expiry and whether the increase was active, expired, staged or disabled at the database observation time. Displayed eligibility is not permission or provider health. With `temporary_budget_increases` off, the increase is staged/inactive and the **base remains enforced**. Removing an optional allowance cannot weaken the base. Calendar/lifetime feature requirements and every other applicable ceiling still apply. Per-end-user policies raise each covered end user’s individual ceiling, not a shared pool. ### Expiry, reservations and alerts The gateway locks the applicable counters, then checks the database clock for the final temporary decision before changing balances. A request that waited beyond expiry uses the base, even if it reached the gateway earlier. Existing reservation window identities keep their original capture; the later temporary decision time is stored separately. No workstation clock authorizes the increase. Consumption and unknown reservations remain intact when an increase expires, is cleared, edited or disabled. A request already admitted can complete and settle after expiry; it is neither canceled nor replayed. A subject already above its restored base is refused until there is legitimate headroom. For lifetime, waiting does not renew that headroom, so its429 still has no Retry-After. The reservation captures the original policy and the applied effective ceiling, observation and version/provenance. Settlement, reconciliation and threshold alerts use that capture, not a later edited policy or clock. The existing alert identity remains once per policy/subject/window/threshold; editing an increase does not promise a duplicate threshold notification. All calendar/lifetime views remain views of the same charge. ### Edit, clear and audit The existing versioned policy API and console edit the same optional object. **Omission in an API update preserves its current value under the quota transaction; explicit `temporary_budget_increase: null` clears it.** This prevents an older client from accidentally erasing a field it does not know. YAML absence means no declared increase and follows explicit base adoption. To remove the USD budget, explicitly clear an existing increase too. CAS, audit, administrator permission and the independent `temporary_write` capability apply; a metadata row or flag grants no rights. Temporary changes have a bounded append-only history at `GET /api/v1/admin/quota-policies/temporary-increases/history`, also available in the budget page. It records the policy, before/after temporary context, actor, quota version, real timestamp and request/trace IDs in the same transaction as the mutation. A **Declared YAML base** entry describes the adopted base even if a console override masks it; an **Effective policy** entry records a managed policy change. No context recorded never means the entire policy was absent or its balance was zero. History does not invent pre-feature configuration values and remains readable by authorized global quota readers when the operational flag is off. ### Upgrade and compatibility Migration122 adds the bounded adopted temporary-base snapshot/change journal and the larger policy-decision snapshot capacity. Stop every older replica, administrative writer and settlement/reconciliation worker before applying it and creating temporary captures: old JSON readers would ignore the applied ceiling and use the base denominator. Keep the coordinated database/key backup and resume only the new binary. Do not run mixed writers or treat an old binary as a supported schema rollback. StatusV4 and metadataV17 describe the new profile and effective ceiling. Earlier metadata selectors retain their exact capability shapes. StatusV1–3 keep token fields but hide the USD section of any policy carrying a temporary profile; useV4 for its complete supported quota view. Unknown measurements/status remain unavailable. The general administrative audit and its CSV retain their existing contract; the temporary history is a narrow financial view. ## Require the end user and tags An end-user limit only counts the requests that declare an end user (there is no budget per usage tag; [attribution groups](/docs/features/attribution-groups/) budget server-decided groups). A request that leaves `X-Gateway-End-User` out is simply not counted against any end user. To close that gap, a **team**, a **key**, or both can require every inference request to declare an end user and usage tags with given names. A request that lacks one is refused before anything else happens to it. ### How to turn it on ```yaml features: attribution_requirements: true # off by default; enforces every require block end_user_tracking: true # needed by require.end_user usage_analytics: true # needed by end_user_tracking and usage_tags usage_tags: true # needed by require.tags usage_tags: allowed_values: project: [apollo, gemini] cost_center: [cc-100, cc-200] keys: - id: checkout-app team: platform # ... require: tags: [project] # this key's requests must also carry project team_requirements: - team: platform # every key of the team, whenever it was issued require: end_user: true tags: [cost_center] ``` `attribution_requirements` is the catalog flag (operator control, default `false`). It switches enforcement for every team and key at once and is changed like any runtime flag. Each `require` block is a per-team or per-key setting under it; both start empty, which requires nothing. | Field | Default | What it requires | | --- | --- | --- | | `team_requirements[].team` | required | The team the entry binds, a YAML or console team ID; one entry per team, and its `require` block takes the fields below | | `keys[].require.end_user`, `team_requirements[].require.end_user` | `false` | The `X-Gateway-End-User` header, one value of 1–128 printable characters. Needs `end_user_tracking`. The OpenAI `user` body field does **not** count: the header is what every end-user control reads at admission (the end-user RPM counter reads only the header). | | `keys[].require.tags`, `team_requirements[].require.tags` | `[]` | Up to 8 unique usage tag names that the request's merged tags must contain: the `X-Gateway-Tags` header plus the team's defaults (`usage_tag_defaults`). Needs `usage_tags`, and each name must be in `usage_tags.allowed_values` when the requirement is written. Only the name is required; the value is checked by the taxonomy as usual. | ### Team and key: the stricter wins The request must meet the **union** of the key's requirement and its team's: - an end user is required when the team **or** the key requires one; - the required tag names are those of the team **plus** those of the key. A key's block can only add to its team's. A key with `require: {end_user: false}` in a team that requires an end user still has to send one. A team's requirement binds **every** key of the team at its next request, including keys issued before the requirement was set: managed keys read their team's requirement from PostgreSQL in the same query that authenticates them. A team's requirement comes from two places, and both apply: the `team_requirements` entry that names it (YAML; the only source for teams declared in YAML) and, for teams created in the console, the requirement stored with the team. A YAML key whose `team` is a console team is bound by that team's stored requirement as well; it is read from PostgreSQL on each of its requests, and a read failure answers `503 attribution_unavailable` without calling the provider. Keep the union within 8 tag names: a request carries at most 8 usage tags, so a key and team that together require more can never be met. ### What the client must send ```http POST /v1/chat/completions Authorization: Bearer gw_... X-Gateway-End-User: customer-4821 X-Gateway-Tags: {"project":"apollo","cost_center":"cc-100"} ``` A request that lacks something answers **400** before any provider call, quota reservation, rate counter, guardrail or routing classifier: ```json {"error":{"code":"missing_attribution","message":"This request lacks attribution that its policy requires: the X-Gateway-End-User header (required by the team policy); usage tag project (required by the key policy)"}} ``` The message lists every missing item and says whether the **team**, the **key** or **both** policies require it. It names tag names only, never values. With `end_user_tracking` off, the gateway cannot record an end user, so a requirement for one refuses every request and the message says so. ### Where it is checked - **Every request admitted under an inference route scope** (`route:` other than `route:models`): chat completions, Responses, Messages, Gemini, embeddings, images, audio, video, rerank, moderations, OCR, decisions, realtime sessions and realtime client secrets, fine-tuning, token counting and the stored-response, conversation and container routes. These are the same requests rate policies count. The check runs once per request, before the rate limit. - **Semantic fallbacks** are checked like a client request at their destination. They carry the client's `X-Gateway-End-User` and `X-Gateway-Tags`, so a request that met the requirement keeps meeting it. The fallback of one of the gateway's own in-process calls (below) is exempt like the call itself. - **Batches** are checked when created: a batch line carries no client headers, so it cannot declare an end user and has only the team's default tags. A key whose requirement lines could not meet gets `400 missing_attribution` from `POST /v1/batches`, naming what is missing. Lines run later as the gateway's own work and are not checked one by one; a requirement added after the batch was created does not stop it. - **Not checked:** the gateway's own in-process calls made for a request that was already admitted (provider guardrails, semantic cache embeddings, routing classifier and embeddings) or with no client present (evaluations, m7 ai). `GET /v1/models`, MCP, agents, files and vector stores are not inference routes. - **Realtime from a browser:** a browser WebSocket cannot set custom headers, so a key that requires an end user cannot open a realtime session with an ephemeral client secret. Open it from a server that sends the header. ### Console and API - **Keys:** **Virtual keys → Create key** has the attribution fields; **Attribution** in a managed key's **Manage** menu edits its own requirement. API: `require` on `POST /api/v1/admin/keys`, and `PUT /api/v1/admin/keys/{id}/require` with `{"require": {...}, "version": }`. Global administrators edit any key, team administrators the keys of the teams they administer, so a team administrator can clear a key's own requirement; a requirement that team administrators must not relax belongs on the team. YAML keys take `require` from the configuration. - **Teams:** the **Attribution** action on a console team card (global administrators). API: `PUT /api/v1/admin/teams/{id}/require` with the team's current `version`, which it advances. YAML teams answer `409 yaml_owned`; use `team_requirements`. Team listings show `require` (stored) and `yaml_require` (from `team_requirements`, when present). - Writing a non-empty requirement while a flag it needs is off, or with a tag outside the taxonomy, answers `400 invalid_require`. Clearing a requirement is always accepted. A stale version answers `409 version_conflict`. ### Upgrade notes Migration 113 adds the stored requirements to managed keys and console teams, empty for every existing row; nothing changes until `attribution_requirements` is on and a requirement is set. Configuration validation checks the shape of `require` blocks and `team_requirements` entries (unique valid tag names, at most 8, one entry per team); the flags and the tag taxonomy stay runtime settings, so `attribution_requirements`, `end_user_tracking` and `usage_tags` can always be switched off and the taxonomy edited. A requirement that the current flags or taxonomy make impossible to meet (for example a tag later removed from `usage_tags.allowed_values`) refuses its requests, and the `missing_attribution` message says why, until the requirement, the flag or the taxonomy is fixed. The admin API refuses to write such a requirement (`400 invalid_require`). ## Approved rates The budget uses `quotas.rates`, a list of rates that **you approve** for enforcement, separate from the reference prices of [automatic pricing](/docs/features/automatic-pricing/). That way, a change in a public catalog does not change your limit without your review. - Each rate identifies the provider, the exact upstream model and the connection: | Key | What it does | | --- | --- | | `quotas.rates[].provider_id` | ID of the configured provider connection the rate prices | | `quotas.rates[].model` | Exact upstream model ID the provider bills | | `quotas.rates[].connection` | Hash of the provider's protocol, Base URL and API version, shown in the console; a rate stops applying when the connection changes, so a new endpoint needs a new approval | | `quotas.rates[].reasoning` | Marks a model that reasons by default: an OpenAI-compatible chat call to it must carry `max_completion_tokens`, which bounds its reasoning, since `max_tokens` may not | | `quotas.rates[].revision` | Required identifier of this approval; give it a new value when you approve new prices | - Text uses `input_usd_per_million` and `output_usd_per_million`. Image, audio and rerank use `unit`, `variant` and `unit_usd`. - A realtime model adds `audio_input_usd_per_million` and `audio_output_usd_per_million` (both or neither), for the audio tokens its responses report separately. - Prompt caching adds `cache_read_usd_per_million` and `cache_write_usd_per_million`, each optional. When the answer reports tokens read from or written to the provider's prompt cache, they are charged at these prices and the rest of the input at `input_usd_per_million`. Without the matching price, such an answer **keeps its reservation**: cached tokens are never charged as plain input. The write price is the five-minute write; a one-hour write uses `cache_write_1h_usd_per_million`, or keeps the reservation without it. On a TPM-only policy, cached tokens simply count as tokens. - **Long context** adds a higher tier that providers bill for a whole request whose input crosses a threshold: ```yaml long_context: threshold_tokens: 200000 # input tokens, cache included input_usd_per_million: "6" output_usd_per_million: "22.5" cache_read_usd_per_million: "0.6" # optional, like the base tier's cache prices ``` The tier is absent by default. `threshold_tokens` accepts 1–100,000,000; input and output prices are required when it is present, and the cache prices are optional. A request whose input exceeds the threshold settles input, output and cache at these prices. A reservation whose input estimate exceeds the threshold is priced at the highest prices of both tiers, since the answer may fall on either side. - **The model's maximum output** is optional: `max_output_tokens` on a text rate (1–10,000,000) is the most output tokens the model writes in one answer, as its provider documents it. A request that asks for more is refused with `output_limit` before the call, instead of earning the provider's refusal after it, which would leave the reservation held. Without it, only `quotas.settings.max_output_tokens` bounds the limit. The gateway does not read this number from a model catalogue: catalogues are advisory and may be absent, and a rate is what you approved. - **Images** need `image_input_tokens`: your ceiling of input tokens one image can bill on this model, taken from the provider's pricing rules (for example the largest tile count of the model's own tiling), and optionally `max_images` per request. `image_input_tokens` defaults to 0 (images are not approved); the allowed ceiling is 1–1,000,000. `max_images` defaults to 0 (no additional per-rate cap), accepts 1–1,000, and never bypasses the profile's 1,000-image bound or request-size limits. Each image is reserved at the larger of that ceiling and the tokens the provider documents for the image's size, read from its PNG, JPEG, GIF or WebP header (see [image sizes](/docs/features/quota-protocols/#image-sizes)), and settled from the prompt tokens the provider reports. Image URLs are accepted where the provider documents that it bills a URL as an image only (the OpenAI API, Claude Messages on the Anthropic API), reserved at its documented maximum per image; on any other connection they need `image_urls: true`, your statement that the ceiling bounds whatever such a URL bills. Without the ceiling, a request with images is refused with `422 quota_profile_unsupported` (reason `image_ceiling_not_approved_or_exceeded`), under a budget or a token ceiling alike: nothing else bounds what an image bills. - **`image_floor: ceiling`** (with `image_input_tokens`) reserves each image at your ceiling alone, overriding the provider's documented tokens for its size: for a model whose provider changed its rule before the gateway's table follows. Without it, each image takes the larger of the two. - **Service tiers** add `service_tiers` (`priority`, `flex`, `batch`), each with `input_usd_per_million`, `output_usd_per_million` and the optional cache prices. A chat or Responses request that asks for a tier reserves at the higher of the tier's and the standard prices and is refused (`service_tier_not_approved`) when the rate does not approve it; a request without `service_tier` reserves at the highest approved tier, `default` at the standard prices alone. Settlement uses the tier the provider reports; a tier without approved prices keeps the reservation. See [service-tier pricing](/docs/features/service-tier-pricing/). - `response_models` accepts up to eight additional IDs that the provider may return in the response (for example, the dated snapshot of an alias). No wildcards. - `revision` is an identifier such as `rev-1`. Changing the target invalidates the approval; a new rate needs a new `revision`. ## Global and provider budgets | Flag | Default | What it turns on | | --- | --- | --- | | `global_budget_limits` | `false` | The `global` subject: one monetary ceiling shared by the whole installation; requires `budget_limits` | | `provider_budget_limits` | `false` | The `provider` subject: a monetary ceiling on one exact provider connection; requires `budget_limits` | A global ceiling covers supported protected inference across every replica sharing this gateway database. A provider ceiling covers one configured provider **connection ID** across its models, keys and teams. It does not group all connections using the same vendor or protocol. Both are monetary policies; they do not add TPM/TPD limits or grant model access. ```yaml features: budget_limits: true global_budget_limits: true # default false; requires budget_limits provider_budget_limits: true # default false; requires budget_limits quotas: policies: - id: installation-month subject: global subject_id: gateway # exact fixed ID; not a hostname or replica ID budget_usd: "1000" budget_period: month - id: openai-connection-month subject: provider subject_id: openai # an exact existing providers[].id budget_usd: "500" budget_period: month ``` The example assumes an existing `providers[].id: openai` and the normal usage/storage prerequisites above. The provider ID follows the existing financial identifier profile:2–64 lowercase ASCII letters/digits/underscore/hyphen, starting with a letter, and must exist in the reviewed provider catalog. Both new subjects require positive USD up to1000000, an existing supported budget period, and zero/absent `tpm` and `tpd`. They support the same optional temporary increase, soft-budget alerts and exact approved rates. A call must satisfy **every** matching global, selected-provider and existing owner/model ceiling in the same reservation transaction. The counter views are not separate bills. With an applicable global/provider ceiling configured but its corresponding flag off, protected inference fails closed with503. Staging and authorized recovery reads still work. This differs from turning off a temporary allowance, which restores the valid base ceiling. Calendar/lifetime flag requirements still apply. Editing, disabling, reverting or recreating a policy never resets its shared balance or releases an unknown hold. ### Provider identity and supported traffic The provider is the actual selected upstream connection, captured in the reservation. Credential-pool entries are not separate providers. Historical captures settle against their original connection and approved rate even if that provider has since been removed after its policy was cleared. The existing supported protected native, translated, media/transcription and realtime paths share this reservation boundary; async operations retain their hold until terminal proof. A routing profile without a proven selected provider cannot skip a configured provider ceiling: candidate IDs may detect applicable protection and trigger the existing unsupported-profile refusal **before sending**, but never select the first target or invent its cost. This change does not enable new retry/fallback financial profiles. Existing operator guardrail/moderation exemptions and traffic without an approved monetary profile are not silently priced. The global view covers protected gateway inference, not every HTTP/MCP/tool expense or a complete provider invoice. ### Management and compatibility The existing quota API and **Budget & TPM** editor use these same policies. The console fixes the global ID to `gateway` and selects a provider from its reviewed configuration. Provider references, including disabled policies, are checked against effective configuration under the existing control/quota version fence. Removing an in-use provider is refused; reverting a console provider to a YAML provider of the same ID keeps the reference valid. Startup or refresh cannot publish an orphaned configuration; a failed refresh preserves the last valid snapshot. Current console metadata isV18 with separate `global_write`/`provider_write` capabilities; earlier selectors retain their exact shapes. StatusV5 reports both operational flags and the new monetary subjects. V1–4 omit unfamiliar global/provider rows, while preserving their existing old-subject profiles. History keeps its source/known-context distinctions; it does not create records for a time before the feature existed. Flags, commercial classification and permissions remain separate. ### Upgrade, retained coverage and contention Migration123 adopts **one protected monetary obligation per original reservation**, not each copy of its subject/window views. It validates live/archive identities, archive hashes and original provider/rate agreement. Lifetime uses all retained protected history; current calendar views include the retained obligations in those windows. Every old open/unknown reserve receives all six new global/provider views at its original window identities, with backing counters even for ended windows and its attested reconciliation baseline. These buckets stay pinned until resolution. No reserve is released or prior unprotected traffic assigned an advisory cost. Stop every pre123 financial writer, administrator writer and settlement/reconciliation worker first; take the coordinated database/key backup, migrate and resume only new binaries. Older live writers are not fenced by a newer startup-schema check. Corrupt, ambiguous or overflowing history fails atomically; do not discard holds or manually mark the migration applied. There is no supported old-binary rollback on the migrated state. Global counter rows serialize the shared financial boundary across replicas. This is an explicit correctness/throughput tradeoff; existing pool/admission controls still apply, and final whole-branch load qualification remains separate. Historical coverage is retained **protected** accounting, not a reconstruction of all provider charges. ## Quota settings Bounds on protected requests and on the overrun alert, with defaults, set under `quotas.settings` in the YAML and replaceable from the console (**Budget & TPM → Quota settings**) or the API; a zero or omitted field takes its default, and a revert returns to the YAML. Read effective values and `settings_source` with `GET /api/v1/admin/quota-policies`; replace or revert them with `PUT` or `DELETE /api/v1/admin/quota-settings`, using the current `version` and `base_fingerprint`. Writes require an authorized administrative session and `quota_management`, use CSRF protection and version checks, and are audited. They are not part of the approval fingerprint, so a YAML change needs no adoption. | Setting | Default | Bounds | What it does | | --- | --- | --- | --- | | `quotas.settings.max_input_tokens` | 2,000,000 | 1-100,000,000 | Most input tokens one reservation may estimate, images included (`input_limit`) | | `quotas.settings.max_output_tokens` | 1,000,000 | 1-10,000,000 | Most output tokens one reservation may hold. A request reserves the output limit it asks for; one that asks for more is refused (`output_limit`). A rate's `max_output_tokens` declares a lower maximum for its model | | `quotas.settings.max_items` | 1,024 | 1-100,000 | Most messages, contents or input items in one request (`item_limit`) | | `quotas.settings.max_tools` | 128 | 1-4,096 | Most function tools, or Gemini function declarations (`tool_limit`) | | `quotas.settings.max_content_parts` | 128 | 1-4,096 | Most parts or blocks in one message (`content_part_limit`) | | `quotas.settings.overrun_alert_tolerance_percent` | 0 | 0-1,000 | The `quota_reservation_overrun` alert fires only above this share of the reservation, in tokens or USD; the ledger records every overrun | | `quotas.settings.overrun_alert_dedupe_seconds` | 0 | 0-86,400 | 0 raises one alert per reservation; a window folds only the same model and identical billed-policy subject set. Once any channel queues an event, or its metadata list fills, later overruns start another event | A request over a limit gets `422 quota_profile_unsupported` with the reason in parentheses, before any provider call. Each reservation keeps the alert settings it was taken under. A folded event records `count` and `reservation_ids`. Its reserved/measured amounts and `request_id` describe the latest included reservation, not a sum for the group; use the ledger for financial totals. Folding keys include every billed policy subject (such as team, key, user, project, organization or end user), independent of counter dimension. Queuing and folding serialize on the event row, so a channel never receives details that can later change. Delivery retries may repeat a notification; receivers should honor its [idempotency key](/docs/features/alerting/#how-delivery-works). ## How the reservation works 1. The key is authorized (route, model, access policy). 2. The gateway estimates the maximum the call can consume and **reserves** that amount in every applicable policy, in a single transaction: it reserves in all of them or in none. - Input: `payload bytes + tool and output schemas once more + 1024 × (messages, tools and tool calls) + 4096`, plus each image at the larger of the rate's `image_input_tokens` and the provider's documented tokens for it, up to the `max_input_tokens` [quota setting](#quota-settings) (2,000,000 by default). Byte-level tokenizers emit at least one byte per token, so the bytes bound the text; schemas count twice because chat templates re-serialize them; 1024 per item covers each message's template; 4096 covers a provider's fixed preamble, such as the system prompt it adds when tools are present. - Output: the request's `max_tokens` (or `max_completion_tokens`), required, reserved as the request asks for it: its worst case. There is no fixed cap: a limit above `quotas.settings.max_output_tokens` (1,000,000 by default), or above the `max_output_tokens` its approved rate declares for the model, is refused with `output_limit` before the call. A coding agent that asks for 128,000 output tokens on every call therefore reserves 128,000 at the output price; give the budget room for it, or lower the limit with the target's [`max_output_tokens`](/docs/features/request-parameter-policy/). Where `max_tokens` may not bound reasoning, a call that asks for reasoning must use `max_completion_tokens` (see [protected profiles](/docs/features/quota-protocols/#agents-what-the-chat-profile-accepts)); a rate with `reasoning: true` requires it on every OpenAI-compatible chat call. - With input guardrails on, the estimate uses the request as they rewrote it. - Money: input at the highest input-side price the rate approves (a cache write usually costs more than plain input), output at the output price, so no mix of categories the answer can report costs more than the reservation. 3. Only after the reservation is confirmed does the call go to the provider. 4. With a complete and valid response, the reservation is swapped for the real usage reported by the provider: a smaller difference goes back to the balance; a larger one is debited in full. The response is complete once the provider's answer has ended, even if the client disconnects right after. When the gateway translates the provider's answer (Bedrock, Anthropic, Gemini or Cohere behind the chat route, or any translated route), the measurement is the provider's own native usage, read by the adapter before translation; see [protected profiles](/docs/features/quota-protocols/#translated-providers). 5. If the call never went out, the reservation is released. If it went out and something went wrong (timeout, cancellation before the answer ended, truncated response, missing counters), **the reservation stays**, because the provider may have charged for it. A stream whose client disconnects is such a cancellation; with [`stream_settle_on_disconnect`](/docs/features/stream-usage/#when-the-client-disconnects) the gateway reads the provider's answer to its end instead and settles the measured amount. A reservation that can never be reconciled is given back only by an administrator's [audited manual release](/docs/features/quota-finance/#releasing-an-unknown-reservation-by-hand). Practical consequences: - The sum of reservations never exceeds the limit. Real usage can, if the provider reports more than the estimate; the excess is debited in full, shows as `overrun_tokens` in the ledger and the proof, and raises the `quota_reservation_overrun` [alert](/docs/features/alerting/) event, written with the settlement so none is lost. - `X-Request-Id` can repeat; each request has its own internal ID in the ledger. - A crash neither releases reservations nor repeats calls to the provider. - A reservation uses the rates and windows in force when it was made; editing the policy afterwards does not rewrite the past or reset consumption. - Switching a protected policy between supported calendar periods reuses the consumption already recorded in that calendar, including outstanding holds. See [calendar budgets and upgrade](#calendar-budgets-and-upgrade). - Each replica prunes, once an hour, the counters of windows that ended more than an hour earlier, in small batches that never wait on admission or on another replica. A window still referenced by an open reservation (reserved or unknown) is kept until that reservation settles or is reconciled. Without the pruning, every end user an application declares would leave one row per window forever. With no policy applicable to a key, nothing changes for it. With a policy, a call that the gateway cannot measure safely is **rejected before sending**, not let through without control. **One exemption: the moderation guardrail's check.** A [moderation guardrail](/docs/features/guardrails/#moderation-model) sends the request's text to a moderations alias through the gateway, as the caller. Moderation has no quota profile, so that call would be refused (`422 quota_profile_unsupported`) under every policy that applies to the caller and the guardrail would fail every request. The check is the gateway's own call, made because the operator configured it, so it is exempt from this admission: - no reservation, no `422`, and nothing counted against any budget, TPM or TPD, whichever subject the policy names (key, team, user, project, organization, end user, or the moderation alias); - the guarded request itself is reserved, settled and refused over the limit as usual. Input guardrails run before that reservation, which is estimated from the request as they rewrote it. So that a provider that bills moderation is not charged for a check of a request already bound to be refused, the gateway first asks, right before the first moderation check and without reserving anything, whether this admission is certain to refuse the request whatever the guardrails do to its text: what settled requests already spent on an applicable calendar budget or TPD counter leaves no room for the smallest reservation the request could take (its output limit plus the fixed 4,096-token input allowance, with its images and shape), or a ceiling is below that reservation by itself. Then the request answers `429 quota_exceeded` for that policy, with the `Retry-After`, `X-Gateway-Quota-Policy` and `X-Gateway-Quota-Dimension` this admission uses, and neither the moderation provider nor the model's provider is called. The precheck applies the admission's own comparison to that lower bound and counts only what cannot free first: not the reservations of requests in flight, not a TPM minute, and not a calendar window that ends within the time the checks and the admission can take (7 seconds per provider check, plus 5). So it never refuses a request the admission would admit, short of an operator action in those seconds. Anything less than certain (room smaller than this request's estimate, room held only by requests in flight, a profile refusal, storage trouble, a quota store other than PostgreSQL) runs the check and leaves the answer to the admission, which then refuses after the moderation call as before; the [guardrail page](/docs/features/guardrails/#moderation-model) has the details; - a policy whose subject is the moderation alias refuses every direct call to it (`422`) and never applies to guardrail checks; - the check still appears in the request log and the usage ledger under the caller's key and team, with the request ID `.guardrail` (`.guardrail-output` on the answer) and tokens and cost unknown. A provider that bills moderation charges the connection's account; that cost is outside the budget and visible only on the provider's bill; - it is not counted toward the caller's [RPM](/docs/features/access-control/#request-limits-rpm) either; the guarded request is, once. Only that in-process call is exempt. A client calling `/v1/moderations` directly under an applicable policy still gets `422 quota_profile_unsupported`, and no header or body field can claim the exemption; the gateway's other in-process calls (semantic fallbacks, routing embeddings, evaluations, batch lines) go through this admission like a client request. ## Background responses A Responses request with `background: true` answers at once, before the model has produced anything, so its reservation cannot be settled with that answer. Without the flag, a budget or TPM policy refuses it with `422 quota_profile_unsupported` (`unsupported_parameter`). With the operator flag `quota_background_responses` (off by default; requires `responses_lifecycle` and `budget_limits` or `tpm_limits`, and the PostgreSQL store): - **At create** the request is reserved like any other Responses call (same estimate, same `429 quota_exceeded` when a limit is reached, before the provider is called). `stream` must be `false` and `store` must not be `false`. The reservation stays open, bound to the provider's response in a durable row. - **When it ends** the reservation settles from the provider's own response object, the first time any replica sees it terminal: - a client `GET /v1/responses/{id}` or `POST /v1/responses/{id}/cancel` (the object is read before it is returned); - or the background worker, which asks the provider every `charge_accounting.background_poll_seconds` (default 30, 5–3600) about the responses still open. - **What it settles to:** | The provider shows | The reservation | | --- | --- | | `completed` or `incomplete` with usage the approved rate prices | Settled at the exact usage | | `cancelled` or `failed` with no output and no usage, never seen `in_progress` | Released | | `cancelled` or `failed` with no output and no usage after it was seen `in_progress` (it may have billed its prefill) | Held as unknown | | `cancelled` or `failed` with usage | Settled at that usage | | Anything else terminal (a hosted tool, another model, an unpriced category) | Held as unknown, for [reconciliation](/docs/features/durable-usage/) | | Nothing terminal within `charge_accounting.background_max_age_seconds` (default 86400, 600–604800) | Held as unknown; the worker stops asking | - **Once only:** the store decides the first terminal observation and ignores the rest, so a repeated `GET`, the worker and another replica never charge twice. A replica restart loses nothing: the row and the reservation are in PostgreSQL, and any replica settles them. - **Delete:** `DELETE /v1/responses/{id}` on a response whose reservation is still open answers `409 background_response_pending`; cancel it or wait until it ends. When the tracking state cannot be read, it answers `503 background_state_unavailable` instead of deleting. - **Workers:** each pass leases the responses it polls; a replica only gives back its own lease. A row that keeps failing never blocks the expiry of the others. Ended rows are removed 31 days after they end. - **Overrun:** a settlement above the reservation's tokens is logged as `quota_reservation_overrun` (`source: background_response`) and debited in full. - **Connection:** the response is only asked about on the provider connection it was created on. If that connection changes or disappears, the reservation waits, then expires as unknown. - **Receipts:** with `single_charge_settlement`, the create's receipt is not linked to the reservation (it settles later, from the terminal response, not with the receipt). - **Console:** **Logs → Delivery receipts → Background responses** shows the poll interval, the maximum age and how many background responses are open, settled, released, held or expired (`background_responses` in `GET /api/v1/admin/durable-usage`). - **Turning it off** stops the polling and the settlement on `GET`; open reservations stay held, and the worker still holds those past their maximum age as unknown, so none stays open forever. - **Upgrade:** migration 179 adds the tracking table. An older binary rejects the flag name and the two `charge_accounting` fields in YAML: remove them before rolling back; open reservations then stay held until a reconciliation. ## Realtime A [realtime](/docs/features/realtime/) session is not reserved as a whole: **each response inside it** is reserved, settled and, when its outcome is unknown, held, like an HTTP request. - The connection checks only that quota storage answers (`503 quota_unavailable` otherwise) and, under a budget, that the model's approved rate has `audio_input_usd_per_million` and `audio_output_usd_per_million` (`422 quota_profile_unsupported` otherwise). - Each `response.create` (or each `response.created` the provider starts by itself) is reserved with the estimate described in [realtime](/docs/features/realtime/#the-reservation), priced at the higher of the text and audio prices. A refusal drops the request (or cancels the provider's response) and sends the client an `error` event with `budget_exceeded`, `tpm_exceeded` or `tpd_exceeded` and `retry_after`; the session stays open. - `response.done` settles it: TPM with the token totals, the budget with text and audio tokens each at its own approved price. Cached input is charged at the full price. - A response cut by the end of the session keeps its reservation, like an HTTP answer cut mid-stream. ## Responses | Situation | Response | | --- | --- | | Limit exceeded | `429 quota_exceeded`, with `Retry-After`, `X-Gateway-Quota-Policy` and `X-Gateway-Quota-Dimension`; the message names the policy and when it resets and, for the caller's own ceiling (its key, team, user, end user or a per-child counter), the exact limit: `Budget limit exceeded: policy tiny-budget allows US$0.000008 per UTC calendar day; it resets at 2026-11-24T00:00:00Z` (`Token limit exceeded: policy tpm allows 1000 tokens per minute; …`; a lifetime budget says it never resets). A global, provider, model, organization or customer ceiling is the operator's financial inventory: its refusal names the policy and the reset only (`Budget limit exceeded: policy global-monthly; it resets at …`). With [`span_store`](/docs/features/traces/) the request span has a `quota_refused` event with the same policy, dimension, reset and, under the same rule, limit | | Profile or rate without coverage | `422 quota_profile_unsupported`, before sending to the provider | | Database unavailable or configuration base diverged | `503` | | Realtime response over a limit | An `error` event inside the session (`budget_exceeded`, `tpm_exceeded`, `tpd_exceeded`), not an HTTP status | ## Console and API The **Budget & TPM** menu uses the same API: | Endpoint | What it does | | --- | --- | | `GET /api/v1/admin/quota-policies` | Policies, version, fingerprint and connections | | `PUT` / `DELETE /api/v1/admin/quota-policies/{id}` | Create, edit or revert to the YAML | | `PUT` / `DELETE /api/v1/admin/quota-rates` | Replace the approved rates or revert to the YAML | | `PUT` / `DELETE /api/v1/admin/quota-settings` | Replace the [quota settings](#quota-settings) or revert to the YAML | | `POST /api/v1/admin/quota-policies/adopt-base` | Adopt a new YAML without resetting balances | | `GET /api/v1/admin/quota-policies/status` | Committed balance and next reset | | `GET /api/v1/admin/quota-policies/ledger` | Reservations, paginated, without prompts or secrets | | `GET /api/v1/admin/quota-policies/{id}/children` | Current use of each child of a [per-child template](#per-child-templates) | - **Who can:** admin edits; global viewer and operator read. Team roles do not see the financial inventory. - **Did the YAML change?** The base fingerprint diverges and admission stays blocked until an admin adopts the new base. This prevents an old replica from applying the old configuration again. - **Committed balance** includes open, unknown and settled reservations; it is not confirmed spend. In a TPM-only policy, `budget_applied` is `false` and `reserved_usd: "0"` does not mean a free call. - **API reference**, in the console, has ready-made examples. ## Turning it on and off safely - Enable it on every replica before relying on the limit: replicas without enforcement do not respect the ceiling. - Turning it off lets new calls through without a reservation, but does not erase earlier commitments. Calls made without a policy are not charged later, when a new policy appears. - To go back to an earlier gateway version, first remove the flags, fields and overrides it does not know. Do not delete balances or migrations. ## Limits - The reservation is a conservative estimate, not a tokenizer, and it does not guarantee the amount on the external invoice. - The gateway does not control provider price changes, charges from another source or wrong provider counters. - `/v1/models` and MCP do not consume these limits. - Budgets and TPM do not limit how many requests run at once; for that, use a [concurrency cap per key or team](/docs/features/access-control/#concurrent-requests-per-key-and-team). - Alerts stay in the console; for email, Slack or a webhook, use [alerts](/docs/features/alerting/). ## See also - [Attribution, TPD and alerts](/docs/features/quota-governance/). - [Protected profiles](/docs/features/quota-protocols/): what each type of call requires. - [Financial reconciliation](/docs/features/quota-finance/) and [billing imports](/docs/features/native-billing-imports/). - [Asynchronous video](/docs/features/quota-video/). ## Configuration and price semantics Quota policy identities, owners, approval fingerprints and rates remain typed domain data. Shared [parameter definitions](/docs/reference/parameter-registry/) consolidate consumed validation/defaults; they do not approve a rate or activate enforcement. Protected rates and budgets use validated decimal strings, separate from the advisory price catalog and valuation adjustments. Existing managed changes retain version, audit and approval checks; file changes retain their documented rollout/adoption requirements. The quota-settings editor binds a draft to the version and base fingerprint that were reviewed when it was opened. A concurrent update returns a conflict and keeps that draft; cancel and reopen to review the new state. A draft closes after a successful save and is discarded on observed loss of access or invalid configuration metadata. # Attribution, TPD and budget alerts **Last updated:** 2026-11-25T02:20:13-03:00 (UTC-3) Additions to [budgets and TPM](/docs/features/budgets-and-tpm/), under the same flags: - **Attribution:** charge a key's usage to a user, project or organization. - **TPD:** a tokens-per-day limit. - **Soft budget and alerts:** warn when usage reaches 80% or 100%, with or without blocking. ## Attribution to a user, project and organization Besides `key`, `team`, `model` and `end_user` (see [budgets and TPM](/docs/features/budgets-and-tpm/#policies)), a policy can have `user`, `project` or `organization` as its subject. - A **user** is a local gateway user. - **Projects** and **organizations** are financial accounts created in the console. A project has an organization as its parent. Type and parent cannot change after creation. - A **managed key** can be attributed to a user, a project and an organization. The user must be an active member of the key's team. Attribution is done only by a global admin, with versioning and audit. Headers, claims, email and the request body **never** choose these subjects. A key without attribution gets no inferred financial subject. How it works at admission: - Every applicable policy must have balance (AND), including model, user, project and organization. - Changing the attribution affects only future reservations; what was already charged keeps the previous subjects. - A disabled account or a removed member **blocks** the call, instead of silently removing the ceiling. Financial accounts do not isolate tenants and do not grant a role, access or entitlement. The console lists up to 500 accounts and 500 attributions. ## Tenant ceiling With `organizations`, the subject `tenant` names a gateway [organization](/docs/features/organizations/) by its ID: one budget, TPM or TPD counter shared by every key of every team of that organization, read on the request path with the organization's model ceiling. It is a ceiling set by the global administrator; a team or key policy inside the organization still applies on top (every applicable policy must have balance). It is not the `organization` subject above, which is a financial account a key is attributed to. ```yaml quotas: policies: - {id: acme-month, subject: tenant, subject_id: acme, budget_usd: "500", budget_period: month} ``` An [organization admin](/docs/features/organization-admins/) reads its tenant policies and cannot change them. **When a team moves to another organization**, each tenant counter keeps what was charged to it. A request is charged to the organization its team is in when it is admitted, so the former organization's window keeps what the team spent there (it is not freed, and an exceeded budget stays exceeded), and the new organization's window counts the team from its first request after the move, never its past. The team's own policy, and those of its keys and users, have their own counters and run across the move unchanged. See [when a team moves](/docs/features/organizations/#when-a-team-moves). ## One policy for a list of subjects With the operator flag `quota_subject_lists` (off by default; requires `budget_limits` or `tpm_limits`), a policy can name an explicit list of subjects instead of one, with `subject: subjects` and `subjects`: ```yaml quotas: policies: - id: contractor-limits subject: subjects subjects: - {subject: key, id: key_contractor_a} - {subject: key, id: key_contractor_b} - {subject: user, id: user_ana} - {subject: membership, id: user_bob/team_core} budget_usd: "50" budget_period: month tpm: 20000 ``` - **One counter per subject.** The limits are written once and apply to each listed subject separately, exactly as one policy per subject would: `key_contractor_a` and `key_contractor_b` each have their own 50 USD. A request is charged on the counter of every listed subject it belongs to; a request of `key_contractor_a` attributed to `user_ana` uses both counters, and each must have room. There is no shared counter for the list: to share one ceiling, use a team, a project or a [tenant](#tenant-ceiling). - **Entries:** each `subjects[]` entry has `subject`, the kind below, and `id`, the existing key, team, user or project ID (`/` for a membership). - **Kinds:** `key`, `team`, `user`, `project` and `membership`, mixed freely (a counter is identified by its kind and ID, so mixing is never ambiguous); 1–256 unique subjects; `subject_id` stays empty and a list has no per-child template. - **Every listed subject must exist** when a global admin writes it (`422 unknown_quota_subject` otherwise). An [organization admin](/docs/features/organization-admins/) may list only its organization's keys, teams, users and memberships (`403 organization_forbidden`, checked in the write transaction before and after, as for one subject) and lists only the lists whose every subject is its own. - **Status** shows one row per listed subject under the policy's ID; the Prometheus series `gateway_budget_remaining_usd{policy=...}` shows the tightest of them, once. - **Audit:** the write is recorded under the organization every listed subject shares; a list spanning organizations is recorded under none, so no organization admin sees another organization's subjects in its audit view. - **Console:** the **Subject** choice **A list of subjects (one counter each)** takes one `kind:id` per line. ## Membership: a user within one team With the operator flag `membership_budgets` (off by default; requires `budget_limits` or `tpm_limits`), the subject `membership` names one user within one team, as `/`: ```yaml quotas: policies: - {id: ana-in-core, subject: membership, subject_id: user_ana/team_core, budget_usd: "20", budget_period: month} ``` - It counts only the requests of keys of that team [attributed](#attribution-to-a-user-project-and-organization) to that user, on its own counter; the same user's requests through another team's keys do not count. A key without a user attribution is no membership's. - The user must be an active member of the active team when a global admin writes the policy. An organization admin may write it when both the team and the user are of its organization and the user is a member of the team. - **Console:** the **Subject** choice **Team member (a user within one team)**. **Both flags:** they control creating these policies (YAML and API: `422 feature_disabled` while off). A policy created while a flag was on keeps being enforced after it is turned off, so a limit never disappears silently; delete it to remove it. These subjects are enforced by the PostgreSQL quota store. No migration; an older binary rejects the flags, `subject: subjects`, `subjects` and `subject: membership` in YAML and in stored policies: delete such policies before rolling back. ## Tokens per day (TPD) `tpd` in a policy limits a subject's tokens per UTC day, alongside `tpm` and `budget_usd`; a policy can have any combination of the three. ```yaml features: tpm_limits: true tpd_limits: true # boot; requires tpm_limits quotas: policies: - {id: estagiarios, subject: team, subject_id: interns, tpm: 20000, tpd: 500000} ``` - The reservation uses the same estimate as TPM, and the settlement returns to the day whatever was not consumed. - When the limit is exceeded, the response carries `X-Gateway-Quota-Dimension: tokens_day` and a `Retry-After` until UTC midnight. - Image, audio, video and rerank have no tokens: when a TPD applies, they are rejected. - In the console, the policy editor has the **Tokens per UTC day (TPD)** field, and the status shows consumption, balance and when the day resets. ## Soft budget and alerts ```yaml quotas: policies: - id: marketing subject: team subject_id: marketing budget_usd: "200" budget_period: month soft_budget: true # warns, does not block alert_thresholds: [80, 100] ``` - **`soft_budget: true`** keeps reservation, settlement and history, but does not deny when the USD ceiling is reached. TPM and other hard budgets still deny. - **`alert_thresholds`**: up to five unique integer percentages between 1 and 100. Without the list, there are no alerts. - Both require a positive budget and a supported calendar period. Lifetime additionally requires its [independent flag and retained-history upgrade](/docs/features/budgets-and-tpm/#lifetime-budgets), with no temporal renewal. Week, quarter and year additionally require the [calendar budget flag and upgrade](/docs/features/budgets-and-tpm/#calendar-budgets-and-upgrade); alerts retain the selected period’s exact UTC window. Each alert is recorded together with the balance change that triggered it, with the policy, subject, window, percentage, committed amount, ceiling, origin (reservation or settlement), request ID and trace ID. An alert happens once per policy, subject, window and percentage, even with concurrent requests. A later, smaller settlement does not clear the alert. In the console, the alert can be acknowledged; the acknowledgment is audited and does not return balance. These alerts stay in the console panel. For email, Slack or a webhook, use the [alert channels](/docs/features/alerting/). ## Limits - The committed amount includes reservations that do not have an outcome yet: it is not an invoice or final spend. - Turning off enforcement removes the ceilings; do not use that as a way to authorize someone. - Before going back to an earlier gateway version, remove policies with subjects or fields that version does not know. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `GET /api/v1/admin/quota-accounts` | Lists the financial accounts (projects and organizations) | | `POST /api/v1/admin/quota-accounts` | Creates a project or organization account | | `PUT /api/v1/admin/quota-accounts/{id}` | Edits an account at its current version; type and parent never change | | `GET /api/v1/admin/quota-attributions` | Lists the user, project and organization each managed key is attributed to | | `PUT /api/v1/admin/quota-attributions/{key_id}` | Sets a key's attribution; it applies to future reservations only | | `GET /api/v1/admin/quota-alerts` | Lists the budget alerts recorded when a threshold was crossed | | `POST /api/v1/admin/quota-alerts/{id}/ack` | Acknowledges an alert; audited, and it returns no balance | ## See also - [Budgets and TPM](/docs/features/budgets-and-tpm/). - [Organizations](/docs/features/organizations/) and [access control](/docs/features/access-control/). - [Alerts](/docs/features/alerting/). # Protected budget and TPM profiles **Last updated:** 2026-11-27T12:13:34-03:00 (UTC-3) A budget is only reliable if the gateway can measure what the call consumed. That is why each type of call has a **profile**: what the request must carry for the reservation to be calculated, and what the response must carry for the usage to be proven. A call under a policy that does not fit any profile is refused before it goes to the provider. Rules common to all profiles: - a single target, with no retry and no cache (realtime uses only the first target, with no fallback); - under a USD budget, an approved rate for the exact connection and upstream model; input images require an approved rate with an image ceiling even under a token-only policy; - an explicit output limit when the call generates tokens; - measuring does not rewrite requests, stream events or media bytes; an explicitly configured protocol adapter still performs its normal translation, and an alias with [`stream_usage: inject`](/docs/features/stream-usage/#ask-for-the-usage-on-the-clients-behalf) asks a chat stream for the usage its client left out and keeps it out of the client's stream. ## The profiles | Profile | Flag | What the request needs | What the response needs | | --- | --- | --- | --- | | Chat, JSON | `tpm_limits`/`budget_limits` | An output limit; text, function tools and agent parameters (below) | Approved model, one final choice (text, refusal or function tool calls) and complete counters | | Chat, stream | `quota_streaming` + `stream_usage` | On the openai protocol, `stream_options.include_usage: true`, or on an alias with `stream_usage: inject` `stream_options` absent, `null`, or with only `include_usage` (`true`, `false` or `null`) and `include_obfuscation`; on a translated provider, nothing more | Stable model and ID, a finish, the final `usage` (on the usage-only chunk or the finishing one; a repeat must match) and `[DONE]` (a repeated `[DONE]` is ignored); on a translated provider, the native terminal usage | | Responses API (native, `api: responses` or `auto` target) | `tpm_limits`/`budget_limits`; stream also the stream flags | `max_output_tokens`; text or stateless tool-loop input items; function tools, alone or grouped in a `namespace`; `client_metadata` ([Codex CLI](#codex-cli)) | `completed` (or `incomplete` for the output limit or a content filter), only messages, reasoning and function calls in the output, the default tier and the usage | | Anthropic Messages, JSON or stream | `quota_native_protocols` (stream also requires the stream flags) | Text, client tools and their results, `5m`/`1h` cache breakpoints; `max_tokens` | Approved model; `message_start` → final `message_delta` → `message_stop` | | Gemini Interactions, JSON or stream | `quota_native_protocols` (stream also requires the stream flags); background needs `quota_background_responses` | Text input, function tools and results, an inline PDF with a closed `page_image` range; `generation_config.max_output_tokens`; no continuation, agent or hosted tool ([file inputs](/docs/features/file-inputs/#under-a-budget-or-token-ceiling)) | Approved `model`, status `completed` or `incomplete`, steps of text, thoughts and function calls; thoughts count as output | | Gemini, JSON or stream | `quota_native_protocols` (same) | Text, function declarations, calls and responses; a `thinkingConfig` ([Gemini CLI](#gemini-cli)); with `gemini_file_inputs`, an inline PDF with a closed page range whose layers name `page_image` alone, each page reserved like an image ([file inputs](/docs/features/file-inputs/#budgets-and-token-ceilings)); `generationConfig.maxOutputTokens` | Approved `modelVersion`, one final candidate and counters; thoughts count as output | | Embeddings | `quota_embeddings` | Input texts (`input_type` on a translated provider) | On the openai protocol: approved model, indexed data and consistent usage. On Bedrock (Titan text, Cohere families), Cohere v2 and Vertex AI: every provider call's own count (the `X-Amzn-Bedrock-Input-Token-Count` header, Cohere's `meta.billed_units.input_tokens`, Vertex's `statistics.token_count` of an untruncated prediction); one call without it keeps the reservation | | DALL-E images | `quota_media` | Explicit `n`, size and quality | Complete list of images; per-image rate for the variant | | GPT Image generations and edits (OpenAI, `gpt-image-*`) | `quota_media` + `quota_image_tokens` | Prompt (reserved by its UTF-8 bytes), optional `n` (1-10, default 1) and the documented image options; not streamed, no partial images, no `svg` or `gif` output; input images at the rate's `image_input_tokens`; see [GPT Image budgets](#gpt-image-budgets) | The usage after the images, read whole: text and image input, image and text output, each at its approved price | | Whisper transcription (WAV PCM) | `quota_media` | Valid WAV PCM, up to 8 MiB; `response_format: verbose_json` | `usage.type: duration` and `usage.seconds` | | Rerank (Cohere) | `quota_media` | Query and documents | Valid results and `meta.billed_units.search_units` | | Video (Runway) | `quota_video` | See [asynchronous video](/docs/features/quota-video/) | — | | Realtime, per response | `tpm_limits`/`budget_limits` | Under a budget, an approved rate with audio prices; output from `max_output_tokens` or `realtime.default_max_output_tokens` | `response.done` with consistent totals and text/audio details; see [realtime](/docs/features/realtime/) | The Messages, Responses and GenerateContent routes translated to another provider ([protocol translation](/docs/features/protocol-translation/)) are measured as chat: the canonical request must fit the chat profile, and the answer is measured as below. ## Agents: what the chat profile accepts An agent loop fits the chat profile. Each of these changes how many tokens the answer has, never what a token costs: - `tools` with `type: function` only, `tool_choice` (`none`, `auto`, `required` or a named function), `parallel_tool_calls`; - assistant messages with `tool_calls` (and `content: null`), `tool` messages with their `tool_call_id`, and `name` on any message; - content as a string or a list of `text` parts; - `response_format` (`text`, `json_object` or `json_schema`); - `reasoning_effort` (`none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`): reasoning is billed as output, inside the output limit, and the answer must still prove it is part of the output (see below). On an [`api: auto`](/docs/features/protocol-translation/#api-auto-the-api-chosen-per-request) target the profile follows the API the attempt uses: on Responses, the output limit bounds reasoning, every stream ends with usage, and a policy object effort (`{effort, summary}`) counts as its `effort`; - up to 1,024 messages and 128 tools per request, and 128 parts per message, by default: the [quota settings](/docs/features/budgets-and-tpm/#quota-settings) change these limits. A function tool call in the answer is output text the client runs itself, counted in the output tokens; the finish reason `tool_calls` ends the answer like `stop`. The reservation bounds the tool and output schemas too: they count twice, since chat templates re-serialize them, and each tool and tool call gets the same 1,024-token template allowance as a message (see [budgets and TPM](/docs/features/budgets-and-tpm/#how-the-reservation-works)). Still refused, with the reason in the 422: | Request | Why | | --- | --- | | Hosted tools (web search, file search, code interpreter, MCP, custom tools) | Billed per call or per session, which no token rate prices | | Images in the input **without** an approved `image_input_tokens` on the rate | An image's tokens depend on the model's own tiling (one provider bills the same picture at 85 base tokens on one model and 2,833 on another of the same family), and a remote image's size is unknown before the provider fetches it: only the operator's per-model ceiling bounds it. With the ceiling, `image_url` parts, Messages `image` blocks, Gemini image `inlineData` and Responses `input_image` (not a stored `file_id`) are reserved at it, or at the provider's documented tokens for the image when larger ([image sizes](#image-sizes)), and the answer's image token details count as input | | Audio, video and files in the input | Billed by their own rules (seconds, pages), which no token rate prices | | `n` above 1, `logprobs`, `modalities` with audio, `prediction`, `web_search_options`, `service_tier` | More answers, priced categories or tiers the rate does not cover | | Responses `previous_response_id`, `conversation`, `item_reference`, a `reasoning` item without its `encrypted_content`, `background`, `prompt`, `truncation: auto` | The provider bills stored turns (and stored reasoning loaded by ID) again as input, which this request's bytes do not bound; background work has no terminal answer in the call | | `reasoning_effort` with `max_tokens` only, on an OpenAI-compatible chat target (or any call to a rate marked `reasoning: true` without `max_completion_tokens`) | A third-party model may reason past `max_tokens`; `max_completion_tokens` bounds reasoning and output by the OpenAI contract. Anthropic, Claude on Bedrock, Gemini, Converse and the Responses API count reasoning in their own limit; on Cohere the reservation adds the thinking budget the adapter asks for (up to 16,384) | | Anthropic-defined tool types; a Messages `thinking` setting other than `adaptive`, `enabled` with `budget_tokens`, or `disabled` (each with an optional `display`); in `output_config`, a `task_budget` or any field other than `effort` and `format`; in `context_management`, any edit other than `clear_thinking_20251015` with `keep: "all"` (an edit that clears turns or tool results changes what the prompt cache holds, and compaction runs a second generation billed apart); a tool call whose `caller` is not the model itself (`direct`); a `tool_reference` to a tool the request does not declare; Gemini `googleSearch`, `codeExecution` and other built-in tools, and any `thinkingConfig` field other than `includeThoughts`, `thinkingLevel` and `thinkingBudget` | Billed per use, outside the output limit, or not a field the profile knows. Claude's thinking itself is admitted on `/v1/messages`: it is output inside `max_tokens`, billed as output tokens, so the reservation bounds it; thinking blocks of an answer, of a stream (`thinking_delta`, `signature_delta`) and of an earlier turn sent back are measured like text, and `usage.output_tokens_details.thinking_tokens` is read as a part of `output_tokens`, never added to it. **Claude Code's requests are inside the profile**, measured field by field: `output_config.effort` (`low` to `max`) changes how much the model writes, inside `max_tokens`; `output_config.format` of type `json_schema` is input, counted like one client tool with its schema bytes (measured: a 133-byte schema added 207 input tokens, well inside that bound); `context_management` with `clear_thinking_20251015` keeping all thinking changes nothing in the request; a tool's `defer_loading` flag and a `system` turn inside `messages` (text only) are input the request's bytes bound; a tool's `eager_input_streaming` flag and `thinking.block_binding` ([OpenCode](#opencode)) change nothing the bytes do not bound; the `estimated_tokens` beside a thinking delta is a display estimate, never the measurement. A recorded Claude Code task (two calls, thinking, a tool call, cache writes and reads) is admitted and measured at the tokens the valuation prices | ## Coding agents under a budget A coding agent sends fields an ordinary application does not, and a budget refuses what it cannot bound. Each client below was run through the gateway on a real task with a budget on its key, and its requests were recorded with every text blanked; the recordings are the fixtures of the gateway's own tests (`internal/gateway/testdata/*_shape.jsonl`). For each one: what to configure, what is admitted and by which rule, and what stays refused. A refusal answers `422 quota_profile_unsupported` with the reason, before any provider call. How each client is recognized from its requests is in [agent recognition](/docs/features/agent-recognition/). ### Claude Code Measured twice: the Claude Agent SDK 0.2.189 (`claude_code_messages_shape.jsonl`, the fields in the Messages row of the [refused table](#agents-what-the-chat-profile-accepts)) and the Claude Code CLI 2.1.330 with tool search on, 2026-11-27 (`claude_code_tool_search_shape.jsonl`: two calls, a tool search and its result). **Nothing to configure.** The CLI asks for `max_tokens: 128000` on the current models, and the reservation holds that limit as asked: 128,000 output tokens at the output price, settled at what the answer used. To reserve less per call, lower the limit on the target with `max_output_tokens` ([request parameter policy](/docs/features/request-parameter-policy/)) or in the client with `CLAUDE_CODE_MAX_OUTPUT_TOKENS`. | What the CLI sends beyond the SDK recording | Rule | | --- | --- | | A `tool_reference` block inside a tool result (`{"type": "tool_reference", "tool_name": ...}`), which the client's tool search answers with | Admitted when it names a tool the same request declares, with those two fields only. The provider loads that tool's definition into the context, so each reference is reserved as another copy of the definition (one item and its schema bytes). A reference to a tool the request does not declare is refused (`client_tools_only`): its definition is not in the request | | `output_config: {effort}` on a `system` turn inside `messages` (the effort for the turns after it) | Admitted on a system turn with `effort` alone, also on a turn with no text. A format or a task budget there, or the field on another role, is refused | Before the reference was admitted, the CLI recovered by itself: after three refusals it resent the turn with the reference replaced by text. Each refusal answered before any provider call, so nothing was held. ### Codex CLI Measured with `codex-cli` 0.163.0 over the Responses API, 2026-11-27 (`codex_responses_shape.jsonl`: two calls, a tool step, reasoning handed back encrypted, a cache read). **Configure two things.** 1. **An output limit on the alias.** Codex sends no `max_output_tokens`, and a budget cannot reserve an answer without one: the request is refused with `output_limit_required`. Give the target a ceiling with the [request parameter policy](/docs/features/request-parameter-policy/) (`request_parameter_policy` on, `max_output_tokens` on the target): a request without a limit then goes out with that limit, and the reservation is computed from it. 2. **Web search off in the client.** Codex declares the provider's hosted `web_search` tool on every call, even for cached results (`external_web_access: false`). A hosted tool bills per call, which no token rate prices, so the request is refused with `function_tools_only`. In Codex's `config.toml`: `web_search = "disabled"`. ```yaml features: request_parameter_policy: true models: - id: gpt-5.4-mini capabilities: [responses] targets: - provider: openai model: gpt-5.4-mini max_output_tokens: 4096 # the limit Codex does not send ``` ```toml # ~/.codex/config.toml model = "gpt-5.4-mini" model_provider = "gateway" web_search = "disabled" [model_providers.gateway] name = "gateway" base_url = "https://gateway.example.com/v1" env_key = "GATEWAY_KEY" wire_api = "responses" ``` | What Codex sends | Rule | | --- | --- | | `client_metadata` (session, thread, turn and window IDs) | Admitted: a flat object of at most 64 string values. They label the request and are not model input | | A `namespace` tool (Codex groups its agent tools under one) | Admitted: a name, an optional description and 1 or more function tools. Each member is framed and counted like a top-level function tool; a namespace or a hosted tool inside one is refused | | `phase` on an assistant message handed back (`commentary`, `final_answer`) | Admitted on an assistant message with one of those two values | | `logprobs: []` on an `output_text` part handed back | Admitted when the list is empty; log probabilities themselves stay refused | | `reasoning: {effort, summary}`, `include: ["reasoning.encrypted_content"]`, reasoning items with their encrypted content, `prompt_cache_key`, `store: false` | Already in the Responses profile | | `web_search` | Refused (hosted tool); turn it off in the client | | No `max_output_tokens` | Refused as sent; the target's `max_output_tokens` supplies it | The cost ledger values the same calls: a Responses request's `reasoning` setting (an effort and a summary) is not a price category, and the answer's echoes of this turn's reasoning (`context: "current_turn"`, `mode: "standard"`), of the cache key and of the default 24-hour cache retention bill nothing. Cache writes a provider bills are reported in the usage (`cache_write_tokens`); a nonzero count there keeps the answer unresolved, as does any other retention, context or mode. ### Gemini CLI Measured with `@google/gemini-cli` 0.71.1 in API key mode against `gemini-3.5-flash-lite` on Vertex AI, 2026-11-27 (`gemini_cli_generate_shape.jsonl`: two streamed calls, thoughts shown, a tool step, a context-cache read). **Configure one thing: an output limit in the client.** Gemini CLI sends no `generationConfig.maxOutputTokens`, and the request is refused with `output_limit_required`. The [request parameter policy](/docs/features/request-parameter-policy/#what-each-route-applies) does not apply to the native `generateContent` route, which passes the request through unchanged, so the limit is set in the client's `settings.json`: ```json { "modelConfigs": { "customOverrides": [ {"match": {"model": "gemini-3.5-flash-lite"}, "modelConfig": {"generateContentConfig": {"maxOutputTokens": 4096}}} ] } } ``` Point the client at the gateway with `GOOGLE_GEMINI_BASE_URL` and a gateway key in `GEMINI_API_KEY`. | What Gemini CLI sends | Rule | | --- | --- | | `generationConfig.thinkingConfig` with `includeThoughts` and `thinkingLevel` | Admitted: `includeThoughts` (a flag), `thinkingLevel` (`minimal`, `low`, `medium` or `high`, any case) and `thinkingBudget` (a whole number, or `-1`). Thoughts are output inside `maxOutputTokens` and bill at the output price. Measured: with `maxOutputTokens: 64`, a 4,096-token thinking budget stopped at 58 thought and 2 answer tokens, and `thinkingLevel: HIGH` at 60. Any other field of the setting is refused | | Answer parts marked `thought: true` (shown because of `includeThoughts`) | Measured like text; their tokens are in `thoughtsTokenCount`, counted as output. A request may not carry the mark | | `functionDeclarations` with `parametersJsonSchema`, function calls with their `thoughtSignature`, function responses, `temperature`, `topP`, `topK`, a `systemInstruction` | Already in the Gemini profile | | No `maxOutputTokens` | Refused as sent; set it in the client | **Vertex AI streams are now measured.** On Vertex AI every chunk before the last carries `usageMetadata: {"trafficType": "ON_DEMAND"}` and no count. That was read as a broken count, so a streamed Gemini call on Vertex AI kept its whole reservation (`unknown`) and its cost stayed unknown. A chunk before the finish that names only the tier is now a tier report: the tier must agree with the other chunks, and the counts are still required on the finishing chunk. ### OpenCode Measured with `opencode-ai` 1.19.6, 2026-11-27, on both of its paths: its Anthropic provider on `/v1/messages` (`opencode_messages_shape.jsonl`: the title call and two calls of the task, cache writes and a read) and its OpenAI-compatible provider on `/v1/chat/completions` (`opencode_chat_shape.jsonl`: the title call and two calls). **On Messages there is nothing to configure.** OpenCode sends `max_tokens` on every call. | What OpenCode sends on Messages | Rule | | --- | --- | | `thinking.block_binding: {prefix_mismatch_behavior: "drop_block"}` | Admitted: `block_binding` with that one field, `error` or `drop_block`. It says what the provider does with a thinking block handed back from another conversation: refuse the request, or leave the block out unbilled. Neither adds input the request's bytes do not bound | | `eager_input_streaming: true` on a tool | Admitted as a flag: the tool call's input is streamed as it is generated, which changes how the answer is delivered, not what it holds | | `thinking: {type: "adaptive"}` with an optional `display`, `cache_control` marks, `tool_choice: {type: "auto"}` | Already in the Messages profile | **On Chat Completions, configure the alias.** OpenCode sends `max_tokens` together with `reasoning_effort`. Under a budget that pair is refused on an OpenAI-compatible target with `reasoning_requires_max_completion_tokens`, because a model may reason past `max_tokens`; and the current OpenAI models refuse `max_tokens` themselves, and refuse function tools with a reasoning effort on Chat Completions. One target setting answers each ([request parameter policy](/docs/features/request-parameter-policy/), [`api: auto`](/docs/features/protocol-translation/#api-auto-the-api-chosen-per-request)): ```yaml features: request_parameter_policy: true models: - id: gpt-5.4-mini-chat capabilities: [chat] targets: - provider: openai model: gpt-5.4-mini api: auto # tools with an effort go to the Responses API request_overrides: {max_completion_tokens: 4096} # replaces the client's max_tokens max_output_tokens: 4096 ``` Nothing in OpenCode's chat requests needed a new rule: the limit, the effort, `stream_options.include_usage`, function tools and `tool_choice` are in the chat profile. Configure the alias before pointing the client at it: a request the provider refuses after it was sent (as the current OpenAI models do with `max_tokens`) leaves that call's reservation held as unknown: see [what is left out](#what-is-left-out) and [financial reconciliation](/docs/features/quota-finance/). ### pi Measured with `@mariozechner/pi-coding-agent` 0.73.1, 2026-11-27, on its three APIs, one task of two calls each: `anthropic-messages` (`pi_messages_shape.jsonl`), `openai-responses` (`pi_responses_shape.jsonl`) and `openai-completions` (`pi_chat_shape.jsonl`). **Nothing to configure for the budget.** pi sends an output limit on every call (`max_tokens`, `max_output_tokens` or `max_completion_tokens`, from the model's `maxTokens` in its `models.json`). | What pi sends | Rule | | --- | --- | | Messages: `eager_input_streaming: true` on every tool | Admitted as a flag, as for [OpenCode](#opencode) | | Responses: the answer's reasoning item handed back with `content: []` beside its `encrypted_content` | Admitted when the list is empty. Reasoning text in it, or the item by its ID alone, stays refused (`stored_state_not_bounded`) | | Responses: `reasoning: {effort, summary}`, `include`, `prompt_cache_key`, `store: false`; chat: `max_completion_tokens` with `reasoning_effort`, a `developer` message, `stream_options.include_usage`, `store: false` | Already in the profiles | Two things outside the budget, seen on the same run: - **Thinking with a budget.** pi 0.73.1 asks a model it marks `reasoning: true` for `thinking: {type: "enabled", budget_tokens}`, which the current Claude models refuse with a `400` after the call was sent, leaving its reservation held. Declare the target [`thinking_mode: adaptive`](/docs/features/protocol-translation/#claude-thinking-mode): the gateway then refuses that request itself with `422 unsupported_on_provider` before anything is sent, and nothing is held. In pi, mark the model `reasoning: false`, or use a model that takes a thinking budget. - **Tools with an effort.** On Chat Completions the current OpenAI models refuse function tools with a reasoning effort, so the chat alias needs [`api: auto`](/docs/features/protocol-translation/#api-auto-the-api-chosen-per-request) as for OpenCode. ### Grok CLI Measured with the Grok CLI 1.0.92 (`@xai-official/grok`) and custom models, 2026-11-27, on its three backends: `messages` (`grok_cli_messages_shape.jsonl`: the title call and two calls of the task), `responses` (`grok_cli_responses_shape.jsonl`) and `chat_completions` (`grok_cli_chat_shape.jsonl`), two calls each. **Nothing to configure for the budget.** Without `max_completion_tokens` on its custom model the client asks for 128,000 output tokens on every call, and the reservation holds that limit as asked. To reserve less per call, set `max_completion_tokens` on the model (the recordings used 8,192), or lower the limit in the gateway with the target's `max_output_tokens` ([request parameter policy](/docs/features/request-parameter-policy/)): ```toml # ~/.grok/config.toml [model.gateway] model = "claude-haiku-5-5" base_url = "https://gateway.example.com/v1" name = "Gateway" env_key = "GATEWAY_KEY" api_backend = "messages" # or "responses", "chat_completions" max_completion_tokens = 8192 ``` | What the Grok CLI sends | Rule | | --- | --- | | Chat: `model_id` on an assistant message handed back (the model that wrote it) | Admitted as a string on an assistant message, like `name`; on any other role it is refused | | Messages: cache marks, a forced `tool_choice` on the title call; Responses: `reasoning: {summary}`, `include`, `prompt_cache_key`, `store: false`, function tools; chat: `max_tokens`, `stream_options.include_usage`, function tools | Already in the profiles | | `max_tokens: 128000` (the client's default) | Reserved as asked ([output limit](/docs/features/budgets-and-tpm/#quota-settings)) | Two things to expect: - **Helper calls use the client's own model name.** The session title goes to `grok-4.6` on the same endpoint. Without an alias of that name the call is refused (`model_forbidden` or `capability_unsupported`) and the task still runs; with one, it is budgeted like any call. - **A headless run can leave one held reservation.** `grok -p` starts a turn summary as it exits and closes the connection a few milliseconds later. If the call had already gone out to the provider, it is cut before its answer ended and [keeps its reservation](/docs/features/budgets-and-tpm/#how-the-reservation-works), because the provider may have charged for it. Turn on [`stream_settle_on_disconnect`](/docs/features/stream-usage/#when-the-client-disconnects) and the gateway reads that answer to its end and settles it (measured on 2026-11-27: the summary settled at 478 input and 11 to 14 output tokens). ### Cursor and Antigravity Neither can be run under a budget on a gateway that only your own machine or network reaches, and the gateway ships no recognition rule for them. Checked on 2026-11-27: | Client | Custom model endpoint | What the vendor's documentation and the client itself show | | --- | --- | --- | | Cursor editor | Only one that Cursor's own servers can reach, and only on a paid Cursor plan | The [API keys page](https://cursor.com/docs/settings/api-keys) says a custom key is "sent to our backend with every request" and that all requests are routed through Cursor's servers for the final prompt. The model call is made from Cursor's servers, not from the editor: a gateway on `localhost` or a private network never receives it. Custom keys work with chat models only; Tab keeps Cursor's models. On the Free plan the editor (3.32.4, 2026-11-27) sends nothing to a custom endpoint: with a key, the base URL override and a custom model set, it answers "Cursor Subscription Required: Agent and Edit rely on custom models that require a paid subscription" before any request | | Cursor command-line agent (`agent`, `cursor-agent`), version 2026.11.22 | None | It refuses to run without a Cursor account (`Authentication required`). Its one endpoint option (`--endpoint`, `CURSOR_API_ENDPOINT`) defaults to Cursor's own API, and the model is chosen by Cursor's model names. The package carries hidden options for a provider base URL, and the released build refuses them (`--base-url can only be used with agent-cli-local`) | | Antigravity (editor and CLI) | None | The [plans page](https://antigravity.google/docs/plans) lists "Bring-your-own-key (BYOK) or bring-your-own-endpoint" under what is not supported. Model traffic goes to Google's own hosts after a Google sign-in ([enterprise deployments](https://antigravity.google/docs/enterprise) lists them for firewall allowlists) | On a paid plan the Cursor editor can be pointed at a gateway that is published on the internet (**Settings → Models → Override OpenAI Base URL**). What it then sends was not measured here (the test account was on the Free plan): the requests would come from Cursor's servers, with a prompt Cursor builds, so the rules above for other clients do not describe them. Put a budget on such a key only after reading the refusals its first requests produce. ## Translated providers Behind the chat route (and every translated route), Bedrock, Anthropic, Gemini, Cohere and an openai target with `api: responses` (or `api: auto`, when the request goes to Responses) answer in their own format, which the adapter translates. The translated body names the public alias and folds cache reads into `prompt_tokens`, so it cannot prove the billed model or price the cache. The adapter reads the native answer anyway; under a budget it hands what that answer proves to the settlement, and the bytes the client receives do not change. | Provider | Model proven | Terminal answer | Counters | Kept reservation | | --- | --- | --- | --- | --- | | Bedrock Converse | The model in the request path (Converse names none, and the call cannot change it) | `stopReason` (`end_turn`, `tool_use`, `max_tokens`, `stop_sequence`, `content_filtered`); in a stream, `messageStop` then `metadata` | `inputTokens` plus `cacheReadInputTokens` and `cacheWriteInputTokens` (one-hour writes from `cacheDetails`); `outputTokens`; `totalTokens` consistent | Guardrail intervention or trace, latency-optimized or non-default service tier, unknown categories | | Anthropic Messages | `model` | `stop_reason`; in a stream, `message_start` → `message_delta` → `message_stop` | `input_tokens` plus cache read and creation tokens (one-hour writes from `cache_creation`); `output_tokens` (thinking included) | Server tool use, cited (searched) text, a tier other than standard, a regional inference surcharge | | Gemini | `modelVersion` | One candidate with a final `finishReason` | `promptTokenCount` (cached part included), `candidatesTokenCount` plus `thoughtsTokenCount`; `serviceTier` only `standard` | Flex or priority tier, grounding, tool-use prompt tokens, provisioned throughput, non-text modalities, a blocked prompt | | Cohere v2 | The requested model (the answer names none) | `finish_reason`; in a stream, `message-end` | `billed_units` (the raw counts include Cohere's own template) | Search units or other billed units | | OpenAI Responses (`api: responses`) | `model` | `response.completed` / `response.incomplete` | `input_tokens` (cache reads in the details), `output_tokens` (reasoning inside) | Hosted tool calls, citations, a non-default tier, failed or cancelled responses | Vertex AI's `text-embedding-*`, `text-multilingual-embedding-*` and `textembedding-gecko*` models are priced per 1,000 characters, not per token, so they are refused under a budget or a token ceiling and no token rate can be approved for them; the token-priced `gemini-embedding-*` models are measured. Refused: **SageMaker** bills endpoint instance time, not tokens, and its container's usage has no contract; **OCI** bills several on-demand models per character, and its stream has no terminal event to prove the end of an answer. A stream the provider cuts, an error event, a second proof or a measurement that arrives after the request ended keeps the reservation. ## Bounds the gateway keeps - **Guardrails:** with input guardrails on, the reservation is estimated from the request as they left it: a mask can turn a short match into a longer `[REDACTED:]` placeholder, and the provider bills what it receives. - **Usage over the bound:** if a provider still bills more than the reservation, in tokens or in money (a budget without a token ceiling can overrun only in USD, when more output than estimated costs more than the input it replaced), the settlement debits the full amount (never truncated), the measurement proof and the ledger record `overrun_tokens` and `overrun_usd`, and the gateway logs `quota_reservation_overrun`, and the settlement writes the alert event of the same name in its own transaction, so no overrun settles without its alert, however many settle at once. - **Cache write split:** a cache write settles only with a time-to-live breakdown that accounts for every write (Anthropic's `cache_creation`, Bedrock's `cacheDetails`, their five-minute and one-hour parts adding up to the total); absent, empty or short, the writes may be one-hour writes, so the reservation stays. - **Images the gateway can inspect:** an inline image (a chat or Responses data URL, a Messages `base64` source, a Gemini `inlineData` part) counts only when its leading bytes are the PNG, JPEG, GIF or WebP its MIME type declares. A URL counts only over https, in fields that take images alone (chat `image_url`, Messages `url` sources, Responses `input_image`), and only where the provider documents that it fetches such a URL as an image and bills it by the image rules: the OpenAI API (chat and Responses) and Claude Messages on the Anthropic API. Anywhere else (a third-party OpenAI-compatible or Anthropic-compatible host, a translated route) a URL needs `image_urls: true` on the approved rate; the translating adapters take data URLs only. A Gemini `fileData` URI is refused: its MIME type is the client's claim, and Gemini bills the file by its real type. - **Running counts:** a Gemini stream reports usage on many chunks; only the usage on the finishing chunk or after it settles. ## Image sizes A per-image ceiling alone ignores size, and providers bill a large image more than a small one. For each inline image the gateway reads the width and height from the PNG, JPEG, GIF or WebP header (a JPEG's largest frame before its first scan; a GIF's logical screen or its first frame, whichever reaches further, since decoders grow the image to cover the frame: Nova Lite billed a 2000×2000 frame behind a 16×16 screen exactly like a 2000×2000 GIF, 2,621 tokens against 541) and computes the provider's documented formula for the connection; the reservation takes the larger of that and the rate's `image_input_tokens`. A URL's size is unknown before the provider fetches it, so it is reserved at the provider's documented maximum per image. An inline image whose header does not give a size is treated the same way, and refused where no maximum is documented. | Connection/profile | Reservation formula used by the gateway | Unknown-size reference | Source | | --- | --- | --- | --- | | OpenAI API (`api.openai.com`), patch-based models | ceil(multiplier × patches), 32×32 patches, at most 30,000 (larger images are rejected); multiplier 1.2 to 2.46 by model | multiplier × 30,000 | [OpenAI images and vision, calculating costs](https://developers.openai.com/api/docs/guides/images-vision) | | OpenAI API, tile-based models | base + tile tokens × 512-px tiles, after fitting in 2048×2048 and the shortest side in 768 (gpt-4o 85 + 170, gpt-4o-mini 2,833 + 5,667) | base + 8 tiles | Same page | | OpenAI API, a model the tables do not name | The largest of the implemented published-family formulas | 73,800 from those known families; not a guarantee for future models | Same page | | Claude: Anthropic API, Claude on Bedrock, Anthropic-compatible connections | ceil(width/28) × ceil(height/28), at most 4,784 | 4,784 (high-resolution tier; the standard tier stops at 1,568) | [Claude vision, resolution and token cost](https://platform.claude.com/docs/en/build-with-claude/vision) | | Gemini 3 and later | 1,120 at the default and high media resolution (the 2,240 ultra-high level is set per part, which the profile refuses) | 1,120 | [Gemini media resolution](https://ai.google.dev/gemini-api/docs/media-resolution) | | Earlier Gemini models | 258 up to 384×384; above, 258 per tile, counting tiles of the shortest side over 1.5, kept between 256 and 768 px (never fewer tiles than the documented 768-px tiling) | None: an image of unknown size is refused | [Gemini token counting](https://ai.google.dev/gemini-api/docs/tokens) | | Gemini models matching neither | The larger of both rules | None | Both pages | | Amazon Nova 2 on Bedrock | 230, flat | 230 | [Amazon Nova 2 multimodal understanding](https://docs.aws.amazon.com/nova/latest/nova2-userguide/using-multimodal-models.html) | | Any other connection (Amazon Nova 1, third-party OpenAI-compatible hosts, Cohere) | No published formula: Nova 1 documents approximate counts only, up to about 2,600 for a 1.3K×1.3K image ([Amazon Nova image understanding](https://docs.aws.amazon.com/nova/latest/userguide/modalities-image.html)) | None | The approved `image_input_tokens` is the bound | These are the gateway's implemented reservation references, not a promise that an unlisted or future model shares another model's billing rules. Approve `image_input_tokens` against the selected model and endpoint; review it when the provider changes its contract. **Setting a ceiling where no formula is published.** On such a connection the rate's `image_input_tokens` is the operator's bound. The following are historical Amazon Nova Lite v1 samples through Converse (us-east-1, October 2026), not fresh certification or a maximum for every input. One PNG with a one-line prompt billed: | Image | Input tokens billed (image and prompt) | | --- | --- | | 32×32 | 535 | | 64×64 | 541 | | 1000×3000 | 1,085 | | 4000×1000 | 1,303 | | 4000×3000 | 1,677 | | 900×600 | 1,831 | | 1800×900 | 2,349 | | 2000×2000 | 2,615 | | 1500×1500 | 2,621 | In those samples, the highest counts occurred near 1,500 to 2,000 pixels a side; a ceiling of 3,000 covered the measured sizes, and 2,000 did not. These observations do not prove that 3,000 bounds every possible request. The console warns beside a rate whose image ceiling is below the documented maximum of its model family (Claude 4,784, Gemini 3 1,120, Nova 2 230, each OpenAI model's maximum) or the measured one (Nova v1, 2,621); it does not refuse it. The OpenAI-compatible endpoints of Anthropic and Gemini use their provider's rule. For known OpenAI families, the reservation uses the conservative formula above rather than estimating a discount from `detail`; model-specific sizing rules still apply upstream. A model is matched by its documented name or a dated snapshot of it (`gpt-4o-2024-08-06`); any other suffix is a different model. ## Prompt caching Answers report the tokens read from (and on some providers written to) the provider's prompt cache. These are input tokens at another price, never plain input: - OpenAI shape: `prompt_tokens_details.cached_tokens` (and the write as `cache_write_tokens`, `cache_creation_tokens` or `created_cache_tokens`) inside `prompt_tokens`; DeepSeek's `prompt_cache_hit_tokens` and `prompt_cache_miss_tokens` must add up to `prompt_tokens`; - Anthropic and Bedrock: the cache read and write counts beside the input count; - Gemini: `cachedContentTokenCount` inside `promptTokenCount`; - Responses: `input_tokens_details.cached_tokens` inside `input_tokens`. With `cache_read_usd_per_million`, `cache_write_usd_per_million` and `cache_write_1h_usd_per_million` on the approved rate, each category settles at its own price (one-hour writes are read from Anthropic's `cache_creation` and Bedrock's `cacheDetails`; an OpenAI-shaped write has no time to live and is a five-minute write). Messages accepts `cache_control` with `ttl` `5m` or `1h`, and so does the chat profile (T115) on a Claude target (Anthropic or Claude on Bedrock): on a content part, a message or a function tool, the marks a Chat Completions client sends and the canonical form of a translated Messages request ([prompt caching](/docs/features/prompt-caching/)). On any other target the marks are removed before the call, except on an OpenAI Chat Completions passthrough, where a marked request stays outside the profile (`text_messages_only`): its writes carry no time to live. Automatic points a target adds (`prompt_cache`) are not in the request the reservation reads; the reservation already prices every input token at the highest input-side price the rate approves, one-hour writes included. Without the matching price, the reservation stays: the gateway does not guess a discount, nor charge cached tokens as plain input. The measurement records the cache categories (`cache_read_tokens`, `cache_write_tokens`, `cache_write_1h_tokens`) as part of the input; token ceilings count every input token. ## Long context A rate's `long_context` tier (threshold and higher prices, see [budgets and TPM](/docs/features/budgets-and-tpm/#approved-rates)) settles a request whose measured input (cache included) exceeds the threshold entirely at the tier's prices, and a cache category the tier does not price keeps the reservation. The reservation takes the highest prices of both tiers whenever the input estimate exceeds the threshold. ## What is left out To avoid applying the wrong price, these cases **keep the reservation** (or are refused) instead of using the text rate: - prompt caching without an approved cache price, server tools, service tiers and unrecognized usage categories; - reasoning, unless the provider proves it is part of the output: `completion_tokens_details.reasoning_tokens` no larger than `completion_tokens`, and `total_tokens` equal to input plus output. Then the reasoning text (`reasoning` or `reasoning_content`) is ordinary output at the output rate; a provider that bills reasoning on top of the output reports a larger total and keeps the reservation; - media in Gemini: only TEXT modality details count; - GPT Image streams, partial images, SVG and GIF output, and any GPT Image answer whose usage is not proven ([GPT Image budgets](#gpt-image-budgets)); - audio in a compressed format: duration is read only from WAV PCM, with no guessing; - TPM for images, audio and rerank: these units are not tokens, and the gateway does not convert seconds into tokens to get around the policy. Use a budget policy for these profiles. ## GPT Image budgets With `quota_image_tokens` (off by default; requires `quota_media`), budgets and token limits admit `/v1/images/generations` and `/v1/images/edits` requests to a GPT Image model (`gpt-image-*` on the openai protocol). Before the flag, and for any other image model without a per-image profile, they are refused with `image_token_pricing_requires_separate_profile`. The approved rate prices text and image tokens apart and bounds what one generated image can bill: ```yaml quotas: rates: - provider_id: openai model: gpt-image-2.6-flare connection: input_usd_per_million: "5" # text input output_usd_per_million: "30" # text output; see below image_input_usd_per_million: "8" image_output_usd_per_million: "30" image_input_tokens: 1000 # ceiling per input image (edits) image_output_tokens: 6000 # ceiling per generated image revision: gpt_image_2026_11 ``` | Field | Default | Bounds | Meaning | | --- | --- | --- | --- | | `image_input_usd_per_million`, `image_output_usd_per_million` | none | decimal USD, up to 6 places, at most 10000; both or neither | The image token prices. Not combinable with `long_context` or `service_tiers`: the Images API documents neither. | | `image_output_tokens` | none | 1-1,000,000, beside the image prices | Your ceiling of output tokens per generated image. The profile does not restrict `size`, `quality` or `complexity`, so set it for the largest the provider accepts: a request above it bills past the reservation (debited in full and flagged as an overrun). Without it a GPT Image request is refused (`422 quota_profile_unsupported`), under a budget or a token ceiling alone. | | `image_input_tokens` | none | 1-1,000,000 | The existing per-image input ceiling: each input image of an edit, and its `mask` or `markup`, is reserved at it. `image_urls: true` is needed for https image URLs. | The reservation is the prompt's UTF-8 bytes (no prompt token is shorter than a byte; text tokens the provider adds around the prompt bill past it as an overrun) plus `image_input_tokens` per input image, priced at the higher of the text and image input prices, and `n` × `image_output_tokens`, priced at the higher of the text and image output prices. OpenAI publishes per-size and per-quality output token counts only for the models before `gpt-image-2` (272 to 6,240 tokens for `low` to `high`); for newer models it points to its calculator, so the ceiling is yours to approve and review when the provider changes its rules. An answer that bills more is debited in full and flagged as an overrun, like any other profile. What a request may carry: `model`, `prompt` (1-32,000 characters), `n` (1-10, default 1), `size`, `quality`, `background`, `output_format` (`png`, `jpeg` or `webp`), `output_compression`, `moderation`, `complexity`, `input_fidelity`, `user`, `safety_identifier`, `stream: false` and `partial_images: 0`; an edit also its images, `mask` or `markup`. A stream, partial images (each adds 100 image output tokens and needs a stream), `svg` (its authoring model bills apart in `svg_usage`), `gif`, `service_tier` or any other field is refused before the provider. The answer settles from the usage the gateway reads after the images (the same scanner as [usage valuation](/docs/features/usage-valuation/#gpt-image-tokens)): text input at `input_usd_per_million`, image input at `image_input_usd_per_million`, image output at `image_output_usd_per_million` and, when the answer splits its output, text output at `output_usd_per_million`. An answer that does not split its output is all image output only when `output_usd_per_million` equals the image output price; otherwise which part was text is unproven and the reservation is held. OpenAI publishes no text output price for `gpt-image-2.6-flare`, so approve its image output price there. The measurement proof keeps the image split (`image_input_tokens`, `image_output_tokens`), so a later reconciliation prices it the same way. An answer the scanner cannot prove (malformed, cut short, with an `error` or `svg_usage`, counts that do not add up) keeps its reservation. This profile is qualified on PostgreSQL. ## Response model different from the request Many APIs accept an alias (`gpt-4o-mini`) and respond with the dated snapshot (`gpt-4o-mini-2024-07-18`). By default, the gateway requires the response to carry the exact model requested. To accept snapshots, declare them in the approved rate: ```yaml quotas: rates: - provider_id: openai model: gpt-4o-mini response_models: [gpt-4o-mini-2024-07-18] # ... ``` - Up to eight literal IDs, with no wildcard or prefix; allowed characters: letters, digits and `._:/+-`, starting with a letter or digit. - Omitting the field or using `[]` keeps exact matching; `null` is invalid. - The list does not change routing, credentials, capability or price: it only says which response names prove the same rate. - Changing the list requires a new review of the rate. In a stream, the first model observed stays fixed until the end. - It does not apply to per-unit rates (image, audio, rerank). ## Physical units Images, seconds of audio and search units use a per-unit rate: `unit`, `variant` (for example `1024x1024_standard`, `whisper_duration`, `cohere_v2`) and `unit_usd`, with up to six decimal places. The console shows the human unit separately from tokens. ## Proof of usage Anthropic usage accepts the documented standard speed (`speed: standard`, or an absent/null field). Fast mode, an unknown speed, nonstandard service tiers and regional usage not covered by the protected profile retain the reservation. The legacy `inference_geo: not_available` denotes an unset geo, like an absent/null field; it does not authorize US regional pricing. Optional null response metadata does not create a billed category. See the official [Messages usage contract](https://platform.claude.com/docs/en/api/messages), [speed reporting](https://platform.claude.com/docs/en/manage-claude/usage-cost-api) and [data residency pricing](https://platform.claude.com/docs/en/manage-claude/data-residency) and [legacy geo reporting](https://platform.claude.com/docs/en/manage-claude/usage-cost-analytics-api#migrate-from-the-usage-and-cost-api). Each eligible response generates an immutable **measurement** (with no payload) containing the model, connection, categories, counts and checksum. The measurement is written before settlement; if settlement fails later, it lets you reconcile the reservation in [financial reconciliation](/docs/features/quota-finance/). Read limits for measuring: - streams: 256 KiB per event, 32 MiB and 100,000 events; - JSON: 4 MiB. A larger response is delivered normally, but without complete proof the reservation stays; - requests: 64 levels of JSON nesting (tool schemas nest deeply) and a parser budget of 262,144 JSON values. An error, a limit being reached, an end without termination, cancellation, a model change mid-stream or partial usage **do not release** the reservation. The gateway never repeats a call to recover the usage. ## Validate selected profiles against a real provider For contributors with local Docker/OrbStack and the pinned integration images already loaded, `scripts/verify-quota-live.py` runs selected profiles through a temporary **production gateway binary**, isolated PostgreSQL and two synthetic billing owners. It approves the plan's exact prices through the admin API, sends inference through the public API and compares reservations, immutable measurements, ledger settlement and request/trace IDs. Existing installations and operator configuration are not changed. Create a private JSON plan in the ignored `test-results/` directory. This minimal compatibility example uses a model exercised in November 2026, not a recommendation to deploy that deprecated model: ```json { "providers": [{ "provider": "openai", "model": "gpt-4.1-mini", "response_models": ["gpt-4.1-mini-2025-04-14"], "rates": { "input_usd_per_million": "0.40", "output_usd_per_million": "1.60", "cache_read_usd_per_million": "0.10" }, "profiles": ["chat_json"] }], "max_requests": 1, "max_output_tokens": 64, "budget_usd": "0.25" } ``` Check the model, capability, snapshot IDs and every price against the provider's current official documentation before executing. Rates are operator approvals, never automatically inferred from catalog prices. `budget_usd` is a test-owner enforcement ceiling, not a guarantee of an external provider charge. Bound the combined attempt allowance across every author/reviewer run separately; a failed or timed-out send still consumes an attempt. First exercise setup without credentials or inference: ```sh python3 scripts/with-test-services.py -- \ python3 scripts/verify-quota-live.py \ --plan test-results/quota-plan.json --prepare-only \ --report test-results/quota-prepare.json ``` After explicit authorization for the selected providers and spend, run outside the quality gate: ```sh GATEWAY_TEST_REAL_QUOTAS=1 python3 scripts/with-test-services.py -- \ python3 scripts/verify-quota-live.py \ --plan test-results/quota-plan.json \ --credentials /absolute/path/to/private-provider.env \ --report test-results/quota-live.json ``` Only the selected `OPENAI_API_KEY`, `ANTHROPIC_API_KEY` or `GEMINI_API_KEY` variables are parsed as data; the credential file is never shell-sourced. No real credential is copied into configuration, reports or fixtures. Keep reports private even though they contain only bounded metadata, counters and checksums. A report path must be new. Owned processes, configuration and services are removed on success or failure. Supported selections are OpenAI `chat_json`, `chat_stream`, `responses_json`, `responses_stream`; Anthropic `messages_json`, `messages_stream`, `messages_cache_write`, `messages_cache_read`; Gemini `generate_json`, `generate_stream`. Cache profiles must be a write/read pair in that order with explicit read and one-hour-write prices; the helper creates a unique synthetic prefix. Anthropic connections requiring a workspace accept a non-secret `workspace_id` in the private plan, passed through the existing operator header policy. The selected 2026-11-01 acceptance resolved that workspace requirement and covered real native Messages image/one-hour-cache write/read and SSE. Historical account access is not current quota proof; the translated Chat regression replay used a synthetic provider and is not live translation certification. `json_image: true` requires an approved single-image ceiling; the helper sends only a small synthetic inline PNG, including in both JSON calls of a selected cache write/read pair; the shared system-cache prefix remains identical. `stream_tool: true` exercises OpenAI client function output, not a hosted provider tool. The helper validates official endpoints, refuses redirects and never retries inference. A provider's HTTP 200 alone is not success: an unknown reservation or absent complete measurement fails the run. The successful result proves usage settlement at the approved rate; it does **not** reconcile an invoice, certify every model or change production flags. The quality gate runs only the helper's deterministic guard/privacy tests and recorded response regressions; it refuses real-provider opt-ins. ## See also - [Budgets and TPM](/docs/features/budgets-and-tpm/). - [Usage in streams](/docs/features/stream-usage/). - Official contracts: [OpenAI streaming](https://developers.openai.com/api/reference/resources/chat/subresources/completions/streaming-events), [OpenAI function calling](https://developers.openai.com/api/docs/guides/function-calling), [OpenAI prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching), [OpenAI embeddings](https://developers.openai.com/api/reference/resources/embeddings/methods/create), [Anthropic streaming](https://platform.claude.com/docs/en/build-with-claude/streaming), [Anthropic prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching), [Bedrock Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html), [Gemini GenerateContent](https://ai.google.dev/api/generate-content), [Cohere Chat](https://docs.cohere.com/reference/chat), [OpenAI images](https://developers.openai.com/api/reference/resources/images/methods/generate), [OpenAI transcription](https://developers.openai.com/api/reference/resources/audio/subresources/transcriptions/methods/create), [Cohere Rerank](https://docs.cohere.com/reference/rerank). # Financial reconciliation **Last updated:** 2026-11-27T13:41:51-03:00 (UTC-3) [Budgets](/docs/features/budgets-and-tpm/) reserve up front and settle afterwards, with what the provider reports. Sometimes the settlement does not happen: a timeout, a crash, a truncated response. The reservation stays held, for safety. Financial reconciliation resolves this with proofs, and compares what the gateway estimated with what the provider actually charged. Flag: `quota_finance`, which requires `quota_management`, `durable_usage` and PostgreSQL. In the console: **Budget & TPM → Finance & reconciliation**. ## Three different facts | Fact | Where it comes from | What it proves | | --- | --- | --- | | **Reservation** | Admission, with the approved rate | The maximum the call could cost | | **Measurement** | The provider's response, validated by the [profile](/docs/features/quota-protocols/) | The tokens or units consumed | | **Imported charge** | A billing export you send | What the provider says it charged | The gateway never confuses one with another. An analytics log, the client's `X-Request-Id`, a timeout or the end of a window do not replace a measurement. Importing a charge does not change balances on its own. ## Importing charges `POST /api/v1/admin/quota-finance/imports` receives a **statement** with: - the import ID, source, an HTTPS link to the original (no credentials or query) and the file's SHA-256; - the external account, a UTC interval of up to 366 days, USD currency and coverage (`partial` or `complete_export`); - from 1 to 1,000 lines (up to 512 KiB), each with an external ID, the exact connection and model, a category (`charge`, `credit`, `tax` or `adjustment`) and a decimal amount with up to 12 decimal places; - optionally, the internal inference ID and the provider's native request ID. Rules: - **Immutable.** The same import with the same content is idempotent. Different content with the same ID, the same file with another ID, or lines repeated across overlapping exports produce a conflict. A correction is a new adjustment or credit line. - **No double counting.** Aggregate reports from the same source and account cannot have overlapping periods. - **Linking.** A line becomes `matched` only when the internal ID, the native ID the gateway saw in the provider's response, the connection, the model and the interval all match. Without a link, it is `aggregate`; with an unproven link, `unmatched`. Gemini does not provide a native ID, and the gateway does not invent one. - `complete_export` means you sent the whole declared export, not that the invoice is complete. The gateway validates structure and amounts; it does not authenticate the provider's signature. To convert the official OpenAI and Anthropic exports into this format, use the [native billing imports](/docs/features/native-billing-imports/). ## Report `GET /api/v1/admin/quota-finance/report` sums all selected lines, with charges, credits, taxes, adjustments, net and estimates shown separately. `import_id` limits it to one import. - Each linked inference counts once in the estimate, even with several external lines. - `linked_estimate_lines` and `linked_unestimated_lines` tell how many linked charges do or do not have an estimate. - `invoice_coverage: not_verified` is deliberate: the report covers what was imported, not the external invoice or a tax audit. - A zero subtotal with missing coverage does not prove zero cost. ## Releasing a reservation with a measurement When the settlement failed but the measurement was recorded: 1. `GET /api/v1/admin/quota-finance/evidence?reservation_id=...` shows the evidence. 2. `POST /api/v1/admin/quota-finance/reconcile`, with the operation ID, reservation ID, `measurement_fingerprint` and version. The gateway checks the checksum, connection, model, unit and rate of the reservation, and adjusts the counters **in the original windows**. Repeating the same operation is idempotent; divergent or generic evidence is rejected without touching the balance. Without a valid measurement, the reservation stays held. ## Releasing USD with a charge `POST /api/v1/admin/quota-finance/reconcile-charge`, with the operation ID, import and line, the file's SHA-256, version and the confirmation `ATTEST_PROVIDER_CHARGE_USD_ONLY`. - Only a **positive**, unique charge, `matched` by native ID, replaces the reserved USD amount, and only on a reservation that is still unknown and has an approved rate. - Aggregate, ambiguous and zero lines, credits and taxes release nothing. The absence of a line does not prove there was no charge. - **TPM stays reserved:** a dollar charge does not prove tokens. A later token settlement preserves the USD already reconciled. `budget_basis` and `reconciled_charge_usd` in the evidence show where the balance came from. ## Releasing an unknown reservation by hand Some unknown reservations can never be reconciled: the provider gives no native request ID to match a charge line against (Gemini on Vertex), or you have no billing export for that account. Their hold lasts until each window rolls over, and forever on a lifetime budget. A manual release is the one explicit way out. **What it is, and what it is not.** An administrator gives back the holds of an unknown reservation and writes down why. The gateway never does this by itself: no timer, window end, import or restart releases an unknown reservation. The release proves nothing about the provider. **The provider may still have charged for the call**; every answer and every record says so. Use it when you have decided, outside the gateway, how that cost is accounted for. **Turn it on.** Flag `quota_manual_release`, off by default; it requires `quota_finance`. It is an operator flag, changed in the YAML or under **Settings & sources**: ```yaml features: quota_finance: true quota_manual_release: true ``` **Who can.** The permission `quota_reservations:release`. The global admin holds it for every organization. With [organization admins](/docs/features/organization-admins/) on, an organization admin holds it for reservations of its own organization's teams. Nobody else does, and a custom role cannot receive it. **In the console.** **Budget & TPM → Finance & reconciliation → Unknown reservations** for the global admin; **My organization → Unknown reservations** for an organization admin. Filter the list (the global admin also by organization), tick the reservations, write the reason in one line, confirm that the provider may still have charged, and release. A refused release says why and changes nothing. **Manual releases**, below it, shows the trail. The screen appears only with both flags on and the permission in your session. **Steps (API):** 1. `GET /api/v1/admin/quota-finance/unknown-reservations` lists the held unknown reservations, oldest first. Filter with `team_id`, `key_id`, `provider_id`, `model`, `organization_id`, `created_after` and `created_before`. Each item shows what it holds (`windows`: every subject, dimension, window and amount) and whether it is `releasable`. The answer carries the finance `version` to send back. Page it with `limit` (1 to 100, default 50) and `offset`. 2. `POST /api/v1/admin/quota-finance/release-unknown` releases them: ```json { "id": "release-vertex-2026-11", "version": 12, "reason": "Vertex stream cut before the fix; no native ID to reconcile", "confirmation": "RELEASE_UNKNOWN_PROVIDER_MAY_HAVE_CHARGED", "reservation_ids": ["0f3a...32 hex...", "9b1c...32 hex..."] } ``` | Field | Rule | | --- | --- | | `id` | Operation ID, 2 to 64 characters (`a-z`, digits, `_`, `-`, starting with a letter). The same ID with the same content is idempotent; with other content it is a conflict | | `version` | The finance version from the list; a stale one answers `409` | | `reason` | Required, one line of 10 to 500 characters. It is kept in the finance trail | | `confirmation` | Exactly `RELEASE_UNKNOWN_PROVIDER_MAY_HAVE_CHARGED` | | `reservation_ids` | 1 to 100 reservation IDs; **or** | | `filter` + `expected_count` | The same filter members as the list, at least one, with the number of reservations you reviewed (1 to 100). If the filter selects another number the release is refused with `release_count_mismatch` | All the named reservations are released in one transaction, or none is. **What a release does.** For each reservation it subtracts the reserved amounts from the counters of the **original windows**, moves the reservation to `released`, and writes two records: - a **finance-trail row** (`GET /api/v1/admin/quota-finance/manual-releases`): who, when, the reason, the reserved USD and tokens, and each window given back, with `open: true` when that window was still the current one (an ended window changes no current balance; a lifetime window is always open). Rows are written once and never changed. The trail is read newest first, paged with `limit` (1 to 100, default 50) and `offset`, and narrowed to one organization with `organization_id`. - an **audit row** with the action `quota.reservation.release_unknown`, the actor, the request ID and the reservation's organization. Afterwards the [evidence](#releasing-a-reservation-with-a-measurement) of that reservation shows `budget_basis: manual_release_unproven`, and cost reports treat its budget charge as unknown, never as zero. The daily [reconciliation](/docs/features/billing-connectors/) keeps counting a released reservation among the day's unknown ones until a provider charge is attested for it. **When the provider's charge arrives afterwards.** A release is not the last word. If you later import a charge line for that call and it is `matched` by the provider's native request ID, attest it with `POST /api/v1/admin/quota-finance/reconcile-charge` as for any [charge](#releasing-usd-with-a-charge) (global admin, `quotas:manage`). For a released reservation the charge goes **back into the budget**: - the charged amount is added to every money window the release gave back that is **still the current one**: day, week, month, quarter, year and lifetime, for each subject. A charge smaller than the released hold adds only the charge; - a window that has rolled over since takes nothing, and the record lists it with `skipped: window_rolled_over`; - a **zero** charge is accepted for a released reservation: it adds nothing and is recorded (`skipped: zero_charge`), so the call is settled as not charged; - token windows (TPM, TPD) are never held again: a dollar charge proves no tokens; - it is applied once per reservation and per charge line. Repeating the same operation changes nothing; another operation on the same line or reservation answers `409`. - as for any charge, the call must have exactly one matched charge line: with two, neither is applied (`422`), and you correct the import first. The answer has `state: released_charge_reapplied` and a `released_charge` object with each window and what was added. The same object appears as `charge` on the release in the trail (and in the console's **Manual releases**), an audit row `quota.reservation.release_charge_reapplied` is written with the reservation's organization, and the evidence of the reservation moves from `manual_release_unproven` to `budget_basis: manual_release_charge_attested`, with `reconciled_charge_usd`. Cost reports then show that charge as the call's budget charge. An organization admin sees it on its own releases; attesting a charge stays with the global admin. It needs `quota_finance` only, so a charge still goes back if `quota_manual_release` was turned off after the release. **What is refused**, with nothing released: | Answer | Why | | --- | --- | | `409 reservation_not_unknown` | A reservation is not held as unknown, or does not exist in your scope | | `409 measurement_available` | A validated measurement exists: use `POST .../reconcile`, which settles the real amount | | `409 charge_reconciled` | An attested provider charge already owns its budget | | `409 release_count_mismatch` | The filter no longer selects `expected_count` reservations | | `403 organization_forbidden` | An organization admin named a reservation of another organization, or one that also holds a ceiling set above its organization | | `404 feature_disabled` | `quota_finance` or `quota_manual_release` is off | **Organization admins.** An organization admin lists and releases only reservations of its organization's teams, and reads only its own trail and audit rows. A release returns every hold of a reservation, so it cannot release one that also holds a ceiling set from above: a tenant ceiling of its organization, a global or provider budget that is in force, an attribution group, a subject list or a hierarchy account. Those appear in its list with `blocked: outside_organization`, and the global admin releases them. ## Archiving the ledger 1. `GET /api/v1/admin/quota-finance/retention?retain_days=90&limit=500` shows what would be archived. 2. `POST /api/v1/admin/quota-finance/retention`, with the preview unchanged, version, fingerprint and the confirmation `ARCHIVE_TERMINAL_LEDGER`. The preview is valid for 15 minutes. - Only closed reservations (`settled` or `released`) older than 32 days are archived, up to 1,000 per batch. - The full record and its SHA-256 remain queryable at `GET .../archive` and in the console. - **Nothing is deleted:** unknown reservations, counters, proofs, imports, reconciliations, manual-release records and audit records stay. - A late charge can still be linked to an archived reservation (`archived: true`), but it does not reopen the balance. Calendar-budget upgrade uses these retained originals to preserve current week, quarter and year consumption, without reopening or rewriting terminal/archive records. Lifetime upgrade adds the permanent view from all retained protected history, including unresolved reservations from prior years. Financial reports count the original reservation once; calendar/lifetime shadow counters are not separate provider charges. See the [coordinated upgrade procedure](/docs/features/budgets-and-tpm/#upgrade-from-a-version-before-calendar-budgets). Archiving is not a backup, WORM or regulatory retention. ## Who can Read with global `quotas:read`; write only by a global admin, with `quotas:manage`, CSRF and audit. Team roles do not see financial data. The [manual release](#releasing-an-unknown-reservation-by-hand) has its own permission, `quota_reservations:release`. All responses are `no-store`. Billing credentials are never the inference credentials and do not appear in the console. ## Measured performance On a local PostgreSQL, 100 synthetic inferences with 12 concurrent workers (reservation, measurement and settlement) took 999 ms: p50 of 99.6 ms, p95 of 298.8 ms and p99 of 342.8 ms. The number includes database latency and contention over the same subjects; it does not measure the network, the provider or Kubernetes. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `GET /api/v1/admin/quota-finance/archive` | Lists the archived imports, metadata only | | `GET /api/v1/admin/quota-finance/unknown-reservations` | Lists the held unknown reservations and whether each is releasable | | `POST /api/v1/admin/quota-finance/release-unknown` | Releases unknown reservations by hand, with a written reason | | `GET /api/v1/admin/quota-finance/manual-releases` | Reads the finance trail of manual releases | | `POST /api/v1/admin/quota-finance/connectors/{id}/sync` | Reads the provider's cost report for a date range now and imports what changed since the last read | ## See also - [Budgets and TPM](/docs/features/budgets-and-tpm/). - [Native billing imports](/docs/features/native-billing-imports/). - Official sources: [OpenAI Costs API](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/usage/methods/costs), [Anthropic Usage and Cost API](https://platform.claude.com/docs/en/manage-claude/usage-cost-api), [Google Cloud Billing export to BigQuery](https://docs.cloud.google.com/billing/docs/how-to/export-data-bigquery). # Provider cost connectors **Last updated:** 2026-11-22T07:30:00-03:00 (UTC-3) A cost connector reads a provider's organization cost report directly, with an administrative credential you supply, and imports it into the [financial reconciliation](/docs/features/quota-finance/) ledger. A daily reconciliation then shows, side by side, what the provider charged and what the gateway recorded for the same provider, with an explicit state for every day. Flag: `billing_connectors` (default `false`). Two sources are implemented: | Source | Report | Credential | | --- | --- | --- | | `anthropic_cost_report` | [Anthropic Cost Report](https://platform.claude.com/docs/en/api/beta/organization/cost_report/retrieve), `GET https://api.anthropic.com/v1/organizations/cost_report`, daily buckets grouped by description | An Anthropic Admin API key (`sk-ant-admin...`), sent as `x-api-key` with `anthropic-version: 2023-06-01` | | `openai_costs` | [OpenAI organization costs](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/usage/methods/costs), `GET https://api.openai.com/v1/organization/costs`, daily buckets grouped by line item | An OpenAI Admin key with read access to usage (`api.usage.read`), sent as `Authorization: Bearer` | The origin is fixed per source; it cannot be configured, redirects are not followed and no other host is called. The credential is read from its environment variable (or your [secret manager](/docs/operate/secret-managers/)) at each synchronization. It is never an inference key, never stored, never logged and never shown: the API and the console only say whether it is set. A connector is different from pasting an export with [native billing imports](/docs/features/native-billing-imports/): the paste is operator-attested, the connector fetches the report itself, pages through it completely and imports only what changed since its last read. For the same report and account you use one or the other; the gateway refuses overlapping periods between the two. ## Enable it ```yaml features: quota_management: true # syncing is a finance write durable_usage: true quota_finance: true billing_connectors: true billing_connectors: - id: anthropic-org # ^[a-z][a-z0-9_-]{1,31}$ source: anthropic_cost_report # or openai_costs admin_key_env: ANTHROPIC_ADMIN_KEY provider_id: anthropic # a configured provider; its connection fingerprint labels the lines account_id: main-org # your label for the provider organization finalization_hours: 48 # optional, 1-720; default 48 max_days: 31 # optional, 1-92; default 31 ``` | Field | Default | Meaning | | --- | --- | --- | | `id` | required | Unique connector ID. | | `source` | required | `anthropic_cost_report` or `openai_costs`. | | `admin_key_env` | required | Name of the environment variable holding the administrative key. A value that is not a variable name is refused at boot. | | `provider_id` | required | The configured provider the charges belong to, with a canonical ID (`^[a-z][a-z0-9_-]{1,63}$`). Lines carry its exact connection fingerprint. | | `account_id` | required | Your label for the provider organization, up to 128 characters. Source and account identify the ledger, so the label must not change once synchronized (a new label would import every row again), and a manual paste of the same report must use the same label to be recognized as overlapping. | | `finalization_hours` | `48` | Days that ended less than this ago are imported as provisional: the import's coverage is `partial`, and the reconciliation shows those days as `provisional`. Providers revise recent days. | | `max_days` | `31` | Longest period one synchronization may read. | Connectors are boot configuration: changing the list requires a restart. Up to 16 connectors, at most one per provider (the daily reconciliation compares one provider's report with its gateway traffic) and at most one per source and `admin_key_env`. A connector re-pointed to another `provider_id` after it synchronized is refused (`409`). The flag is an operator control; it requires `quota_finance`. ## Synchronize ```bash curl -b "$COOKIE_FILE" -H "X-CSRF-Token: $CSRF" -X POST \ -H 'Content-Type: application/json' \ -d '{"version": 12, "from": "2026-10-15", "to": "2026-11-15"}' \ http://localhost:8080/api/v1/admin/quota-finance/connectors/anthropic-org/sync ``` - `version` is the current finance version (`GET /api/v1/admin/quota-finance/report?limit=1`); a concurrent import answers `409`. - `from` and `to` are UTC dates, `to` exclusive, at most `max_days` apart and ending no later than tomorrow. - The gateway reads every page (at most 32, each at most 512 KiB), checks the cursors, the buckets (inside the period) and the currency (USD), and converts amounts exactly: Anthropic reports decimal cents, OpenAI decimal dollars; a value that is not exact at 1e-12 USD is refused, never rounded. - A row identity that repeats within one fetch, or a bucket re-sent on a later page, refuses the whole synchronization (`502 connector_invalid_report`): it is never summed. - Each report row has an identity made of its bucket and every descriptive field the provider returned (model, description, token type, tier, line item, project and so on), without its amount and quantity. What one synchronization imports, as one immutable import (source `anthropic_cost_connector` or `openai_cost_connector`): | Row | Import line | | --- | --- | | New, non-zero | `charge` (or `credit` if negative) | | Same identity, different amount | `adjustment` of the difference | | Previously reported, now absent from the complete report | `adjustment` back to zero ("withdrawn by provider") | | Unchanged | nothing | If nothing changed, the run is recorded as `no_change` and no import is created. The run keeps the SHA-256 of the fetched pages; the import's `source_sha256` binds that digest to the run, so a provider that reverts a revision still produces a distinct, traceable import. The connector's line ledger and the import commit in one transaction, so the net of all imports always equals the latest report, and no row is counted twice. A period that would change more than 1,000 lines is refused; sync a shorter period. Responses: `200` with the run (`state`, `import_id`, `new_lines`, `corrected_lines`, `withdrawn_lines`, `pages`, `rows`, `final_through`, `source_sha256`). Errors: `503 connector_credential_missing`, `502 connector_credential_rejected` (the provider refused the key; it needs read access to the cost report), `503 connector_rate_limited` (with the provider's `Retry-After`), `502 connector_unavailable`, `502 connector_invalid_report` (the report did not match its published format), `422 connector_report_too_large`, `409` version or overlap conflict. The provider's response body is never echoed. `GET /api/v1/admin/quota-finance/connectors` lists the connectors as `billing_connectors` (the YAML names: `id`, `source`, `provider_id`, `account_id`, `finalization_hours`, `max_days`; without secrets: `credential_configured` only) and their last five runs. ## Daily reconciliation `GET /api/v1/admin/quota-finance/reconciliation?provider_id=anthropic&from=2026-10-15&to=2026-11-15` (at most 92 days) returns one row per UTC day: | Field | Meaning | | --- | --- | | `provider_charged_usd` | Net of connector lines whose bucket starts that day; `null` when nothing was imported | | `gateway_requests`, `gateway_estimated_usd` | Usage events of that provider and day, and the sum of their **known** valuations: an estimate priced from the price book, with discounts and margins, frozen in each request | | `gateway_not_fully_valued` | Events whose valuation is partial, unknown or missing: their cost is not in the estimate | | `ledger_settled_usd`, `ledger_unknown_reservations` | Budget reservations of that provider and day: settled amounts at the approved rates captured at admission (the budget charge) and reservations still unknown | | `state` | See below | | `difference_usd` | Provider minus gateway estimate, only on `comparable` days | States, decided in this order: | State | Meaning | | --- | --- | | `not_imported` | No connector run covered the day | | `provisional` | Covered, but the day is inside `finalization_hours`: the provider may still revise it | | `incomplete` | Some gateway request of the day has no known cost, or a reservation is still unknown | | `provider_only` | The provider charged, the gateway recorded nothing: traffic outside this gateway (another application, a coding tool, the provider console) | | `gateway_only` | The gateway recorded traffic, the provider charged nothing: a different account, a free tier or a report gap | | `no_activity` | Neither side has anything | | `comparable` | Both sides complete; `difference_usd` is shown | `coverage` counts days per state. A comparable difference is evidence to investigate, not a correction: imports never change budget balances (see [releasing USD with a charge](/docs/features/quota-finance/#releasing-usd-with-a-charge) for the explicit, per-request path). ## Console **Budget & TPM → Finance & reconciliation → Provider cost connectors** lists the connectors and their runs, synchronizes a chosen period (global administrator) and shows the daily reconciliation with its coverage. ## Who can Reading needs global `quotas:read`; synchronizing needs a global administrator with `quotas:manage`, `quota_management`, CSRF and same origin, and is audited (`quota.billing.import` when lines are imported, `quota.billing.connector_sync` otherwise). Team roles see nothing. ## Limits and upgrade notes - The reports are aggregates: no line names a gateway inference, so connector lines never release a held reservation. - Amounts are what the provider's report says, not an invoice: credits, taxes and invoice adjustments may differ. - Anthropic usage billed through other products (for example a subscription plan) may not appear in the API organization's report. - Other sources are added as new fixed sources with their own parser, never as a configurable URL. Further provider cost reports and coding-tool usage feeds are designed for and not implemented here. - **Upgrade.** Migration 148 creates the connector line ledger and run history. Upgrade every replica before enabling the flag. # Optimization insights **Last updated:** 2026-11-21T09:54:10-03:00 (UTC-3) Optimization insights explain what the gateway's cost features did and where more could be saved, with evidence you can check: the sample, the window, the exact approved rate revision behind every dollar, and why a comparison is or is not valid. Flag: `optimization_insights` (default `false`). They complement the [cost optimization panel](/docs/features/exact-cache/) (savings at today's catalog price) with [approved rates](/docs/features/budgets-and-tpm/#approved-rates) in exact decimal arithmetic and immutable baselines. Every request is priced with the rules that value a single request: the service tier the provider reported, the long-context tier when its input is above the threshold, and cache reads and five-minute and one-hour cache writes at their own prices (see [pricing rules](#pricing-rules)). Nothing here changes a policy, and no figure is a guaranteed or causal saving: these are estimates from approved rates, not provider charges. Provider charges are compared in [provider cost connectors](/docs/features/billing-connectors/). ## Enable it ```yaml features: usage_analytics: true # required optimization_insights: true quotas: rates: # approved rates value the effects - provider_id: openai model: gpt-4.1-mini connection: "" input_usd_per_million: "0.40" output_usd_per_million: "1.60" cache_read_usd_per_million: "0.10" # needed for prompt-cache effects cache_write_usd_per_million: "0.50" # optional: five-minute writes cache_write_1h_usd_per_million: "0.80" # optional: one-hour writes long_context: # optional: the whole request above the threshold threshold_tokens: 200000 input_usd_per_million: "0.80" output_usd_per_million: "3.20" cache_read_usd_per_million: "0.20" service_tiers: # optional: tiers the provider may report priority: {input_usd_per_million: "0.70", output_usd_per_million: "2.80", cache_read_usd_per_million: "0.18"} revision: rev-1 ``` The flag is an operator control, applies at runtime and needs PostgreSQL (migration 148 creates `gateway_optimization_baselines`; migration 149 adds the cache counters described below). A model is valued only when its alias has one target and an approved rate for that exact provider, model and connection; otherwise its requests are counted as unpriced, never as zero. Cache writes are known only for requests that `usage_valuation` priced from the answer's own split. ## Pricing rules Each request is priced in one price set, chosen as for a single request: | Rule | Behavior | | --- | --- | | Service tier | The tier the provider reported (`service_tier` of the answer) selects that tier's approved prices from `service_tiers`. No tier, `default` or `auto` is the standard price. A tier the rate does not approve leaves the request **unpriced**; it is never valued at the standard price. So is a request that asked for a tier its answer did not report (valuation reason `service_tier_unreported`): it is grouped as tier `(unreported)`, which no rate prices. | | Long context | A request whose input (cache reads and writes included) is **strictly above** `long_context.threshold_tokens` is priced entirely at the long-context prices: input, output, cache reads and writes. At the threshold the standard prices apply. An approved service tier has no long-context price of its own, so a tiered request above the threshold is unpriced, as quota settlement decides it. | | Cache reads and writes | Reads at `cache_read_usd_per_million`, five-minute writes at `cache_write_usd_per_million` and one-hour writes at `cache_write_1h_usd_per_million`, in the selected price set. A category with tokens and no price is unpriced, never valued as plain input. | From migration 149 on, usage events record the measured split: `measured_input_tokens` (every input token, cache included, which some dialects leave out of `input_tokens`), `cache_read_tokens`, `cache_write_tokens` (five-minute) and `cache_write_1h_tokens`. The split is recorded only when the valuation priced the request from it (`known`, `text_token_estimate`); a measurement the valuation refused, for example because the answer omitted a cache counter the price requires (`cache_usage_unreported`), proves no zero. They are nullable: older events, and requests without a proven split, keep NULL, which means unknown. When the price set publishes a cache-write price, a served request with unknown writes is counted in `cache_write_unknown_requests` and left out of the prompt-cache value, never assumed to have written nothing; when it publishes none, unknown writes are treated as none, as the rate bills them. Without a known split the side of the threshold is read from `input_tokens`, which some dialects count without the cache reads: when the threshold lies between `input_tokens` and `input_tokens` plus the reported cache reads, the side is unknown and the request is unpriced at that rate (for the served model, or for the routing candidate). Requests are aggregated in SQL by model, route, reported tier, the side of each rate's threshold (for the served model and, for a routed request, for the routing candidate) and whether the split is known. The rows stay bounded, and every request of a row has the same prices. ## Measured effects `GET /api/v1/admin/optimization?from=...&to=...&team=...&baseline_id=...` (RFC 3339, at most 92 days, default the last 30; `team` filters before aggregation) reads successful usage events and returns one row per effect: | Effect | What is measured | Valued as | | --- | --- | --- | | `gateway_cache` | Answers served by the [exact or semantic cache](/docs/features/exact-cache/), which made no provider call | The stored answer's input and output tokens at the model's rate, in the long-context tier when the avoided input is above the threshold | | `provider_prompt_cache` | Provider-reported cache reads and writes on served requests | **Net**: cache-read tokens × (input price − cache-read price), minus the write premium, five-minute writes × (write price − input price) plus one-hour writes × (one-hour write price − input price), in the request's price set. `gross_savings_usd` and `write_premium_usd` give the two parts; the net is negative when writes outweigh reads | | `auto_routing` | Served requests of a routed alias | Input and output tokens at the most expensive candidate's price minus the served model's price, at full price, each in the request's reported tier and in its own long-context tier | | `prompt_compression` | `not_measured` | The removed bytes are not recorded per request; no effect is claimed | | `reasoning_control` | `not_measured` | Avoided reasoning tokens are not observable; no effect is claimed | Each request belongs to one class: a cache hit is never also a prompt-cache or routing saving, and a served routed request splits exactly into its routing difference plus its net prompt-cache difference, so the effects add up without double counting. `unpriced_requests` counts requests whose rate, tier or long-context price (or the routing candidate's) is missing or whose cache category has no price, cache hits whose stored answer had no usage, and rows reporting more cache tokens than input; they are excluded from `estimated_usd`. `cache_write_unknown_requests` (prompt-cache effect only) counts every served request whose writes are unknown while the price set prices writes, with or without cache reads, so it can exceed the effect's `requests`; those with reads are in `requests` and excluded from the value. Routing effects do not measure answer quality. Use [evaluations](/docs/features/evals/) before relying on a cheaper model. ## Baselines A baseline freezes a window's usage per model, reported tier, long-context side and cache reads and writes, together with the approved rates in force when it was captured (body `version` 2). It cannot be updated, deleted or truncated, and its fingerprint covers its name, team, window and body. Baselines captured before this version (no body `version`, reported as `body_version` 1) still load and verify unchanged. They recorded no tier, long-context side or cache writes, so their rows are valued only at a frozen rate that approves no service tier, long-context tier or cache-write price; at any other rate their models are `unpriced`. At such a rate a legacy row's tier is assumed standard, as the release that captured it valued it. Capture a new baseline to compare with tiers, long context and writes. ```bash curl -b "$COOKIE_FILE" -H "X-CSRF-Token: $CSRF" -X POST -H 'Content-Type: application/json' \ -d '{"name":"before prompt caching","from":"2026-10-01T00:00:00Z","to":"2026-10-31T00:00:00Z"}' \ http://localhost:8080/api/v1/admin/optimization/baselines ``` | Field | Rules | | --- | --- | | `name` | 1-120 characters | | `from`, `to` | RFC 3339, `from` before `to`, at most 92 days | | `team` | Optional team ID; a report compared with this baseline must use the same team | `GET /api/v1/admin/optimization/baselines` lists the last 100 (`id`, `name`, `team`, window, `fingerprint`, `created_at`). With `baseline_id`, the window must not overlap the baseline's window (`400 window_overlaps_baseline`), and the report values **both** windows at the baseline's rates, so a later price change never shows up as a saving, and adds one row per model: | `state` | Meaning | | --- | --- | | `comparable` | Both windows have at least 50 served requests, priced, with mean input and output tokens per request within ±50%: `baseline_estimated_usd_per_request` and `window_estimated_usd_per_request` are shown | | `insufficient_sample` | Fewer than 50 served requests in either window | | `workload_changed` | The mean prompt or answer length moved by more than half: the workload differs and costs are not compared | | `incomplete` | Some served request in either window has no reported token count, reports more cache tokens than input, or has unknown cache writes while the rate prices writes: it would lower the means and the cost per request without a real saving | | `truncated` | Either side hit the 2,000-row bound | | `unpriced` | No approved rate in the baseline, or some request's tier, long-context price or cache category has no approved price | | `no_baseline` | No baseline selected | Cost per request includes cache hits at zero provider cost, so it reflects all effects together; served requests are priced with their tier, long-context tier, cache reads and writes. `reconciled` explains why the model's figure is not reconciled with provider charges: provider reports are organization-wide, not per model. Compare per day and provider in [the reconciliation](/docs/features/billing-connectors/#daily-reconciliation). ## Recommendations `recommendations` lists advisory opportunities, each with its `sample_requests`, `confidence` (`low` from 50 served requests, `medium` from 200), `basis` (which rates), `ceiling_usd`, `prerequisites` and `caveats`. The response always carries `applies_changes: false`. | Kind | When | Ceiling | | --- | --- | --- | | `prompt_cache_underused` | Every served request's price set has a cache-read price, at least 50 served requests, at least 1,024 input tokens per request on average and under 10% of input read from cache | Every input token not already read from or written to the cache valued at the cache-read price instead of the input price, in each request's tier and long-context tier: an upper bound, not an expectation, and without the write premium that filling the cache costs | ## Console **Budget & TPM → Finance & reconciliation → Optimization insights** shows the effects (with the prompt cache's read savings, write premium and unknown writes), the per-model comparison against a selected baseline and the recommendations. A global administrator can capture a baseline of the 30 days before the default 30-day window, so the two never overlap. The panel lists gateway-wide baselines; team-scoped baselines are used through the API. ## Who can Reading needs global `quotas:read`; capturing a baseline needs a global administrator with `quotas:manage`, CSRF and same origin, and is audited (`optimization.baseline.create`). Team roles are refused. Responses are `no-store`. ## Limits - Successful requests only; tokens the provider did not report are left out of the sums. - At most 2,000 aggregated rows per window (`truncated` says when more exist; figures are then a lower bound). - Approved rates carry no discount or margin, so none is applied. - **Upgrade.** Migration 148 creates the baseline table. Migration 149 adds four nullable columns to `gateway_usage_events` with no default, and a check added `NOT VALID`, so the table is neither rewritten nor scanned; existing events keep NULL (unknown). Upgrade every replica before relying on cache-write figures: an older replica records no split, which counts as unknown. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `GET /api/v1/admin/savings` | What the gateway cache, provider prompt caching and the auto-router saved across every key, or one team's, with the top ten keys | | `POST /api/v1/admin/optimization/baselines` | Freezes a window's usage and approved rates as a baseline later windows are compared with | # Native billing imports **Last updated:** 2026-10-28T13:54:53-03:00 (UTC-3) Compare what the gateway estimated with what the provider charged. You export the cost report from OpenAI, Anthropic or Google Cloud Billing, paste it into the console, and the gateway normalizes it and adds it to the [financial report](/docs/features/quota-finance/#report). It is part of the `quota_finance` flag. A published price and a cost report are different things: the first is a reference rate; the second is what was accounted to your account over a period. ## Accepted sources | Source | What to paste | Caveats | | --- | --- | --- | | [OpenAI Costs](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/usage/methods/costs) | The pages (`object: page`) with the buckets and the pagination | `amount.value` in USD; a missing amount does not become zero. Requires an OpenAI administrative credential | | [Anthropic Cost Report](https://platform.claude.com/docs/en/api/beta/organization/cost_report/retrieve) | The pages with the `starting_at`/`ending_at` buckets | `amount` comes in **cents**, including fractional cents; the gateway divides by 100 exactly | | [Google Cloud Billing](https://docs.cloud.google.com/billing/docs/how-to/export-data-bigquery-tables/detailed-usage) | The selected rows from the BigQuery detailed export | USD and the declared account only. Credits, taxes and adjustments stay separate. Filter first: the export includes every GCP service, not just Gemini | The gateway does not go to the network to import and does not use inference keys to call billing APIs: you provide the export. ## How to use it 1. In the console, as a global admin: **Budget & TPM → Finance & reconciliation → Provider cost exports**. 2. Start a draft and paste the statement with the export's pages. 3. The result updates the report. Through the API, `POST /api/v1/admin/quota-finance/import-native`: ```json { "version": 0, "statement": { "id": "openai_costs_october", "source": "openai_costs", "account_id": "operator_selected_account", "provider_id": "configured_provider_id", "connection": "COPY_THE_64_HEX_CONNECTION_FINGERPRINT", "period_start": "2026-10-01T00:00:00Z", "period_end": "2026-10-02T00:00:00Z", "coverage": "partial", "pages": [] } } ``` This is a **template**: replace the version, account, connection, period and pages with the real data. The connection hash comes from `GET /api/v1/admin/quota-policies`. In the console, **API reference** generates the complete `curl` with login, CSRF and the current version. Never put keys or tokens in the export. ## Validation rules - Up to 32 pages, 1,000 rows and 512 KiB. - Buckets within the declared UTC period, of up to 366 days. - Complete pages, in order, with no repeated cursor; the last one with `has_more: false`. - Rejected: partial pages, unknown currency, missing amount, duplicates and repeated JSON fields. - Values with up to 12 decimal places, in exact arithmetic, with no float and no silent rounding. - Use an exact decimal export from BigQuery, without rounding in the browser. The invoice month and the usage period can differ because of late entries. ## Immutable, with no double counting - Repeating the same import does not add it again. - A revised export with an overlapping period is rejected. There is no flow yet to replace a revised invoice; record only the difference as an adjustment. - Keep the original export outside the gateway according to your company's policy; the gateway stores the normalized version and the hashes. ## Limits - **Aggregated rows.** None of these reports carries the ID of the gateway's inferences, so the rows stay aggregated: they do not get made-up IDs and **do not release** stuck **reservations**. For that, see [reconciliation by metering or charge](/docs/features/quota-finance/). - **Unverified coverage.** The origin is marked as `operator_attested_export`. `complete_export` describes your selection, not a certification of the invoice. - An aggregated report does not prove that no work happened. - Global viewers and operators read the reports, without importing or reconciling. Team roles do not see financial data. ## See also - [Financial reconciliation](/docs/features/quota-finance/). - [Budgets and TPM](/docs/features/budgets-and-tpm/). # Video with a budget (Runway) **Last updated:** 2026-11-20T17:29:10-03:00 (UTC-3) Generating video takes minutes and is billed per second. With `quota_video`, the gateway also enforces budgets on asynchronous video generation with **Runway Gen-4.5** (text to video): each job is recorded before it is sent, is never resent by accident, and stays tied to the key and team that created it. Without the flag, video routes to other providers keep working as passthrough, with no budget; an alias with a Runway target is refused with `404 feature_disabled` ("Runway video jobs require quota_video") before any call, because Runway jobs are only served with this lifecycle. ## How to enable it ```yaml features: video_generation: true durable_usage: true budget_limits: true quota_media: true # requires budget_limits or tpm_limits quota_video: true # requires quota_media, durable_usage and video_generation providers: - id: runway protocol: runway base_url: https://api.dev.runwayml.com/v1 api_version: "2024-11-06" models: - id: video-runway capabilities: [video] targets: - {provider: runway, model: gen4.5, paths: {video: /text_to_video}} quotas: rates: - provider_id: runway model: gen4.5 connection: "" unit: video_second variant: runway_gen45_mp4 unit_usd: "0.12" revision: rev-1 ``` - The Runway key goes in a Secret or an encrypted override; the client's key never reaches Runway. - The alias has only the `video` capability, a single `gen4.5` target, no cache and no retry. - The client key needs the `route:video` scope. - `gateway validate` checks the configuration before you restart. **Reference price:** Runway's official price table lists 12 credits per second for Gen-4.5, at $0.01 per credit, before taxes. You approve the rate according to your contract. The estimated [valuation](/docs/features/usage-valuation/) uses the per-second price from the community cost map; the quota's approved rate is separate. ## How to use it **Create** a job: ```bash curl http://localhost:8080/v1/videos/generations \ -H "Authorization: Bearer $GATEWAY_API_KEY" \ -H 'Content-Type: application/json' \ -H "Idempotency-Key: $(uuidgen)" \ -d '{"model": "video-runway", "promptText": "A cyan robot waving", "ratio": "1280:720", "duration": 2}' ``` | Field | Values | | --- | --- | | `promptText` | 1 to 1,000 characters | | `ratio` | `1280:720` or `720:1280` | | `duration` | 2 to 10 seconds | | `seed` | optional, unsigned 32-bit integer | | `outputFormat` | optional, `mp4` | The response is `202`, with the job ID in `X-Gateway-Video-Job`. **Track it:** | Endpoint | What it does | | --- | --- | | `GET /v1/video-jobs?limit=25&offset=0` | Lists the key's and team's jobs (limit 1 to 50) | | `GET /v1/video-jobs/{id}` | Last known state, without calling Runway | | `POST /v1/video-jobs/{id}/refresh` with `{version}` | Queries Runway now; at most once every 5 s | | `DELETE /v1/video-jobs/{id}` with `{version}` | Cancels a pending job or deletes the finished video at Runway | The job goes through `queued`, `running` and `succeeded`. The `refresh` that observes completion returns the MP4 link in `outputs`. **The gateway does not store that link** (it is a signed URL that expires): save the video before it expires. A new `refresh` fetches the link again. In the console: **Budget & TPM → Video jobs**. The screen asks for the inference key, which stays only in the page's memory. Opening the screen does not call Runway; list, create, refresh and cancel are separate buttons. ## Idempotency and safety - **`Idempotency-Key` is required** (16 to 128 URL-safe characters). Repeating with the same key returns the same job; changing the content with the same key returns `409`. - **There is never an automatic resend.** A timeout, restart or lost response does not create another job. A job can stay `submitting` or `unknown` without a Runway ID; it keeps its reservation until it is proven and does not authorize recreating it. - **Job owner:** the authenticated key and team. No client field chooses the owner. Every action checks the scope, model, key and team again; a revoked key or a removed team loses access. - The job stores the connection, model, seconds, reservation, request ID and trace ID. It does not store the prompt, media, signed URL or any secret. ## Budget and settlement - The reservation is in **seconds of video**, not tokens. An applicable TPM policy refuses the job rather than converting seconds into tokens. - Only a `SUCCEEDED` response from Runway, with the right ID and exactly one valid HTTPS link, proves completion. The reservation is then settled for the requested seconds. - Failure, cancellation, an invalid response or a network error **do not return balance on assumption**: the reservation is left for [financial reconciliation](/docs/features/quota-finance/). A `204` or `404` on cancellation does not prove there was no charge. - Deleting a finished video keeps the measurement and the charge. ## Real example With a real Runway account: a 2 s job at 1280:720 returned `202`; four `refresh` calls, every 10 s, went through `queued`, `running` and `succeeded` in about 55 s, and the last one returned the MP4 link (925 KB). By the public price table, 24 credits ($0.24). ## Limits - Runway Gen-4.5 only, text to video, MP4. Reference images, audio and other models need a different profile. - No automatic polling: tracking is done with `refresh`. - Maximum time: 30 s to create, 20 s per query, status response up to 64 KiB. - Sora (OpenAI) and Veo (Gemini) are not in the profile: [OpenAI announced](https://developers.openai.com/api/reference/resources/videos/methods/create) the shutdown of Sora on 2026-09-24, and [Google](https://ai.google.dev/gemini-api/docs/video) the shutdown of the Veo previews on 2026-10-22. ## See also - [Budgets and TPM](/docs/features/budgets-and-tpm/) and [protected profiles](/docs/features/quota-protocols/). - Runway: [API](https://docs.dev.runwayml.com/api/), [parameters](https://docs.dev.runwayml.com/assets/inputs/), [pricing](https://docs.dev.runwayml.com/guides/pricing/). # Manual price book **Last updated:** 2026-11-23T10:59:54-03:00 (UTC-3) [Automatic pricing](/docs/features/automatic-pricing/) covers most models. For the rest, such as an open source model on a provider that does not publish a price, or a contract with its own rate, you record the price by hand in the price book. A manual entry is an explicit value, so it wins over the automatic price for the model it names. Flag: `manual_price_catalog`. ## How to use it ```yaml features: manual_price_catalog: true price_book: - provider_id: deepinfra model_id: lab/open-model input_per_million: "0.10" output_per_million: "0.35" effective_from: "2026-10-23T00:00:00Z" source_url: https://deepinfra.com/models/lab/open-model ``` The numbers are only an example: use the values verified on the provider's page. | Field | Rule | | --- | --- | | `provider_id` + `model_id` | The provider connection and the exact upstream ID. The same model on DeepInfra, OpenRouter and Groq has different entries | | `input_per_million`, `output_per_million` | USD per million text tokens, a decimal as a string, not negative | | `effective_from` | RFC3339 date from which the rate applies; a future rate does not apply before then | | `source_url` | Public HTTPS, without credentials, query or fragment | An entry may add `service_tiers` (`priority`, `flex`, `batch`), each with `input_per_million` and `output_per_million` and optional `cache_read_per_million` and `cache_write_per_million`. A tier price wins over the catalog's price for that tier; a tier the entry leaves out keeps the catalog's price. See [service-tier pricing](/docs/features/service-tier-pricing/). ## Media models no catalog prices Some media models are in no catalog. The community cost map lists only Replicate's chat models, for example, and none of the Replicate image models the gateway serves on `/v1/images/generations`. For such a model, an entry may carry one media unit price instead of text rates: ```yaml price_book: - provider_id: replicate model_id: black-forest-labs/flux-schnell unit: per_image unit_price: "0.003" effective_from: "2026-01-01T00:00:00Z" source_url: https://replicate.com/black-forest-labs/flux-schnell ``` The price is only an example: check it on the model's page. | Field | Rule | | --- | --- | | `unit` | `per_image` (images returned), `per_character` (characters spoken), `per_audio_second` (seconds transcribed) or `per_video_second` (seconds rendered) | | `unit_price` | USD per unit, a decimal as a string, not negative, at most 9 decimal places | A media entry has no `input_per_million`, `output_per_million` or `service_tiers`; the gateway rejects an entry that mixes them, a `unit_price` without a `unit` and any other unit. The entry prices only an alias that serves that media capability alone (`capabilities: [images]` for `per_image`), never a text alias of the same model, and never in another unit. It wins over a catalog that publishes the unit, or token prices, for that model. Valuation counts the units from the answer, as for a catalog price: the images in `data[]` and the seconds a transcription reports. Without a count the cost stays unknown, never zero. An explicit `unit_price: "0"` is accepted, as for text rates, and values the model at zero: write it only when the provider publishes the model as free. Before saving a media entry from the console, upgrade every replica: an older version cannot read it. Price only a model billed per unit: a Replicate model billed by hardware time has no per-image price, so leave it without an entry and its cost stays unknown. The gateway rejects negative or non-numeric rates, duplicate entries and more than 10,000 rows. An entry can exist before the connection, but it creates neither a provider nor an alias. The YAML is validated even with the flag off. In the console, global admin and viewer see the list in **Settings & sources**. To edit from the console, with history, turn on [price book management](/docs/features/price-book-management/). ## When the manual price is used - **Whenever an entry is in effect** for that connection and model (`effective_from` reached, `manual_price_catalog` on). It wins over every automatic price for what it prices: the catalogs, an approved [catalog review](/docs/features/catalog-review/) rate and a provider's documented free tier. Without an entry, the automatic price applies as before. - What it prices, it prices whole: text-token rates (with the tiers it names), or one media unit. The catalog's cache, media-token and long-context prices for that model are not mixed into a manual text rate, so cached or media tokens it does not price stay unknown. - The response identifies `source: manual` and `manual_fallback: true` (the field keeps its original name). When an automatic price was available and the entry replaced it, it also says `override: true`, and the catalogs' votes stay listed. A conflict between catalogs is not an override: no automatic price was available. - With [valuation](/docs/features/usage-valuation/) on, the manual price goes into the per-event estimate, frozen at the time of the call, with the same `source`, `manual_fallback` and `override`; with the [span store](/docs/features/traces/), the request and attempt spans carry `price.source: manual` and, for an override, `price.override: true`. Changing the YAML later does not reprice the past. - To go back to the automatic price for a model, remove its entry. An entry effective in the future changes nothing until its date. - The manual price is a reference: the `cost` [routing strategy](/docs/features/routing-strategies/) ranks targets by the price that wins, but [budgets](/docs/features/budgets-and-tpm/) use separate approved rates. ## Good practices 1. Check the upstream ID, unit, currency and effective period on the provider's official page. 2. Record the link and the rate in a code review. 3. Run `gateway validate` before applying. 4. Do not copy one provider's rate to another: the same model costs differently at each intermediary. The community cost map helps you discover prices, but it does not prove the rate contracted for your account. ## Upgrade notes Earlier versions used a manual entry only where no automatic price was available; now an entry in effect wins. Deployments that relied on manual entries only as gap-fillers should remove the entries they no longer want to win before upgrading. ## Limits - One unit per entry: text-token rates, or one media unit price. Token-priced image models such as GPT Image are priced by the [automatic catalog](/docs/features/automatic-pricing/#media). - It is neither an invoice nor a ledger. The real invoice comes in through [billing imports](/docs/features/native-billing-imports/). ## See also - [Automatic pricing](/docs/features/automatic-pricing/). - [Price book management](/docs/features/price-book-management/). # Price book management **Last updated:** 2026-11-23T10:59:54-03:00 (UTC-3) Edit the [manual price book](/docs/features/pricing/) from the console or the API, with a revision history and a revert to the YAML at any time. Flag: `price_book_management`, which requires `manual_price_catalog`, the UI and PostgreSQL. ## How it works The YAML `price_book` is the baseline. Saving from the console writes an **override** of the YAML book to PostgreSQL, which takes precedence over the YAML until it is removed. The book in effect, YAML or override, wins over the automatic catalogs for every model it prices ([when the manual price is used](/docs/features/pricing/#when-the-manual-price-is-used)); remove an entry to return that model to its [automatic price](/docs/features/automatic-pricing/). Each save becomes a revision in the history. The rules for each rate are the same as in the YAML: connection + exact upstream ID, USD per million text tokens as a decimal, RFC3339 effective date and an HTTPS source. Missing is not zero: a model without an entry keeps its automatic price, or stays unknown. ## How to use it **In the console:** **Settings & sources**. The editor has one field per rate, 20 per page, adding, removing, saving everything at once and **Revert to YAML**. - **Prepare revision** only fills in a draft; nothing changes until you save. - If someone saved before you, your draft is kept for review. **Reload** discards it and shows the current state. **Through the API:** | Endpoint | What it does | | --- | --- | | `GET /api/v1/admin/price-book` | Version, source (YAML or override) and the rates in effect | | `PUT /api/v1/admin/price-book` | Replaces the whole book: `{version, prices}`, up to 4 MiB and 10,000 rates. An empty list is an empty override | | `DELETE /api/v1/admin/price-book` | `{version}`; reverts to the YAML. Different from saving an empty list | | `GET /api/v1/admin/price-book/history` | Revisions, paginated by `before_version` and `limit` (1 to 100) | | `GET /api/v1/admin/price-book/history/{version}` | The book as it was at that revision | - **Who can:** the global admin edits (`prices:manage`); global admins and viewers read (`prices:read`). Operators and team roles cannot see it. - Writes require a same-origin session, CSRF and the `version` that was read, and are recorded in the audit log with the actor and the request ID. - An unavailable database blocks reading and editing; inference continues with the last valid configuration. ## History - The history only grows: there is no API to edit or delete revisions. - Numbering follows the global configuration version and can have gaps. - A revert's revision stores the YAML at that moment. Later changes to the YAML or the automatic catalogs do not enter the history. - A database administrator can still change the data: the history is not tamper-proof storage. ## Limits - Turning off `price_book_management` does not delete revisions or the saved override; whether the manual price is used is decided by `manual_price_catalog`. - Reference price: it does not generate spend, budget or invoices, and it does not reprice past events. - When you go back to a gateway version without this management, the overrides are ignored and the YAML applies. Before that, copy the rates you want to keep into the YAML. ## See also - [Manual price book](/docs/features/pricing/). - [Automatic pricing](/docs/features/automatic-pricing/). - [Configuration parity](/docs/reference/configuration-parity/). ## Price data versus parameter defaults A price-book entry is identified advisory data with an effective date, model/provider identity and source. It has no fabricated global price default. Shared [parameter definitions](/docs/reference/parameter-registry/) preserve its existing numeric and reference validation without approving enforcement prices, changing historical events or authorizing a model capability. The managed writer retains its version, audit and whole-snapshot checks. # Catalog review and price archive **Last updated:** 2026-11-23T10:59:54-03:00 (UTC-3) With `catalog_review`, nothing the gateway reads from a public catalog or a provider's model list takes effect by itself. You import a catalog as a **draft**, review the diff (new, changed and removed models and prices) and approve it, whole or entry by entry. Only approved prices value usage and feed cost routing, and only approved models are served through a [wildcard alias](/docs/features/access-control/). Approved prices go to an **append-only archive** with an effective date: a new price never edits the old one, and the old one is archived automatically with its effective window. ## How to turn it on ```yaml features: external_model_catalog: true automatic_price_catalog: true price_source_modelsdev: true # or price_source_cost_map, for those sources catalog_review: true # off by default; requires PostgreSQL ``` `catalog_review` requires `automatic_price_catalog` and a database (migration 183). It is an operator flag and can be switched in the console under **Settings & sources**. What changes when it is on: - [Automatic pricing](/docs/features/automatic-pricing/) no longer applies the catalogs' vote. A target with an approved price shows `source: catalog_review`, `confidence: approved` and its `effective_from`; without one it is `unknown` with `reason: price_not_approved`. Unknown is never zero. - The [manual price book](/docs/features/pricing/) wins over an approved rate, as over any automatic price, and prices a target without one; a provider whose own documentation says it is free keeps that price (it is compiled data, not an import) unless a manual entry names the model. - Drafts carry text rates (USD per million input and output tokens). Media unit prices from catalogs are not imported, so a media alias is priced by the manual price book while the flag is on. - A model reached through a wildcard alias such as `groq/*` is served, and listed by `GET /v1/models`, only when that exact model is approved for its connection. Declared aliases need no approval: you wrote them. With the flag off, the archive and drafts stay in the database and nothing reads them. ## Review a draft in the console **Settings & sources → Catalog review**: 1. Choose a source: models.dev, the community cost map, OpenRouter, DeepInfra, or **Model list of** a connection. 2. **Import as draft**. The draft shows every change against the latest approved row: the previous and new USD per million input/output tokens, `removed` (the price becomes unpriced, or the model stops being routable) and `new`. 3. Select entries and **Approve selected** or **Reject selected**, or decide all at once. Leave **Effective from** empty to apply now, or choose a later date to schedule the price. 4. **Price archive** lists every approved row, newest first, with its window and state: `current`, `scheduled` or `archived`. A viewer (`prices:read`) can read drafts and the archive; only a global admin (`prices:manage`) imports and decides. Catalog approval is gateway-wide: an organization admin cannot import or approve. ## API | Endpoint | What it does | | --- | --- | | `POST /api/v1/admin/catalog/drafts` | `{"source": "modelsdev"}`, `cost_map`, `openrouter`, `deepinfra` or `provider:`. Reads the source now and stores the diff. `201` with the draft; a draft with nothing to change is closed at once | | `GET /api/v1/admin/catalog/drafts` | Drafts, newest first (`limit` 1 to 100, `before` a draft ID) | | `GET /api/v1/admin/catalog/drafts/{id}` | One draft with every entry and its decision | | `POST /api/v1/admin/catalog/drafts/{id}/decisions` | `{"approve": [1, 3], "reject": [2], "effective_from": "2026-12-01T00:00:00Z"}`, or `{"approve_all": true}` / `{"reject_all": true}` | | `GET /api/v1/admin/catalog/archive` | The archive, newest first, with `effective_to` and `state` (`provider_id`, `model_id`, `before`, `limit` 1 to 200) | Writes need a same-origin session and CSRF. A decision is atomic: if one entry fails, nothing applies. | Answer | Meaning | | --- | --- | | `409 draft_closed` | The draft is closed, or a newer import of the same source superseded it | | `409 entry_decided` | The entry was already approved, rejected or superseded | | `409 entry_stale` | The archive row the diff was compared against has changed since; import again | | `422 invalid_effective_from` | The date is in the past (more than one minute), or before a scheduled row of the same target | | `422 source_not_used` | No connection reads that catalog; turn on its price source first | | `422 draft_too_large` | More than 5,000 changes in one import | A draft entry looks like this: ```json { "entry": 1, "kind": "price", "change": "changed", "provider_id": "openai", "model_id": "gpt-4.1-mini", "previous_input_per_million": "0.4", "previous_output_per_million": "1.6", "input_per_million": "0.6", "output_per_million": "2.4", "decision": "pending" } ``` ## What a draft contains - **A catalog source** compares its text rates for every exact target that reads it (the connection's [price sources](/docs/features/automatic-pricing/#where-the-price-comes-from)), plus the models approved behind a wildcard on that connection. `new` is a target without an approved price, `changed` a different rate (compared exactly as decimals), `removed` a target whose approved price came from this source and that the source no longer prices. - **A connection's model list** (`provider:`) compares the active models the provider lists with the models approved for that connection. Identifiers must be valid wildcard suffixes; no pattern is ever approved, only exact models. Importing a source again while one of its drafts is open supersedes the older draft: its pending entries can no longer be approved, so an old diff never lands over a newer one. ## The archive - Rows are append-only. A database trigger refuses `UPDATE` and `DELETE` on `gateway_catalog_archive`; there is no API to edit or delete a row. - A row is in effect from its `effective_from` until the next row of the same connection and model, which archives it with that window. Retiring a price appends a `price_retired` row: the target is unpriced from then on, never free. - No backdating: an approval takes effect now or later, so a past event keeps the rate it was valued at. Every usage event already freezes the rate it used. - Approvals move the configuration version, so every replica reloads the archive. A row the database clock had reached when a replica read the archive is in effect there at once, even if that replica's clock is behind. A scheduled row takes effect on each replica by that replica's clock, without another reload; keep replica and database clocks synchronized (NTP), since a clock that is off by a few seconds applies a scheduled row that much early or late. - Every import, supersession, approval and rejection is recorded in the control audit (`catalog_draft.create`, `catalog_draft.supersede`, `catalog_draft.approve`, `catalog_draft.reject`) with the actor and the request ID. ## Limits and upgrade notes - One import reads the source once, through the same 15-minute catalog cache as automatic pricing; a failed read imports nothing. - An older binary ignores the archive and applies the catalogs' vote again: turn the flag off before rolling back. - The archive is not tamper-proof storage: a database owner can still change it. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `POST /api/v1/admin/catalog/drafts/{id}/decisions` | Approves or rejects the pending entries of a draft, all or by number, in one audited change | ## See also - [Automatic pricing](/docs/features/automatic-pricing/) · [Manual price book](/docs/features/pricing/) · [Price book management](/docs/features/price-book-management/) · [Usage valuation](/docs/features/usage-valuation/) # Access and governance **Last updated:** 2026-11-24T12:24:59-03:00 (UTC-3) Every app needs its own credential, every team its own ceiling, and every change an author. The gateway separates who calls the API (virtual keys) from who administers it (console users), and both are governed by teams and organizations. ## What exists | Feature | What it does | Flag | Learn more | |---|---|---|---| | **Virtual keys** | Per-app credential, with team, models, route scopes, expiration, and revocation | `identity_management` | [Access control](/docs/features/access-control/) | | **Zero-downtime rotation** | A new key coexists with the old one until the switch | `key_rotation` | [Rotation](/docs/features/key-rotation/) | | **Teams and team policy** | The model and route ceiling for all of a team's keys | `team_management`, `team_policy_enforcement` | [Access control](/docs/features/access-control/) | | **Organizations** | Group teams under a model ceiling | `organizations` | [Organizations](/docs/features/organizations/) | | **Access groups** | Reusable sets of models (`group:`) | `access_groups` | [Access control](/docs/features/access-control/) | | **Users and roles** | Named users with global or per-team roles; invitations and bulk import | `console_users`, `granular_rbac`, `user_invitations` | [Access control](/docs/features/access-control/) | | **SSO** | OIDC login (Google, Keycloak, Okta...), group restriction, and federated logout | `oidc_login`, `oidc_group_policy`, `oidc_backchannel_logout` | [OIDC](/docs/features/oidc/) | | **SAML SSO** | SP-initiated SAML 2.0 login bound to existing local users, with trust editable from the API/console | `saml_login`, `saml_management` | [SAML](/docs/features/saml/) | | **Federated MFA assurance** | Exact signed context/method proof and callback-time authentication freshness for configured OIDC/SAML login | `federated_mfa` | [MFA policy](/docs/features/federated-mfa/) | | **SCIM** | User and group provisioning from the IdP | `scim`, `scim_groups` | [SCIM](/docs/features/scim/) | | **Inference JWT** | Apps authenticate with a token from your IdP, bound to a gateway identity | `jwt_inference` | [JWT](/docs/features/jwt-inference/) | | **Plans** | An additional resource ceiling per team plan | `plan_entitlements` | [Plans](/docs/features/entitlements/) | | **Owners and workloads** | Who is accountable for each key | `identity_ownership` | [Owners](/docs/features/identity-ownership/) | | **Audit** | Who changed keys, teams, providers, flags, and policies, with the `request_id` | `audit_explorer` | [Security](/docs/security/security/) | | **Legal holds** | Named, audited holds that suspend every destructive retention purge while active | `legal_holds` | [Data governance](/docs/features/data-governance/#legal-holds) | | **Audit retention** | Contractual minimum/maximum retention of the administrative audit log with bounded, audited purge batches | `audit_retention` | [Data governance](/docs/features/data-governance/#audit-retention) | | **Audit tamper evidence** | Every committed audit row sealed into a SHA-256 hash chain, verified on demand and kept verifiable across retention purges | `audit_tamper_evidence` | [Data governance](/docs/features/data-governance/#audit-tamper-evidence) | | **End-user deletion** | Erase one declared end user's stored data within one team (dry run, durable idempotent jobs); financial records kept | `end_user_deletion` | [Data governance](/docs/features/data-governance/#end-user-deletion) | | **Content capture** | Opt-in, encrypted copy of a team's prompts and answers for audit; what each person reads follows their role's content permissions, and every read is audited | `content_capture` | [Content capture](/docs/features/content-capture/) | | **Capture views and purposes** | One team policy keeps the request as received (audit), as sent after guardrail masking (evaluation), or both, per operation; the evaluation capture policies fold into it | `content_capture_evaluation` | [Content capture](/docs/features/content-capture/#one-policy-for-audit-and-evaluation-content_capture_evaluation) | | **Captured media store** | Images and audio of a captured request or answer kept as encrypted attachments beside the record, bounded per record and per team, expiring with it | `content_capture_media` | [Content capture](/docs/features/content-capture/#captured-images-and-audio-content_capture_media) | | **Captured reasoning** | The model's reasoning kept as its own part of a record, streamed or buffered, shown only with `content_reasoning:read`; a judge reads it only when its evaluator asks | `content_capture_reasoning` | [Content capture](/docs/features/content-capture/#the-models-reasoning-content_capture_reasoning) | | **Content visibility ladder** | Five content permissions bundled by the built-in roles from the top down; a custom role ceiling withholds any of them | (roles) | [Access control](/docs/features/access-control/#content-visibility-follows-the-role) | | **Secret vaults** | Credentials in Vault, Conjur, AWS, Google, or Azure | (configuration) | [Cryptography](/docs/security/cryptography/) | ## The principle A flag enables a feature, but it **never grants permission**. What a key can do is the intersection of its own scope, the team policy, and the organization ceiling. When in doubt, the gateway denies. # Keys, teams and roles **Last updated:** 2026-11-27T11:44:16-03:00 (UTC-3) The gateway separates two things: - **Who calls the API:** applications, with **virtual keys** (the data plane). - **Who administers:** people, with **console users** and roles (the control plane). A key never grants a console role, and a console role never allows inference without a key. A flag turns a feature on, but **never grants permission**: when in doubt, the gateway denies. ## Virtual keys Each application gets its own key, with a team, allowed models, route scopes and an optional expiration. Omission/null means Never; no default policy imposes a deadline. Flag: `identity_management`. **In the console:** **Virtual keys**, via the create key button. The secret is shown only once. **Through the API:** `POST /api/v1/admin/keys`: | Field | Rule | | --- | --- | | `alias` | Display name, 2 to 128 characters | | `kind` | `virtual` or `service_account` | | `principal` | Who uses the key (application, service), 2 to 128 characters | | `team` | Team ID | | `allowed_models` | 1 to 100 aliases, groups (`group:`) or `*` | | `scopes` | 1 to 16 scopes: `route:chat`, `route:embeddings`, ... or `route:*`; `mcp:read` and `mcp:execute` for [MCP](/docs/features/mcp-execution/); `traces:write` to upload a coding agent's transcript with `POST /v1/traces` ([transcript ingest](/docs/features/agent-recognition/#transcript-ingest)) or an application's spans ([OTLP ingest](/docs/features/otlp-ingest/)); `traces:read`, `evaluations:read`, `evaluators:read`, `evaluators:write`, `reviews:read` and `reviews:write` for the [public trace API](/docs/features/public-trace-api/) | | `expires_at` / `expires_in` | Optional absolute UTC date or positive duration, mutually exclusive; omitted/null means Never | | `tags` | Optional static key metadata under `key_metadata_tags`; separate from request tags | | `owner` | Optional: the key's [owner](/docs/features/identity-ownership/) | Keys can also be declared in YAML, with the SHA-256 hash of the secret in an environment variable: ```yaml keys: - id: local-app principal: example-app team: platform kind: service_account sha256_env: GATEWAY_CLIENT_KEY_SHA256 allowed_models: [chat-default] scopes: ["route:*"] ``` | Key | What it does | | --- | --- | | `keys[].id` | Unique key ID, used in logs, policies and the console; it is not the secret | | `keys[].principal` | Who uses the key, such as an application name, recorded with each request | | `keys[].team` | The team the key belongs to | | `keys[].kind` | Required: `virtual` (an application key) or `service_account` | | `keys[].allowed_models` | Aliases, `group:` references or `*` the key may call | | `keys[].scopes` | Routes and MCP scopes the key may use | | `keys[].owner.kind` | `user` or `workload`: who answers for the key ([owners](/docs/features/identity-ownership/)) | | `keys[].owner.id` | The `usr_…` user ID or workload ID of that owner | | `keys[].sha256_env` | Name of the variable (or Secret key) that holds the hex SHA-256 of the key's secret, read at startup; the usual way to declare a key | | `keys[].sha256` | The hex SHA-256 itself, written in the YAML; a digest is not the secret, but prefer `sha256_env` so rotating it does not change the file. If both are set they must be equal | Every YAML key needs exactly one 64-character digest. `gateway keygen` ([CLI](/docs/reference/cli/)) prints a new token and its digest. See [key expiry and policy](/docs/features/key-policy/) for the choices, optional governance, static tags and secret-free notifications. The gateway stores only the hash. Revoking a key denies the next request on every replica; `key_deletion` also removes it from the inventory. To change the secret without downtime, see [rotation](/docs/features/key-rotation/); to authenticate with your IdP's token, see [inference JWT](/docs/features/jwt-inference/). ## Teams and team policy A team groups keys and sets their **ceiling**. Flags: `team_management` (create and rename teams), `team_policy_enforcement` (enforce the ceiling) and `team_policy_management` (edit the ceiling in the console). With `team_deletion`, which requires `team_management`, a global admin deletes a console team, and every key of the team is revoked in the same change. ```yaml team_policies: - team: platform allowed_models: [chat-default, group:embeddings] scopes: ["route:chat", "route:embeddings"] ``` | Key | What it does | | --- | --- | | `team_policies[].team` | The team the ceiling applies to, by its ID | | `team_policies[].allowed_models` | Aliases and `group:` references the team's keys may ever use; an empty list denies every model | | `team_policies[].scopes` | Route and MCP scopes the team's keys may ever hold; an empty list denies them all | What a key can do is the **intersection** of the key, the team policy and the [organization](/docs/features/organizations/) ceiling. Where one side names a `prefix/*` alias (or the key `*`) and the other a model under it, the narrower entry is kept, at the team and at the organization alike. The ceiling is checked on every request: removing a model from the team denies the next call from every key in it. With `team_policy_enforcement`, creating a key is held to the same rule for every role, administrators included: - **Team without a policy:** a key for it is refused with `403 team_policy_required`, because such a team allows nothing yet. - **Model or route outside the ceiling:** naming one the team's ceiling would remove is refused with `403 outside_team_policy`, and the message lists what is outside. - **Wildcards:** `*` and wildcard entries (`groq/*`, `route:*`) stay allowed. They mean "whatever the team allows". - **Console:** **Virtual keys → Create key** offers only the models the chosen team allows. - **Ceiling narrowed later:** a call to a model the key still names is refused with `403 model_forbidden` "Model is outside the team policy of this key", rather than blaming the key. - **[Model aliases](/docs/features/model-aliases/)** (`model_aliases`): a key, team policy, organization ceiling or group that names a canonical model also covers its `alias_of` aliases; one that names only an alias covers only the alias, never the canonical model. A [moving alias](/docs/features/model-aliases/#moving-aliases-follows) (`follows`, `model_follows`) is covered only by its own name, `*` or a `prefix/*` entry: granting the model it currently resolves to does not grant it, so a change of resolution never changes who may call what. ## Access groups A group is a reusable set of models, referenced as `group:` in keys, team policies and organizations. Adding a model to the group makes it available to everyone who references the group. Flags: `access_groups` and `access_group_management` (edit in the console). ```yaml access_groups: - id: embeddings name: Embeddings models: [embeddings-small, embeddings-large] mcp_servers: [docs] # optional ``` | Key | Default | What it does | | --- | --- | --- | | `access_groups[].id` | required | Unique identifier; keys and policies reference it as `group:` | | `access_groups[].name` | required | Display name, 2–128 bytes of UTF-8 on one line | | `access_groups[].description` | empty | Up to 512 bytes of UTF-8, shown in the console | | `access_groups[].models` | `[]` | Up to 100 existing model aliases, listed explicitly (no `*`, no nested group); a group needs at least one model or MCP server | | `access_groups[].mcp_servers` | `[]` | Up to 100 registry MCP servers the group grants, when the server also requires `group:`; a group needs at least one model or MCP server | | `access_groups[].mcp_tools` | `[]` | Up to 200 `server/tool` references that narrow a listed server to those tools | | `access_groups[].disabled` | `false` | Keeps the group without granting anything through it | There are at most 200 groups. - The group is expanded **before** the team policy and never exceeds it. - A group grants an MCP server only if the server requires `group:` in its scopes and the team policy also references the group. ## Request limits (RPM) With `rate_limits`, requests-per-minute policies per key or per team, shared across replicas. With `end_user_rate_limits`, also per end user of your app (`X-Gateway-End-User` header), within a team. A request without the header is not counted per end user; to refuse such requests, require the header on the team or key ([required attribution](/docs/features/budgets-and-tpm/#require-the-end-user-and-tags)). ```yaml rate_policies: - {id: app-rpm, subject: key, subject_id: local-app, rpm: 600} - {id: time-rpm, subject: team, subject_id: platform, rpm: 3000} ``` The checks a [moderation guardrail](/docs/features/guardrails/#moderation-model) makes are the gateway's own calls and are not counted here, on input or on the answer, enforcing or monitor; the guarded request is counted once, like any request, and over its limit it answers `429 rate_limit_exceeded` before any guardrail runs. So a check is never refused for RPM: with `rpm: 1`, one guarded request a minute is served with its checks, and neither `on_error: block` (`503 guardrail_unavailable`) nor `on_error: allow` (an unchecked request) can result from the caller's RPM. A client calling `/v1/moderations` directly, and the gateway's other in-process calls, are counted as before. For limits in tokens and dollars, see [budgets and TPM](/docs/features/budgets-and-tpm/). ## Concurrent requests per key and team An RPM ceiling counts requests as they start; it does not stop one key from holding dozens of slow streams open at once. A **concurrency cap** limits how many inference requests a key, or all the keys of a team together, have **in flight at the same time**. A request holds its slot from admission until its answer ends: the whole response, a stream to its last event, a provider error, or the client going away. ### How to turn it on ```yaml features: concurrency_limits: true # off by default; enforces every max_concurrent rate_policies: - {id: app-parallel, subject: key, subject_id: local-app, max_concurrent: 8} - {id: platform-parallel, subject: team, subject_id: platform, max_concurrent: 40} - {id: batch-both, subject: key, subject_id: batch-worker, rpm: 600, max_concurrent: 4} ``` `concurrency_limits` is the catalog flag (operator control, default `false`). It does not need `rate_limits` or PostgreSQL: the counters live in memory. With the flag off, `max_concurrent` is kept and shown as staged, and nothing is refused. | Field | Default | Bounds and meaning | | --- | --- | --- | | `max_concurrent` | `0` (no cap) | 0–100000. Inference requests of the subject in flight at once **in each replica**. Only `key` and `team` subjects; an `end_user` policy with `max_concurrent` is refused at validation. | | `rpm` | — | 0–1000000. With `max_concurrent`, `rpm` can be `0`, meaning no per-minute ceiling. A policy needs `rpm` or `max_concurrent` (or both) of at least 1. | A key is counted by its own key policies and by the team policies of its team. Every cap that counts a request must have room: a key under its own cap is still refused when its team is full, and a refused request takes no slot of any cap. Two policies on the same subject are two separate caps. ### What the client sees Over a cap, the request is refused at once, before the per-minute counter, quota reservation, guardrails, routing and any provider call: ```http HTTP/1.1 429 Too Many Requests Retry-After: 1 Content-Type: application/json {"error":{"code":"concurrency_limit_exceeded","message":"Too many concurrent requests for this team; retry when one finishes"}} ``` The message says whether the **key** or the **team** cap is full, never the policy ID or another key. There is no queue: a slot frees when one of the subject's requests ends, so retry after a short wait. A refused request does not count against the RPM ceiling. ### Which requests take a slot - **Every request admitted under an inference route scope** (`route:` other than `route:models`): the same requests rate policies count, from chat completions and Responses to embeddings, audio, images, video, OCR, token counting, fine-tuning and the stored-response, conversation and container routes. A **realtime session** holds one slot for its whole life, like a stream. - **Once per request.** A semantic fallback runs inside the client's request and uses its slot: a key with `max_concurrent: 1` still gets its fallback answer. - **Vector stores:** the vector store routes are not inference routes, but the embedding and OCR calls a file upload, file batch or search makes with the client's key are, and each takes a slot while it runs (one at a time per vector store request). At the cap, the vector store request answers the same `429 concurrency_limit_exceeded` with `Retry-After`; in a file batch (or a vector store created with `file_ids`) the refusal is reported per file, as `concurrency_limit_exceeded` in the batch's failed files, like any other per-file error. - **Not counted:** the gateway's own in-process calls (provider guardrails, semantic cache embeddings, routing classifiers, evaluations, m7 ai, batch lines). `GET /v1/models`, MCP, agents, files and batches are not inference routes. A Response created with `background: true` runs at the provider; it holds a slot only while the `POST /v1/responses` that creates it is answered, and each later retrieval is a request of its own. ### Per replica The count is per process, like the [destination limits](/docs/features/routing-and-admission/) and the instance admission limit: replicas do not share it. With N replicas behind a load balancer, a key can have up to **N × `max_concurrent`** requests in flight. Size the cap for one replica, or divide the total you want by the replica count. A restart or rollout starts each new process at zero. Lowering a cap does not cut requests already in flight; new requests are refused until the count drops below the new value. Editing or disabling a policy applies to the next request. ### Console, API and metrics - **Console:** **Rate policies → Add policy / Edit** has **Concurrent requests per replica**; `Requests per minute` accepts 0 when a cap is set. Each card shows the cap and what the replica answering the console holds of it. - **API:** `max_concurrent` in the policy of `PUT /api/v1/admin/rate-policies/{id}` (requires `rate_policy_management`). `GET /api/v1/admin/rate-policies/status` answers with `rate_limits` or `concurrency_limits` and adds a `concurrency` block with `scope: process`, the answering replica's `process_instance_id` and, per active cap, `id`, `max_concurrent` and `in_flight`. - **Metrics:** with `metrics_endpoint` and `concurrency_limits`, `/metrics` publishes `gateway_caller_concurrency_in_flight{subject="key"|"team"}` (slots held in this process; a request counted by a key and a team cap holds one of each) and `gateway_caller_concurrency_admission_total{result="admitted"|"refused"}` (decisions for requests that met at least one cap). No key, team or policy ID is a label. ### Upgrade notes No migration: managed policies store `max_concurrent` in the same JSON document as the rest of the policy, and existing policies keep `rpm` as before. **During a rolling upgrade, do not save a policy with `max_concurrent` or `rpm: 0` until every replica runs this version:** an older replica refuses the whole control snapshot once it holds an `rpm: 0` policy (it keeps its last valid snapshot and stops applying later changes), and silently ignores `max_concurrent` on the others. Policies with `rpm: 0` are new; a gateway older than this version refuses them at validation (and a YAML `max_concurrent` key as unknown), so before rolling back remove those policies and keys. ## Console users and roles With `console_users`, each person has a named, revocable user. The bootstrap admin token still exists for recovery. | Role | Sees | Can change | | --- | --- | --- | | `admin` | Everything | Identities, governance and operations | | `viewer` | Everything except named users, prompt content and admin-only policies | Nothing | | `operator` | Operational configuration: catalog, models, providers, MCP, RPM, circuit breaker, cache | Providers, aliases, MCP inventory, RPM, circuit breaker and cache purge | | `team_admin` | Only their own teams | Keys of their own teams, within the team policy | | `team_viewer` | Only their own teams | Nothing | | `user` | Only their own teams (1 to 20) | Nothing | Flags: - `operator` and `user` require `granular_rbac` (which requires `console_users`); `user` also requires `team_scoped_console`. - `team_admin` requires `team_admin_console`. - With `membership_roles`, each association of a `team_admin` with a team is `admin` (manages keys) or `member` (read only). Caveats: - **`operator` changes routing and provider credentials**: it is a trusted role, not a "look only" role. It does not issue keys, manage people or change flags, and it does not read logs, analytics or audit. - **`team_admin`** does not create keys with `*` in models, `route:*`, `mcp:read` or `mcp:execute`, and does not assign owners. - Prompt content and history are closed to `viewer` and `operator`. Team members can read them with `prompt_scoped_read` (see [prompts](/docs/features/prompt-registry/)); render and write are admin-only. ### Invitations and import With `user_invitations`, the global admin invites people with a single-use link that expires; whoever accepts receives their own credential and joins with the invitation's role and teams, checked at that moment. Bulk import, which needs `user_bulk_management`, previews a list of people and then sends them as invitations with a result per row; it and invitation revocation are global admin actions. With `invitation_email`, the link can be [sent by e-mail](/docs/features/invitation-email/), and with console SSO an invitation only pre-provisions the user, who signs in through SSO. To provision from your IdP, see [SCIM](/docs/features/scim/); for corporate login, [SSO](/docs/features/oidc/). ## How authorization works - Every console route requires a resource-and-action permission (`providers:manage`, `keys:read`, `quotas:manage`...). An unknown route or role is denied, even for admin. - Login and session return the `permissions` list, which the console uses to show menus and buttons. The decision is always the server's: tampering with the JavaScript gives no access. - **Role, state and teams are reread from PostgreSQL on every request.** Deactivating someone or downgrading their role takes effect on the next request; no privilege is stored in the cookie. - Every write requires a same-origin session and CSRF, and goes into the [audit trail](/docs/security/security/). - Queries for team roles filter by team in the database, before paginating or aggregating. Some permissions that appear in other guides: | Permission | Who has it | | --- | --- | | `quotas:read` / `quotas:manage` | admin, viewer and operator read; only admin changes | | `quota_reservations:release` | admin for every organization; an organization admin for reservations of its own organization that hold no ceiling set above it: list the held unknown reservations, [release them by hand](/docs/features/quota-finance/#releasing-an-unknown-reservation-by-hand) with a written reason, and read the trail of releases (flag `quota_manual_release`). Viewer, operator and team roles do not hold it, and it is in no custom role | | `resilience:read` / `resilience:manage` | admin, viewer and operator read; admin and operator change | | `local_inference:read` / `local_inference:operate` / `local_inference:manage` | admin, viewer and operator see the [local inference](/docs/features/local-inference/) pools and replicas; admin and operator start, stop and restart a replica; only admin changes the pool list. Team roles have none of them | | `logging:read` / `logging:manage` | global admin and viewer read; only global admin changes the runtime minimum under `logging_management`; operator and scoped roles denied | | `infrastructure:manage` (cache backend) | admin only | | `workloads:read` / `ownership:manage` | admin and viewer read; only admin changes | | `skills:read` / `skills:manage` | admin, viewer and per-team readers; only admin changes | | `mcp:read` / `mcp:manage` | MCP health check: admin and operator | | `alerts:read` / `alerts:manage` | admin and viewer read; only admin changes | | `alert_rules:read` | [alert rules](/docs/features/alert-rules/#who-sees-what) and their alerts: admin, viewer, operator, `team_admin`, `team_viewer` and `user`, each within its own teams (an organization admin also within its organization) | | `alert_rules:manage` | creating, editing, muting and deleting rules, acknowledging, resolving and muting alerts, and the backtest: admin everywhere; `team_admin` on the teams it administers; an organization admin also on its organization's rules. A custom role never holds it | | `alert_rules:global` | widens the two above to every team, every organization and the global (operational) rules: admin; viewer and operator read only. Without it a session never sees a global rule or alert | | `monitors:read` | [evaluation monitors](/docs/features/evaluation-monitors/#who-sees-what): admin and viewer; `team_admin`, `team_viewer` and `user` within their own teams whose plan includes `evaluation_monitors` | | `monitors:manage` | creating, editing, muting, testing and deleting monitors, and the backtest: admin everywhere; `team_admin` on the teams it administers. A custom role never holds it | | `monitors:global` | widens the two above to every team: admin; viewer read only | | `guardrails:read` / `guardrails:manage` | admin and viewer read; only admin changes | | `branding:manage` | admin only | | `recycle_bin:read` | admin and viewer; an organization admin for its organization (T168) | | `recycle_bin:restore` | admin; an organization admin for its organization ([disable and trash](/docs/features/disable-and-trash/)) | | `mcp_credentials:manage` | admin and operator on any team; `team_admin` on their own teams | | `jwt:manage` | admin only | | `content_capture:manage` | admin only: [content capture](/docs/features/content-capture/) policies, reader grants and deletion | | `requests:replay` | admin on any team; organization admin inside its organization; `team_admin` on their own teams: [replay a captured request](/docs/features/trace-explorer/#replay-a-request) as oneself (flag `request_replay`; also needs `content_sent:read` of the team). A custom role ceiling can withhold it | | `evaluators:publish` | admin on any team; `team_admin` on the teams they administer: publish a version of an [evaluator](/docs/features/evaluators/), pause, resume or disable it, run a backfill, and run it on chosen traffic or cancel such a run (`code_evaluators`, with `logs:read` for the run), which is what puts a judge on traffic (flag `evaluators`). Saving a draft and restoring a version stay with `evals:manage`. A custom role ceiling of a team administrator can withhold it | | `evaluators:test` | the same roles: run the evaluator editor's [test pane](/docs/features/evaluators/#test-before-you-publish), which makes judge calls on real traffic as playground traffic of the team; the previews and resolved variables it shows also need `content_sent:read`. A custom role ceiling can withhold it | | `reviews:annotate` | admin; `team_admin` and `user` in their teams: take the items of a [review queue](/docs/features/human-review/#who-may-do-what) and review them. An open queue is worked by the people who administer its team; a queue with assignees by them, whatever their role. What a reviewer reads of captured content is what the content permissions above give them. A custom role ceiling (base `user` or `team_admin`) can withhold it | | `reviews:assign` | admin; `team_admin` in the teams they administer: name who reviews an item, and take any item whoever it is assigned to (flag `review_multi_annotator`). A custom role ceiling of a team administrator can withhold it | | `review_queues:manage` | admin; `team_admin` in the teams they administer: create, change and delete review queues, add and remove their items, and manage the [automations](/docs/features/human-review/#automations) that fill queues and datasets. Like every `:manage` permission it is in no custom role | | `reviews:calibrate` | admin; `team_admin` in the teams they administer: read every reviewer's values, export a queue, read the [calibration](/docs/features/human-review/#calibration) of the judges and settle a final value; `viewer` reads the same across teams and settles nothing. A custom role ceiling (base `viewer` or `team_admin`) can withhold it | | `saved_views:read` | admin and viewer (the views of every team and organization); `team_admin`, `team_viewer` and `user` (their teams' and organizations'): read [saved views](/docs/features/query-language/#saved-views) of the Traces and Request logs screens (flag `trace_query`). A custom role ceiling can withhold it | | `saved_views:save` | the same roles, in a named session: keep, update and remove one's own views and choose a default. A shared token names nobody and cannot. A custom role ceiling can withhold it | | `saved_views:share` | admin with any team or organization; organization admin with its organization and its teams; `team_admin` with the teams they administer: share a view and manage the views of that team or organization. A custom role ceiling of a team administrator can withhold it | | `dashboards:read` | admin and viewer (the dashboards of every team and organization); `team_admin`, `team_viewer` and `user` (their teams' and organizations'): read [custom dashboards](/docs/features/dashboards/), the built-in ones included, their versions, their widgets' data and the widget library (flag `custom_dashboards`). A widget's data is read through its source, so `analytics:read` (usage metrics) or `logs:read` (traces) applies as well. A custom role ceiling can withhold it | | `dashboards:save` | the same roles, in a named session: keep, change, copy, restore and remove one's own dashboards and library widgets, and preview a widget in the builder. A shared viewer token names nobody and cannot. A custom role ceiling can withhold it | | `dashboards:share` | admin with any team or organization; organization admin with its organization and its teams; `team_admin` with the teams they administer: share a dashboard or a library widget and manage those of that team or organization. A custom role ceiling of a team administrator can withhold it | | `topics:read` | admin and viewer (every team); `team_admin`, `team_viewer` and `user` (the maps of their teams; an organization admin, also its organization's): see [Topics](/docs/features/topics/) maps, topic names and descriptions, counts, figures and the scatter, use the `topic.` term of the query language and the Topics MCP server (flag `topics`). Summary text still needs `content_sent:read` of the unit's team. A custom role ceiling can withhold it | | `topics:manage` | admin (every team); `team_admin` (the teams it administers; an organization admin, also organization-wide maps): create, change, pause, resume, refresh and delete maps, rename, merge and mute topics, write a team's own facets. A custom role ceiling can withhold it | | `topics:configure` | admin only: replace or revert the gateway-wide `topics` settings and reset Topics | | `route_experiments:read` | admin and viewer (every team); `team_admin`, `team_viewer` and `user` (their teams; an organization admin, also its organization's): read [route experiments](/docs/features/route-experiments/) and their readouts (flag `route_experiments`). A custom role ceiling can withhold it | | `route_experiments:manage` | admin (every team); `team_admin` (the teams it administers): create, change, stop and delete route experiments. Guarded rollback still needs the operator's opt-in on the alias. A custom role ceiling can withhold it | | `insights:manage` | admin (every team); `team_admin` (the teams it administers): set the triage status of a [failure insight](/docs/features/failure-insights/) group (flag `failure_insights`); reading insights needs `analytics:read` and `logs:read`. A custom role ceiling can withhold it | | `content_structure:read`, `content_sent:read`, `content_reasoning:read`, `content_media:read`, `content_received:read` | The content ladder below: what each role reads of captured content | | `content:read` | **no role**: a named console user given an explicit grant by another named administrator; it carries the five content permissions for the teams of the grant, and every read is audited ([content capture](/docs/features/content-capture/#the-contentread-grant)) | ### Content visibility follows the role Every access level is a permission inside a role. What a person reads of [captured content](/docs/features/content-capture/) is five permissions that the built-in roles bundle from the top down: the top role holds all of them and each role below holds fewer. | Permission | Reads | | --- | --- | | `content_structure:read` | Record metadata and the structural items of a span; no content | | `content_sent:read` | The request after the input guardrails and the answer, as text | | `content_reasoning:read` | The model's reasoning, captured apart | | `content_media:read` | Captured images and audio | | `content_received:read` | The request exactly as the client sent it | | Built-in role | Scope | `content_structure:read` | `content_sent:read` | `content_reasoning:read` | `content_media:read` | `content_received:read` | | --- | --- | --- | --- | --- | --- | --- | | `admin` | every team | yes | yes | yes | yes | yes | | `org_admin` | the teams of its organization | yes | yes | yes | yes | yes | | `team_admin` | the teams it administers | yes | yes | yes | yes | no | | `team_viewer` | its teams | yes | no | no | no | no | | `user` | its teams | yes | no | no | no | no | | `operator` | every team | yes | no | no | no | no | | `viewer` | every team | yes | no | no | no | no | - **One function decides every read.** It takes the session's effective permissions (the role's bundle under its custom ceiling, if any), never the role's name, and narrows them to the record's team. The request details, the media read, the evaluation screens, the review queue, session transcripts, dataset imports, judge reasoning on results and the structural items of a span all use it. - **No level crosses organizations.** A team role reads its own teams only, an organization admin the teams of its organization only, with or without a `content:read` grant. `admin`, `operator` and `viewer` are gateway-wide roles. - **Nor does a team that moves.** A team's role reaches what the team recorded in the organization it is in now. Captures, spans, traces, results, comments, runs and request log rows it recorded under a former organization are not read through the team any more, by its own roles or by the administrators of its new organization: see [targets after a team moves](/docs/features/evals/#targets-after-a-team-moves). - **An organization administrator reads what was recorded in its organization through the organization on the row.** Its permissions (`analytics:read`, `logs:read`, `evals:read` and the content permissions above) cover everything recorded in its organization, including by a team that has since moved away, and nothing that team records elsewhere. No new permission and no membership is involved; a custom role ceiling narrows it as it narrows every other read; it is a read only; and with feature plans the organization's own plan must include the feature. See [when a team moves](/docs/features/organizations/#when-a-team-moves). - **A [custom role ceiling](/docs/features/custom-roles/) can withhold any of the five and never grants one** beyond its base role: `content_received:read` is in no ceiling, and a `viewer` or `operator` ceiling is offered `content_structure:read` only. So "the sent view as text" for a reviewer is a ceiling on `team_admin` that keeps `content_sent:read` and withholds reasoning and media; there is no evaluator role. - **With `membership_roles`**, a team administrator's `member` association gives that team the member's share: `content_structure:read`. - **The operator** holds `content_structure:read` alone (least privilege): it changes routing and reads no request log, analytics or audit, and no captured content. More comes only through a role that holds it, or a `content:read` grant. - **A shared admin token** names nobody: it holds the administrator's bundle except `content_received:read`. - **[Agent runs](/docs/features/agent-recognition/) use the same permissions, and add none.** The run list and a run's thread (agent, IDs, owners, counters, times) need `logs:read`: `admin`, `viewer`, `team_admin`, `team_viewer` and `user`, each within its scope. Tool names and call IDs need `content_structure:read` of the run's team, in a thread, in the trace view and in the read of one span; without it the steps are listed unnamed. The task the user typed, kept only under `agent_recognition.task_capture`, needs `content_sent:read` of the run's team (`admin`, the organization admin and `team_admin`), and each read is audited as `agent_run_task.read`. The effective settings and rules need `config:read`. - `GET /api/v1/admin/content-access` answers the ladder and what the calling session reads per team; **Content capture → Who reads what** shows the same table. ## Limits - [Delegated prompt actions](/docs/features/prompt-delegation/) require an explicit owning-team policy for existing `user`/`team_admin` identities; membership alone never grants a writer. Draft, publication and destructive rights are separate and retain live custom-role/plan/license ceilings. - The optional [custom role ceiling](/docs/features/custom-roles/) restricts an existing named-user role through an explicit finite permission catalog. It never creates a custom administrator, arbitrary route grant or attribute-based policy. - Do not map an IdP name, email or group directly to `admin`: the link is explicit and reviewed. - The only per-organization role is [`org_admin`](/docs/features/organization-admins/) (`organization_admins`); there is no per-organization viewer. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `GET /api/v1/admin/access-groups` | Lists the access groups (YAML base and console overrides) with the keys and team policies that reference each one; `access_groups` | | `PUT /api/v1/admin/access-groups/{id}` | Creates or edits a group at the current configuration version; `access_group_management` | | `DELETE /api/v1/admin/access-groups/{id}` | Reverts a YAML group to its declaration, or removes a console group | | `GET /api/v1/admin/agent-runs` | Lists the recognized coding-agent runs of the reader's teams; `logs:read` ([agent runs](/docs/features/agent-recognition/#who-reads-what)) | | `GET /api/v1/admin/agent-runs/{id}` | One run as a thread; `logs:read`, tool names and call IDs with `content_structure:read`, the task text with `content_sent:read` | | `GET /api/v1/admin/agent-runs/settings` | The effective agent recognition settings and rules; `config:read` | | `GET /api/v1/admin/keys/page` | One page of managed keys with filters, sort and total, for the console inventory; no secret or hash | | `GET /api/v1/admin/keys/{id}/detail` | One key's metadata, access ceiling, usage and recent audit in one consistent read | | `DELETE /api/v1/admin/keys/{id}` | Revokes and soft-deletes a managed key | | `POST /api/v1/admin/keys/{id}/enable` | Enables a disabled key again with the same secret | | `GET /api/v1/admin/keys/{id}/auto-route-usage` | The key's auto-routed traffic per alias: turns, sessions, models chosen and cost against the most expensive candidate | | `GET /api/v1/admin/keys/{id}/savings` | What the key saved per day through the gateway cache, provider prompt caching and the auto-router | | `PUT /api/v1/admin/keys/{id}/owner` | Sets, changes or clears the [owner](/docs/features/identity-ownership/) of a managed key | | `GET /api/v1/admin/teams/page` | One page of console teams with filters, sort and total | | `GET /api/v1/admin/teams/{id}/detail` | One team's metadata, policy, usage and recent audit | | `POST /api/v1/admin/teams/{id}/enable` | Enables a disabled console team again | | `GET /api/v1/admin/teams/{id}/member-permissions` | The key actions the team delegates to its plain members, and those it could delegate | | `PUT /api/v1/admin/teams/{id}/member-permissions` | Replaces the delegated key actions (`keys:create`, `keys:rotate`, `keys:revoke`, `keys:delete`) | | `PUT /api/v1/admin/teams/{id}/policy` | Sets the team ceiling on model aliases and route or MCP scopes | | `DELETE /api/v1/admin/teams/{id}/policy` | Removes the console policy and restores the YAML policy, or default deny | | `GET /api/v1/admin/keys` | Lists managed and YAML key metadata; scoped roles see only their teams' keys; never a secret or hash | | `GET /api/v1/admin/teams` | Lists teams with their effective policy when team policy enforcement is on | | `POST /api/v1/admin/users` | Creates a named console user and returns its personal token once | ## See also - [Access and governance](/docs/features/feature-access/): overview of the group. - [Organizations](/docs/features/organizations/) and [plans](/docs/features/entitlements/). - [Security](/docs/security/security/). ## Legacy operational switches and catalog origins Five independent catalog flags package behavior that earlier versions always exposed. They default to enabled when omitted and are explicit `true` in both shipped YAML profiles. An explicit `false` wins; none grants a permission or bypasses model/key authorization. All other omitted flags retain their existing defaults. | Flag | When disabled | | --- | --- | | `emergency_stop` | Cannot engage a new emergency stop; an already engaged stop remains enforced, visible and releasable by its existing authorized administrator | | `model_test` | The explicit provider test endpoint/control is unavailable; enabling it never initiates a paid call | | `provider_presets` | The administrative presets endpoint and console integrations/preset controls are unavailable; declarative YAML preset references still expand | | `wildcard_aliases` | Wildcard declarations remain valid, but runtime wildcard resolution/listing is disabled, including the literal wildcard ID; ordinary aliases keep working | | `docs_site` | Documentation, Swagger page and llms.txt are unavailable under the existing UI requirement; this does not disable inference | The global flag catalog labels omitted values **Default**, explicit YAML values **YAML**, and versioned overrides **Console**. Removing an override restores the declared/base default. The private declared-origin map is preserved and independently copied across control-plane snapshots; it is not an inference credential. Operators can read this catalog, but cannot toggle flags or read finance/key data through that new read permission. Scoped team/user roles retain their existing allowlisted feature view. ## Typed credential choices The shared [parameter definitions](/docs/reference/parameter-registry/) keep key kind explicit: `virtual` or `service_account`. Both retain the existing scope/model checks and the team checks applicable to their YAML or managed-key path; a credential kind never supplies an administrative role. The console’s virtual-key creation preset is separate from the required YAML/API field. Optional owner attribution retains its own typed schema and authoritative directory checks; compiled choices contain no credential hashes, subjects or grants. ## Realtime policy administration `realtime:read` is global admin/viewer only; its dedicated policy DTO includes nonsecret per-key IDs. `realtime:manage` is global admin only. Operators, team roles and inference credentials cannot use this editor. Session, CSRF, feature and optimistic-version checks remain cumulative; `realtime_management` never grants permission. The ordinary boot inspector still shows only a map count. [Contract](/docs/features/realtime/#manage-policy-without-reconnecting-existing-sessions). ## Destination policy administration `destinations:read` is global admin/viewer only; `destinations:manage` is global admin only. These rights protect the opt-in `log_destination_management` editor. Existing `logs:read` and synthetic-test rights remain separate. A template is an operator-approved connection binding, never a grant to use another secret source or endpoint. The API refuses caller-selected environment variables, cloud credential/profile selectors and network targets. Session/CSRF/version/flag checks remain cumulative. [Trust boundary](/docs/features/observability/#manage-approved-destination-instances). ## Restart-policy permissions The optional [HTTP restart policy](/docs/operate/http-input-limits/#save-changes-for-the-next-startup) uses `boot_settings:read` for global admin/viewer and `boot_settings:manage` for global admin only. Operators, team roles, auditors and inference keys do not inherit either right. Writes require a valid session, same origin, CSRF token, current global version and the enabled management flag, plus a known owned startup observation. Read access exposes only three nonsecret durations and their sources; it never grants generic listener, connection or secret management. ## Instance model-ranking controls External rankings require global `catalog:read`; their instance fetch-policy read additionally requires a global admin, viewer or operator role and `config:read`. Scoped users/team viewers/team admins do not gain this policy merely because their filtered configuration view uses `config:read`. Policy writes/revert require global `models:manage`, CSRF, management flag and current version. Enabling flags never grants permission, and none of these controls maps source names to authorized inference aliases. See [rankings](/docs/features/model-rankings/). ## Public research and policy authority `model_registry` discloses only original public-source research through anonymous `/registry` and `/v1/registry/models` reads. It is an operator control, not a private-catalog/team permission. Public pages never call session/admin APIs. The separate `model_registry_management` switch requires PostgreSQL and the registry. Its instance policy GET requires a global config reader; PUT/DELETE require global `models:manage`, CSRF and versioned audited CAS. A scoped `config:read` role cannot inspect it. Commercial activation checks remain separate. See [policy, publication and recovery](/docs/features/public-model-research/). ## Client-source ceilings The default-off boot operator `source_ip_controls` adds canonical trusted-proxy resolution and independent key/admin CIDR ceilings. Managed source policies have YAML/API/console inspection or editing according to their owner and current scoped administrator permissions, independent version/audit and credential-rotation preservation. Enabling a flag never grants identity, routes or models; missing native managed-policy proof fails closed. Background work does not invent a localhost grant. See [source controls](/docs/security/source-ip-controls/) for exact XFF, callbacks, default/limits and recovery semantics. Optional `client_ip_logging` collects only stdout/OTLP metadata; SQL/financial history is unchanged. ## Model request windows The optional model/key×model admission group adds shared1m/1h/1d request ceilings after canonical model authorization. It does not grant access or replace legacy pre-parse RPM, budget or process-local concurrency checks. See [request rate limits](/docs/features/rate-limits/) for flags, defaults, the two-group consumption contract, auto-routing/realtime behavior and versioned management/status. ## Named OIDC policy authority `oidc_providers:manage` is a finite global-administrator capability for the [named OIDC catalog](/docs/features/oidc-providers/), including its read routes. It does not grant a role from an identity claim, and operator/team administration does not include it. Current custom ceilings, CSRF, durable policy generation, version/base guards and classified license write restrictions are cumulative. Runtime login resolves an explicit provider-scoped subject to an existing active user; subsequent requests retain live local-role and membership checks. # Custom permission ceilings **Last updated:** 2026-11-25T08:50:47-03:00 (UTC-3) Give a named console user a smaller, explicit set of actions while preserving the user's existing built-in role and team boundaries. A financial reader can see analytics without seeing keys or providers. A team key rotator can rotate authorized credentials without creating or deleting keys. A custom role is a **restriction**, not another source of authority. It cannot make a global administrator, add a team membership, authorize inference, bypass a plan or grant an action that the underlying role or team denies. Existing users without a custom binding keep their built-in behavior. ## Enable or stage a policy ```yaml features: console_users: true granular_rbac: true custom_roles: true custom_roles_management: true custom_roles: roles: - id: finance_reader name: Finance reader base_role: viewer permissions: [session:read, config:read, analytics:read] disabled: false bindings: [] ``` Both new flags default to `false`. `custom_roles` enables the named user's restrictive authorization profile. `custom_roles_management` enables the administrative API/console writers and requires the UI plus the existing named-user/RBAC foundation. YAML definitions and bindings default to empty lists. No user, credential or infrastructure is provisioned by this configuration. An administrator can stage definitions and bindings with management enabled and enforcement off. **A bound user is denied while enforcement is off**; the gateway never interprets that state as permission to fall back to the full built-in role. Keep an unbound global recovery administrator available. Existing restrictive rights continue to apply if a license expires; expiration does not remove a security ceiling. Administrative changes also require the existing license write checks, so a classified expired edition can remain read only. Feature flags do not grant a console permission or select a commercial plan. ## Definition and binding fields | Field | Meaning and bounds | | --- | --- | | `custom_roles.roles[].id` | Stable lowercase identifier, 2–64 bytes, beginning with a letter and continuing with letters, digits, `_` or `-`; built-in role names are reserved | | `custom_roles.roles[].name` | Trimmed display name, 1–128 UTF-8 bytes, without control characters | | `custom_roles.roles[].base_role` | `viewer`, `operator`, `user`, `team_viewer` or `team_admin`; must match the bound user's built-in role | | `custom_roles.roles[].permissions` | Explicit unique catalog entries, at most64; an empty list grants no resource actions | | `custom_roles.roles[].disabled` | Boolean, default `false` in YAML; the canonical API definition includes it explicitly | | `custom_roles.bindings[].user_id` | An existing named console user's generated ID; cannot identify the shared recovery administrator | | `custom_roles.bindings[].role_id` | The chosen role definition ID; the same name in the API (`bindings[].role_id` of `GET /api/v1/admin/custom-roles`, `role_id` of the assignment body) | At most64 role definitions and500 distinct binding users are supported. The binding bound includes explicit clearing overrides and declared references, not only currently active assignments. Definition IDs, base roles and permission names are case sensitive. Unknown fields, malformed types, duplicate permissions and invalid references are rejected. To declare a binding, first provision the named user through the normal user-management workflow, obtain its actual ID from **Console users** or `GET /api/v1/admin/users`, then add that ID and `role_id` to the YAML list. A name or e-mail is not a user ID. The gateway validates the referenced user and its built-in ceiling; YAML never creates the identity. Include `session:read` and `config:read` when the profile needs the console shell. Give only the other actions that the user needs. Turning off an unrelated read permission must not expose its inventory through configuration: the gateway projects configuration fields according to the effective rights. Public compiled schema metadata can be returned as top-level `parameter_catalog` without disclosing applied infrastructure settings. ## Supported permission profile The administrative catalog returns the exact `permission_catalog`, permitted base roles, action kind and conditional team requirements. Use those entries; do not synthesize permission names from HTTP methods or a `:read` suffix. Some existing console capabilities perform an inference or self-service action, subject to their separate authorization and quotas. The custom write profile contains qualified key actions and the separately enabled owner-team prompt actions below: | Permission | Qualified operations | | --- | --- | | `keys:create` | Create a managed key within existing team/model/route constraints | | `keys:rotate` | Immediate rotation, retiring a previous credential, static metadata tags, and the prepared/confirmed scheduled-rotation workflow | | `keys:revoke` | Revoke an authorized managed key | | `keys:delete` | Logically delete an authorized managed key | A scoped action still requires the user's current team administration or an explicitly delegated member action, plus all applicable policies, flags, plans and license checks. Selecting `keys:rotate` alone does not grant creation, deletion, source-policy editing, attribution editing, ownership assignment or permission delegation. `keys:manage`, arbitrary routes and the `content:read` grant are not custom grants. Unqualified operational write families are not offered by this finite catalog. The key list and credential rotation do not require `teams:read`; when the user cannot list teams, the console shows the admitted team ID instead of its display name. The **console creation form** also needs explicit `teams:read` to obtain the selected team's actual model/route policy. Without it, **Create key** is disabled with that prerequisite shown. Creation does not require key-inventory access: a creator with `teams:read` can open the creation page through `keys:create` while the console labels the key inventory as unavailable to that role. This interface dependency grants nothing implicitly: `keys:create` remains independently enforced by the API, which validates the supplied real team and its policy. The five [content permissions](/docs/features/access-control/#content-visibility-follows-the-role) are in the catalog like any other read, each only for the base roles that hold it: `content_structure:read` for every base, `content_sent:read`, `content_reasoning:read` and `content_media:read` for `team_admin`, and `content_received:read` for none. So a ceiling withholds a content permission by leaving it out, and can never add one: a `team_admin` ceiling that lists only `content_structure:read` reads the metadata of captured records and no content, and a ceiling that lists none of them reads nothing of captured content, the structural items of a span included. The console lists them with a label that says what each one reads. A `content:read` grant does not raise a ceiling. Three [review permissions](/docs/features/human-review/#who-may-do-what) are in the catalog for the base roles that hold them: `reviews:annotate` for `user` and `team_admin`, `reviews:assign` for `team_admin`, and `reviews:calibrate` for `viewer` and `team_admin`. A ceiling over `user` that keeps `evals:read` and `reviews:annotate` is a reviewer who works the queues they are named on and manages nothing; add the content permissions a `team_admin` base allows when the reviewer must read the conversation, or give a reader grant. `review_queues:manage` is administration and, like every `:manage` permission, is in no ceiling. For [delegated prompt management](/docs/features/prompt-delegation/), only `user` and `team_admin` ceilings may include `prompts:write`, `prompts:publish` and `prompts:delete`. Each still needs the explicit owning-team delegation, operational flags, active membership and current plan/license. A `team_viewer` does not gain a prompt writer. Draft save cannot disable, resurrect or withdraw publication; operator-bound revisions remain protected. Global reader profiles keep their built-in global scope; team/user profiles keep their admitted team scope. A permission ceiling does not convert a global reader into a team role. Create the user with the appropriate built-in scope before binding a profile. ## Console workflow In **Console users**, use **Custom role ceilings** to create or edit a definition. Choose its built-in ceiling and explicit permissions, then save. Select an existing compatible named user to assign the profile. The interface displays current sources/versions and the enforcement state; server-side checks remain authoritative. The binding objects of the API and the assignment body use `role_id`, the YAML name (the user and session objects keep `custom_role_id`, the role that applies to them). `PUT` with explicit `null` clears the binding as an administrator's deliberate override. `DELETE` removes the override and restores the declared YAML binding, if any. These actions have different effects: inspect the declared/current state before choosing one. A conflict preserves a draft only within the same authority. Reload and review before saving again. Known permission loss, a changed identity or a newer publication invalidates stale editing authority and discards one-time access state; restoring a flag alone does not resurrect an old writable response. ## Administrative API All endpoints below require a built-in global administrator. They use same-origin session/CSRF protection and return no credential, token, hash or session material. | Endpoint | Behavior | | --- | --- | | `GET /api/v1/admin/custom-roles` | Definitions, bindings, finite permissions, limits, sources and edit capability | | `PUT /api/v1/admin/custom-roles/{id}` | Upsert a complete restrictive definition | | `DELETE /api/v1/admin/custom-roles/{id}` | Remove the console override or restore its declared definition | | `PUT /api/v1/admin/users/{id}/custom-role` | Assign `role_id`, or explicitly clear it with `null` | | `DELETE /api/v1/admin/users/{id}/custom-role` | Revert the binding override to YAML | | `POST /api/v1/admin/custom-roles/adopt-base` | Adopt the operator's reviewed declared base | Every writer includes the current global `version` and `expected_base_fingerprint` from the catalog. Binding writers also include the user's current `user_version`. Definition `PUT` supplies a complete `role` with all five definition fields, whose `id` matches the URL. Successful writes return204; fetch fresh versions before another mutation. Use **API access** for complete login and `curl` examples that fetch real IDs and versions. A malformed request is400, incompatible role/binding422, denied authority403, missing resource/disabled writer404, and stale version/base or a referenced role409. Storage/synchronization failures return503; reload before retrying because a change may have committed. These responses are not interchangeable with a new authorization grant. ## Revocation, declared changes and recovery Role, state, memberships, binding and role permissions are read from PostgreSQL for each named request. They are not embedded as authoritative grants in a cookie or an optional inference-key cache. Revoking a right affects the existing cookie on the next request, across replicas. A response already admitted/transmitted is not retracted. Qualified key mutations revalidate the current ceiling under the same locks as the affected write. A writer waiting on a user lock cannot commit using a permission removed before it acquires authority. Scheduled activation checks the actor's current custom rights again when due: withdrawn rights block that job without retiring the current credential. See [key rotation](/docs/features/key-rotation/#scheduled-activation). The first admitted declared base is persisted. Later YAML drift is visible through fingerprints and requires explicit adoption; removing a binding from a file cannot silently restore built-in privileges before that review. Users potentially bound by the old or new base fail closed while authority is unresolved. A console-null mask is different from malformed or missing persisted authority. All declared and override references remain protected, including dormant YAML bindings hidden by a console override. A referenced role cannot be deleted or changed incompatibly. Review/adopt the intended YAML change and remove or rebind its users before deleting the remaining definition. Ordinary user/SCIM updates cannot silently clear an incompatible custom restriction. If a changed YAML file removes a role that a console binding still references, adoption is rejected and the base mismatch blocks ordinary override edits. Restore the last valid YAML base first, restart with that matching base, and repair or clear the affected bindings using current administrative versions. Then reapply the intended YAML change and adopt its reviewed fingerprint. There is no force-adoption option that bypasses references or restores privileges. For a locked-out named user, use the unbound global administrator, inspect the role/base/binding and restore a valid definition, adopt the reviewed base, or deliberately clear/revert the binding under current administrative checks. Do not edit authority JSON directly or restore an old backup to bypass revocation. A damaged authority state is denied, not treated as an unrestricted user. ## Upgrade Back up PostgreSQL and apply the custom-role migration through the existing [migration procedure](/docs/operate/operations/). Upgrade every replica before enabling these flags or persisting definitions/bindings; older binaries cannot enforce the new authority profile. Follow the backup/configuration rollback procedure instead of mixing older identity writers. The accepted built-in OIDC/SAML/SCIM identity contracts remain unchanged: a custom name from an identity-provider claim does not assign a role. Bind the existing local identity explicitly. Inference keys remain governed by their own identity, model/route, team and financial contracts. # Request rate limits **Last updated:** 2026-11-26T03:21:52-03:00 (UTC-3) Rate policies cap admitted inference requests. They do not count tokens, estimate cost or grant access to a model. [Budgets and TPM](/docs/features/budgets-and-tpm/) cover those separate limits; [access control](/docs/features/access-control/) still applies before model admission. The gateway uses shared PostgreSQL counters and the database clock. Replicas share a policy's ceiling. A rejected admission consumes no slot in its own transaction; it does not refund an earlier, separate admission phase. Concurrency policies remain process-local and are labeled separately in the console. ## Defaults and profiles No policy means no request ceiling from this subsystem. The following new flags default tofalse; staging a policy does not activate its flag or grant identity/model permission. | Flag | Enables | Prerequisite | | --- | --- | --- | | `rate_limits` | Existing shared request counter admission | Configured PostgreSQL | | `model_rate_limits` | Global requests to one canonical public model alias | `rate_limits` | | `key_model_rate_limits` | Requests to that alias from one key | `rate_limits` | | `long_window_rate_limits` | New model-policy windows of1hour or1day | `rate_limits`, plus the applicable model scope flag | | `rate_policy_management` | Existing API/console policy management | UI, identity and team management; an authorized administrator | The first two model-scope flags are independent: enabling key×model limits does not require a global model policy. Flags are operator controls; tenant entitlements never turn off an operator's active ceiling. Vendor classification can additionally restrict configuration writes without stopping established inference on license expiry. | Profile | Required scope fields | Limit | Window | | --- | --- | --- | --- | | `tenant` (T168, `organizations`) | Organization ID | `rpm` only, one counter for every key of the organization's teams; no `max_concurrent` | Fixed UTC minute | | Legacy `key`, `team`, `end_user` | Existing `subject_id` | `rpm`0..1000000; zero requires an applicable nonzero concurrency cap | Fixed UTC minute, unchanged | | `model` | `subject_id`: canonical exact alias | `requests_per_window`1..1000000 | `1m` default, `1h` or `1d` | | `key_model` | `subject_id`: key ID; `model_id`: canonical exact alias | `requests_per_window`1..1000000 | `1m` default, `1h` or `1d` | A new model policy has effective RPM and concurrency equal tozero; positive legacy limits cannot be combined with it. Rawzero remains an unset value for existing Go serialization. `model_id` is reserved for the compound profile. The creation preset shown in the console is not a default ceiling: no policy is created automatically. Disabled policies do not admit or charge requests. Model references must identify a current canonical exact alias. An `alias_of` request resolves to that canonical model, so a transparent alias does not provide another counter. Wildcard patterns/dynamic wildcard aliases are outside this profile. A key policy applies an additional restriction; it does not authorize the key to use the model. ## What consumes a slot The two admission groups have explicit ordering: 1. Existing key/team/end-user RPM runs during caller admission, before parsing the requested model. Existing behavior for invalid bodies and process-local concurrency is preserved. A transcript upload (`POST /v1/traces`, [agent runs](/docs/features/agent-recognition/#send-a-transcript)) takes one slot in these same key, team, organization and end-user counters, after its key and scope are checked and before its body is read; concurrency caps and the model policies of group 2 do not apply to it. 2. New matching model/key×model policies run after authorized canonical resolution, before model work. All matching policies and windows in this group admit atomically; one refusal rolls back every increment in that group. A later model refusal can therefore consume a prior legacy RPM slot. This is not an all-or-nothing transaction across the two groups. Use a model policy when the ceiling is specifically about admitted requests to that alias. Cache hits count. Retries and provider-target fallback within the admitted alias do not add another model admission. Semantic fallback to another alias and actual internal inference have their own canonical admission. Auto-routing admits its public router alias before classification and the selected destination before that destination does work; the same canonical alias is counted once per request. A selected-destination refusal can occur after classifier work, so its cost is not promised to be zero. The existing moderation guardrail exception applies to both rate groups, avoiding a rate refusal that would bypass the guardrail. Chat, translated/native JSON and multipart inference, native Gemini and token-count operations use their authorized canonical ingress. Realtime checks the new group per generated response; it does not add a model slot merely for upgrading the WebSocket or issuing a client secret. Existing handshake/per-response legacy RPM remains unchanged. Resource-only file/container/conversation/fine-tuning lifecycle operations and video polling/deletion keep their existing legacy checks; the gateway does not infer a requested model from an account resource. ## Declarative configuration This fragment assumes that `chat-default` is an existing canonical alias in the same complete configuration. Replace it with your actual alias. The global policies below apply simultaneously; either refusal rolls back the new group's increments. ```yaml features: rate_limits: true model_rate_limits: true key_model_rate_limits: false long_window_rate_limits: true rate_policies: - id: chat-minute subject: model subject_id: chat-default requests_per_window: 60 window: 1m disabled: false - id: chat-hour subject: model subject_id: chat-default requests_per_window: 600 window: 1h disabled: false ``` | Key | What it does | | --- | --- | | `rate_policies[].id` | Unique identifier of the policy, used by the console, the API and the `429` answer | | `rate_policies[].subject` | What the ceiling counts: `key`, `team`, `end_user`, `tenant`, `model` or `key_model` (table above) | | `rate_policies[].subject_id` | The ID of that subject: key, team, organization or canonical alias | | `rate_policies[].model_id` | For `key_model` only: the canonical alias the key is limited on | | `rate_policies[].rpm` | Requests per fixed UTC minute for the legacy and `tenant` profiles | | `rate_policies[].requests_per_window` | Requests per window for the `model` and `key_model` profiles, 1–1,000,000 | | `rate_policies[].window` | `1m` (default), `1h` or `1d`; the longer windows need `long_window_rate_limits` | | `rate_policies[].disabled` | `true` keeps the policy without admitting or charging requests through it | | `rate_policies[].mode` | `enforce` (default) refuses past the limit; `observe` counts and reports without refusing ([below](#observe-only-policies)); needs `rate_limit_observe_mode` | For a compound policy, select an existing declared or active managed key ID, set `subject: key_model`, keep the key ID in `subject_id`, and put the canonical alias in `model_id`. Enable `key_model_rate_limits`. Never use a cleartext API key as `subject_id`. YAML is the base. The authorized versioned API and **Rate policies** console can create/update a validated PostgreSQL override; removing an override explicitly restores its declared YAML base when one exists. This does not revoke a key, change model access or migrate counter history to another identity. A changed policy scope/window/limit has a distinct counter identity; editing it can start a new bucket. Review limit changes as operational changes, rather than treating them as a harmless rename. ## Observe-only policies Try a limit before enforcing it. With the operator flag `rate_limit_observe_mode` (off by default; requires `rate_limits`), a policy with `mode: observe` takes its slot in the same shared counter as an enforced one, but never refuses: a request past the limit is admitted, and counted as one the policy *would have limited*. Watch it for a few days, then set `mode: enforce` (or remove the line): the counter and its history stay the same, because the mode is not part of the counter's identity. ```yaml features: rate_limits: true model_rate_limits: true rate_limit_observe_mode: true rate_policies: - id: chat-hour-trial subject: model subject_id: chat-default requests_per_window: 600 window: 1h mode: observe ``` Where the would-limit requests are reported: | Where | What | | --- | --- | | `GET /api/v1/admin/rate-policies/status?status_version=2` and **Rate policies** | `mode: "observe"`, `would_limit` (this window) and `would_limit_15m` (the windows that started in the last 15 minutes; the current window alone for a `1h` or `1d` policy); `used` can exceed the limit | | `/metrics` and OTLP | `gateway_rate_limit_would_limit_total{policy}` | | Logs | A `rate_limit_would_limit` line per policy at most once a minute on each replica, with `policy_id`, `subject`, `window`, `would_limit` (the requests past the limit since the previous line) and the IDs of the request that wrote it | | The request span | `rate_limit_would_limit`: the observed policies the request went past | | [Alert channels](/docs/features/alerting/#events) | The `rate_limit_would_limit` event, at most once per policy every 15 minutes, with the subject, the limit and the window (never an end user); a replica offers it once per policy and bucket, so a policy far below real traffic costs no write per request | - **What it applies to:** request counts (`rpm`, `requests_per_window`) of every profile. A concurrency cap (`max_concurrent`) is always enforced; a policy that has one cannot observe (`422`). - **Mixed groups:** an enforced policy in the same admission group still refuses; a refused request counts for no policy of its group, observed ones included. The key, team and end-user group is admitted before the model group ([what consumes a slot](#what-consumes-a-slot)): a request past an observed key or team policy and then refused by an enforced model policy has taken its slot and is reported as would-limit by the first group. - **Without the flag** a configuration with `mode: observe` is refused, so turning the flag off cannot silently start enforcing an observed policy: set the policies to `enforce` or remove them first. - **Old replicas** do not read `mode` and would enforce the policy: roll every replica to this release before writing `mode: observe`. ## API and console Use the current version from `GET /api/v1/admin/config` when calling `PUT /api/v1/admin/rate-policies/{id}`. The request contains `version` and the typed `policy` (with `mode` for an [observe-only policy](#observe-only-policies)); session authentication, CSRF, role permissions, current subject/model authority and feature-aware licensing are checked server-side. A stale version returns409. Reload and review the change before saving again; the console does not silently adopt a newer version for an old draft. The following complete example requires `curl`, `jq`, a current console cookie jar/CSRF token and an existing canonical alias. It creates a model-hour override; it does not enable flags automatically. ```sh BASE_URL="${BASE_URL:-http://localhost:8080}" : "${COOKIE_JAR:?Set the path to your authenticated console cookie jar}" : "${CSRF_TOKEN:?Set the CSRF token from that console session}" : "${MODEL_ID:?Set an existing canonical exact alias}" POLICY_ID='model-hour' VERSION=$(curl --fail-with-body -sS --cookie "$COOKIE_JAR" \ "$BASE_URL/api/v1/admin/config" | jq -er '.version') jq -n --arg id "$POLICY_ID" --arg model "$MODEL_ID" \ --argjson version "$VERSION" \ '{version:$version,policy:{id:$id,subject:"model",subject_id:$model, requests_per_window:600,window:"1h",disabled:false}}' | curl --fail-with-body -sS --cookie "$COOKIE_JAR" \ -X PUT "$BASE_URL/api/v1/admin/rate-policies/$POLICY_ID" \ -H "X-CSRF-Token: $CSRF_TOKEN" -H 'Content-Type: application/json' \ --data-binary @- curl --fail-with-body -sS --cookie "$COOKIE_JAR" \ "$BASE_URL/api/v1/admin/rate-policies/status?status_version=2" ``` `GET /api/v1/admin/rate-policies/status?status_version=2` is the supported mixed-window status contract. Dynamic per-end-user counters remain excluded instead of being shown as misleading aggregate headroom. It identifies the configuration version and each row's scope, unit, limit, start and reset. `observed_at` is the database observation time; it is null when shared rate limits are off, without affecting optional process-local concurrency reporting. The console validates that identity against its current configuration before showing usage/remaining. Missing, stale, denied or failed observations are unavailable, not zero. The defaultV1 response remains the legacy minute/concurrency view for compatible older clients and identity details; it is not a complete model-window report. Parameter metadataV14 defines the new form's typed bounds/defaults and distinguishes a creation preset from an operational default. A missing/malformed descriptor or write-capability projection makes the new controls unavailable; it never grants permission. Existing legacy controls retain their established contract. The [Swagger contract](/docs/api/) describes request/response fields and the same-origin endpoint explorer provides runnable examples. ## Failure, reset and operations A full matching bucket returns `429 rate_limit_exceeded` with `Retry-After` derived from its fixed UTC reset; the gateway does not sleep or invoke a provider to satisfy admission. The answer names the policy that refused, so the caller knows which ceiling it hit and when to come back: ```json {"error": {"code": "rate_limit_exceeded", "message": "Inference request limit exceeded: policy chat-minute allows 60 requests per minute; it resets at 2026-11-26T15:04:00Z"}} ``` The message gives the policy `id`, its limit, its window (`per minute`, `per hour` or `per UTC day`) and the reset in UTC. It is the same on every route a policy counts: chat, Responses, Messages, embeddings, Gemini, token counts, the other inference routes, passthrough, agent transcript uploads (which count in the key's requests-per-minute policies only), and each Realtime response (the `error` event's `message`, with `retry_after`). Only the refusing policy is named, and it is always one that matched the caller's own key, team, end user, organization or model; the message never carries a counter, another subject's ID or the end-user value. An end-user policy adds `(per end user)`: the limit is each end user's, and the message does not say which end user. When several policies are full at once, one of them is named: the key, team, end-user and organization policies are checked first, then the model policies. Budget and token refusals name their policy the same way ([budgets and TPM](/docs/features/budgets-and-tpm/)). Database/repository failure returns503 when an applicable ceiling cannot be proven. No counter decision depends on an observer, browser clock, Collector or Grafana. Daily buckets reset at00:00UTC, hourly buckets at the UTC hour and minute buckets at the UTC minute. These are aligned windows, not rolling durations from the first request. Pruning preserves every active supported bucket. A restart or another replica does not provide extra slots; the database is authoritative. Upgrade and stop every old replica/worker before enabling new profile flags. Older binaries do not enforce these fields or flags, and their minute-counter cleanup can delete an active daily bucket older than one hour; mixed old/new enforcement is not supported. Preserve the normal PostgreSQL/configuration backup and roll back configuration together with an older binary. This feature reuses the existing counter table; it does not require a new schema migration. No managed-cloud, optional-adapter or paid-provider certification is implied by local PostgreSQL validation. A model-policy denial records the already-authorized canonical model and the request/trace IDs, without inventing a provider attempt, reported tokens or spend. Use the returned `X-Request-Id` and `traceparent` to correlate the decision with the request explorer/OTLP journey. A counter observation and a provider execution receipt are different evidence. # SSO login (OIDC) **Last updated:** 2026-11-21T08:59:43-03:00 (UTC-3) Optional [federated MFA policy](/docs/features/federated-mfa/) adds signed assurance and login-time freshness checks to configured legacy or named providers. SSO by itself is not MFA. Policies and their durable epochs are managed separately from issuer/client trust; local login paths retain their own controls. Console users sign in with their corporate account (Google, Keycloak, Okta, authentik, Auth0, or any OpenID Connect provider), with no new password to manage. The gateway never sees the user's password and never returns provider tokens to the browser. Flag: `oidc_login`. What SSO does **not** do: grant a role or access. Whoever signs in is a local gateway user, with the role and teams an admin assigned. The provider's email, domain, groups, and roles do not promote anyone. | Related feature | Flag | Guide | | --- | --- | --- | | Restrict login to IdP groups | `oidc_group_policy` | [Groups](/docs/features/oidc-groups/) | | End the console session when the IdP logs out | `oidc_backchannel_logout` | [Logout](/docs/features/oidc-logout/) | | Also sign out of the IdP when signing out of the console | `oidc_rp_logout` | [Logout](/docs/features/oidc-logout/#sign-out-of-the-console-and-the-idp) | | Create and deactivate users from the IdP | `scim` | [SCIM](/docs/features/scim/) | The existing `admin.oidc` profile remains supported unchanged. [Named providers](/docs/features/oidc-providers/) add an opt-in multi-provider path; its explicit mapping does not inherit the legacy SCIM externalId or JIT lookup. Their [Google/Microsoft setup](/docs/features/oidc-vendors/) has separate named-vendor admission switches and exact trust requirements; those switches do not disable this legacy singleton. ## How to turn it on ```yaml features: ui: true console_users: true oidc_login: true # boot admin: oidc: label: Corporate SSO issuer_url: https://identity.example.com/realms/company client_id: ai-gateway client_secret_env: GATEWAY_OIDC_CLIENT_SECRET redirect_url: https://gateway.example.com/api/v1/admin/auth/oidc/callback allowed_endpoint_origins: [] allow_loopback_http: false subject_users: immutable-idp-subject: usr_0123456789abcdef0123456789abcdef ``` - `oidc_login` is a boot flag and requires PostgreSQL. This legacy profile uses one issuer. To offer several providers side by side, use [named OIDC providers](/docs/features/oidc-providers/); each profile has its own trust and explicit local-user links. - The client secret lives in an environment variable or Secret, never in the YAML or the browser. - `subject_users` links the provider's `sub` to a local user (the `usr_…` ID appears in **Console users**). With [SCIM](/docs/features/scim/), the link comes from provisioning and the map can stay empty; the SCIM link wins over the map. - Local login and the admin bootstrap token keep working, for recovery. The console shows the SSO button on the login screen with the configured `label`. ### `admin.oidc` reference Every key is boot trust: set it in the YAML and roll the gateway out. | Key | Default | What it does | | --- | --- | --- | | `label` | required | Text of the SSO button, 1–80 bytes | | `issuer_url` | required | The provider's issuer, compared byte for byte with the token's `iss` (keep a trailing slash if the provider publishes one); HTTPS, no credentials, query or fragment | | `client_id` | required | The confidential client registered at the provider, at most 512 bytes | | `client_secret_env` | required | Name of the environment variable (or Secret key) that holds the client secret; the value must be at least 8 bytes | | `redirect_url` | required | The callback registered at the provider; its path must be `/api/v1/admin/auth/oidc/callback` on the console origin | | `post_logout_redirect_url` | empty | Where the provider sends the browser after an RP-initiated logout; must be on the console origin | | `allowed_endpoint_origins` | `[]` | Up to 8 extra exact HTTPS origins (no path) the discovery document may point token and JWKS endpoints to | | `allow_loopback_http` | `false` | Allows `http://localhost` for local development only; also requires `admin.allow_insecure_http: true` and a loopback redirect | | `subject_users` | `{}` | Map of the provider's immutable `sub` to an existing `usr_…` ID, 1–1000 entries unless `scim` or `federated_jit` links users | | `session_epoch` | empty | 1–64 identifier characters; changing it ends every console session this provider created | ### Keycloak - A confidential OIDC client, with Standard Flow and PKCE S256 required. - Only the exact redirect URI above, no wildcard. - The realm's exact issuer, with `/realms/`. Keycloak can broker Google social login; in that case the gateway trusts Keycloak's issuer. ### Google directly A web-type OAuth client, with the exact callback: ```yaml issuer_url: https://accounts.google.com allowed_endpoint_origins: - https://oauth2.googleapis.com - https://www.googleapis.com ``` Allow only the origins that discovery publishes (token and JWKS live on other hosts). Domain wildcards are not accepted. The gateway requests only the `openid` scope. ### authentik and Auth0 The issuer may end in `/` (`…/application/o//` in authentik, `https://tenant/` in Auth0). In authentik, configure an **RSA signing key** on the OAuth2 provider: without it, the ID token is signed with HS256, which the gateway refuses. ### Local development HTTP only with `allow_loopback_http: true`, `admin.allow_insecure_http: true`, and a callback on `localhost` or a loopback IP. A private-network host is not an exception. Never in production. ## How it works - **Flow:** Authorization Code with PKCE S256, `state` and `nonce`, discovery, and JWKS. The code is exchanged on the backend. - **Identity:** the issuer + `sub` pair. The `sub` is immutable; the email is not used as a shortcut. - **ID token validation:** RS256, ES256, or PS256 signature via JWKS, exact issuer, audience, expiration, subject, and nonce. - **Session:** the user's role, teams, and status are reread from PostgreSQL on every request. Deactivating the user or changing the role takes effect on the next request. - **Configuration change:** changing the issuer, client, endpoints, redirect, secret, or links invalidates federated sessions. - **Failure:** the browser goes back to `/ui/#login=failed`, with a generic message; API calls get a JSON 401. Provider details do not leak. Endpoints: | Endpoint | What it does | | --- | --- | | `GET /api/v1/admin/auth/providers` | Minimal public list `{providers:[{id,label,login_url}]}`; empty with the flag off | | `GET /api/v1/admin/auth/oidc/start` | Starts the login and redirects to the provider | | `GET /api/v1/admin/auth/oidc/callback` | Receives `code` and `state`, creates the session, and returns to `/ui` | The flow cookie is encrypted (AES-GCM), HttpOnly, SameSite=Lax, valid for five minutes, and contains no tokens. No provider token is stored. ## Limits - Up to four simultaneous callbacks per process; the excess gets 503 and the user tries again. - Discovery, token, and JWKS: HTTPS on the issuer's origin or on the explicit list, no redirects, 8 s per HTTP call, 10 s in total, up to 1 MiB. - Signing out of the console ends the local session. To reflect a logout done in the IdP, turn on [backchannel logout](/docs/features/oidc-logout/); to also sign out of the IdP, [RP logout](/docs/features/oidc-logout/#sign-out-of-the-console-and-the-idp). - This legacy singleton was tested against real Keycloak 26.4 and authentik 2025.10. The separate [named Google/Microsoft profiles](/docs/features/oidc-vendors/) have real Web-client/account qualification; that does not retrospectively certify this singleton or Okta. - First-login user creation is opt-in: [JIT provisioning](/docs/features/jit-provisioning/) creates a pending user, with the user role and no teams, for allowlisted identities; or use [SCIM](/docs/features/scim/). For a SAML-only IdP, see [SAML](/docs/features/saml/). ## See also - [Access control](/docs/features/access-control/): roles and permissions. - [Security](/docs/security/security/). - References: [Google OpenID Connect](https://developers.google.com/identity/openid-connect/openid-connect), [Keycloak OIDC](https://www.keycloak.org/securing-apps/oidc-layers), [RFC 9700](https://www.rfc-editor.org/rfc/rfc9700.html). # Multiple OIDC login providers **Last updated:** 2026-11-21T08:59:43-03:00 (UTC-3) A separate [federated MFA catalog](/docs/features/federated-mfa/) can require signed context/method proof and authentication freshness for an existing profile. It does not add fields to the original five-field named-provider policy. Changes invalidate the affected MFA authority without granting a role or altering another provider. Offer several corporate sign-in buttons on the console login screen. Each named provider has its own issuer, client, callback and explicit links to existing gateway users. Up to eight named profiles coexist with the existing single [OIDC](/docs/features/oidc/) and [SAML](/docs/features/saml/) logins. Named OIDC is a separate, opt-in feature; an empty configuration changes no existing login. This profile implements standard OpenID Connect. Its local qualification uses Keycloak 26.4.0 and PostgreSQL 16.15, two gateway processes and two real realms with deliberately equal subjects. The two isolated IdP instances are test infrastructure, not a deployment requirement: multiple realms on one IdP are supported with their own real subjects. [Native Google/Microsoft profiles](/docs/features/oidc-vendors/) additionally have real Web-client/account qualification; this is separate evidence from Keycloak. GitHub user OAuth is not OIDC and is not supported by this native profile; the owner removed that separate delivery from the T085 requirement. ## Enable and configure | Setting | Default | Purpose | | --- | --- | --- | | `features.oidc_providers` | `false` | Enable the configured named login profiles | | `features.oidc_provider_management` | `false` | Permit global administrators to edit their access policies | | `features.google_oidc_login` | `true` | Standby admission for official Google named profiles; parent/runtime and explicit local links still required | | `features.microsoft_oidc_login` | `true` | Standby admission for official organizational-tenant Microsoft named profiles | | `admin.oidc_providers` | `[]` | Boot-admitted provider trust and declared access policies | Named runtime also requires `ui`, `console_users` and `oidc_login`, the existing session signing key, PostgreSQL and the secret for each configured client. A named-only deployment needs no legacy `admin.oidc`. Management can stage a declared provider while named runtime is off. Flags enable behavior; they never grant a local role, membership or custom permission. ```yaml features: ui: true console_users: true oidc_login: true oidc_providers: true oidc_provider_management: true admin: allow_insecure_http: false oidc_providers: - id: employees label: Employee sign-in disabled: true issuer_url: https://identity.example.com/realms/employees client_id: gateway-console client_secret_env: GATEWAY_EMPLOYEE_OIDC_SECRET redirect_url: https://gateway.example.com/api/v1/admin/auth/oidc/employees/callback allowed_endpoint_origins: [] allow_loopback_http: false post_logout_redirect_url: https://gateway.example.com/ui session_epoch: initial-v1 subject_users: {} group_policy: null ``` Each entry of `admin.oidc_providers` (at most 8) takes these keys. Trust keys are boot-only; the access policy keys (`label`, `disabled`, `session_epoch`, `subject_users`, `group_policy`) can also be replaced from the console or the API, see below. | Key | Default | What it does | | --- | --- | --- | | `id` | required | Lower-case identifier of the profile; it is part of its callback path and never changes | | `issuer_url` | required | The provider's issuer, compared byte for byte with the token's `iss`; HTTPS, at most 2048 bytes | | `client_id` | required | The confidential client registered at the provider, at most 512 bytes; an active issuer/client pair may appear only once | | `client_secret_env` | required | Name of the environment variable or Secret key that holds the client secret (at least 8 bytes) | | `redirect_url` | required | The registered callback, exactly `/api/v1/admin/auth/oidc//callback` on the console origin | | `post_logout_redirect_url` | empty | Where the provider returns the browser after an RP-initiated logout; must be on the console origin | | `allowed_endpoint_origins` | `[]` | Up to 8 extra exact HTTPS origins (no path) for the provider's token and JWKS endpoints | | `allow_loopback_http` | `false` | `http://localhost` for local development only, together with `admin.allow_insecure_http: true` | The example stages a disabled provider without fabricating a user link. Create the confidential OIDC client, require Standard Flow and PKCE S256, and register the exact callback and optional post-logout URL. Put its secret in the referenced environment variable or an existing Kubernetes Secret. Create the local user in **Console users**, obtain its gateway-generated ID and the immutable `sub` from the trusted IdP. Add that exact subject→user link, then enable the provider. Do not use an email address as a substitute for `sub`. Local HTTP is limited to explicit loopback development with both `allow_loopback_http: true` and `admin.allow_insecure_http: true`. It is not a private-network or production exception. Endpoint origins are exact HTTPS origins, not wildcard domains. Discovery, token and JWKS requests do not follow redirects. ## What can change without restart **Console users → Named OIDC providers** and the administrative API expose the same declared/effective policy, override, source, current generation, version and base fingerprint. | Fields | Change procedure | | --- | --- | | `label`, `disabled`, `session_epoch`, `subject_users`, `group_policy` | Complete versioned policy replacement through console/API, or reviewed YAML baseline | | ID, issuer, client ID, secret reference, redirect, endpoint origins, loopback and post-logout redirect | Boot trust: edit YAML and restart; shown read-only/restart-required in the console/API | | Secret value | Operator-owned Secret/ENV; never returned by a read or export | A policy replacement supplies all five mutable fields. `group_policy: null` explicitly clears it; otherwise it contains `claim`, `match` (`any` or `all`) and `required_groups`. An enabled provider requires at least one valid explicit local-user link. With `oidc_group_policy` enabled, every active named provider also needs its explicit valid group restriction. Groups restrict sign-in; they do not assign access. Only a builtin global administrator with current `oidc_providers:manage` authority may access the management API. Custom role ceilings and classified enterprise write restrictions still apply. An operator, viewer or team administrator does not inherit this authority. Mutations require CSRF and current version/base guards, validate the whole resulting configuration and record a correlated metadata-only audit event. A stale version or unreviewed baseline drift is a conflict. Validation, authorization and CAS failures change no policy. If the database commit succeeds but the local configuration refresh fails, `503 configuration_sync_pending` explicitly means the policy **was committed**: read the catalog before attempting another mutation; do not replay the previous PUT blindly. A console override takes precedence over the declared YAML policy. **Revert** removes an existing override and returns to the declared policy; it does not delete the boot provider or its users. **Adopt base** explicitly accepts a reviewed changed YAML baseline. Do not use adoption to bypass reviewing the complete declared provider set. A trust change or ID addition/removal uses a coordinated restart and reviewed base adoption; authentication remains closed while authority is unresolved. Client secrets are captured by the named runtime generation. Replacing material under the same secret reference does not change a callback midway. Every secret-material rotation **and rollback requires a deliberate `session_epoch`/security-generation change**. Deliver the intended material and coordinate replicas so they use the same trust, epoch and current secret. A restart applies material but is never a substitute for durable revocation; restarting with an old secret and unchanged epoch is not a supported rotation/rollback procedure. A label edit does not recapture secret material or revoke sessions. Preserve recovery access through an authorized named administrator or the explicitly configured bootstrap flow. ## API operations All paths below have versioned canonical URLs. The **API access** menu contains runnable examples that discover the current ID and version rather than embedding a real secret or fictional user. | Method and path | Result | | --- | --- | | `GET /api/v1/admin/auth/providers` | Anonymous, minimal `{id,label,login_url}` list | | `GET /api/v1/admin/auth/oidc/{id}/start` | Browser redirect, with a provider-specific encrypted flow cookie | | `GET /api/v1/admin/auth/oidc/{id}/callback` | Same-browser code/state callback; verified local session | | `POST /api/v1/admin/auth/oidc/{id}/backchannel-logout` | Optional authentic IdP-signed logout, scoped to that provider | | `GET /api/v1/admin/oidc-providers` | Private administration catalog | | `GET /api/v1/admin/oidc-providers/{id}` | Declared/effective/override policy and boot trust detail | | `PUT /api/v1/admin/oidc-providers/{id}` | Complete mutable-policy replacement | | `DELETE /api/v1/admin/oidc-providers/{id}` | Remove an existing policy override | | `POST /api/v1/admin/oidc-providers/adopt-base` | Adopt the reviewed declared baseline | The PUT body is `{version, expected_base_fingerprint, provider}`. DELETE and adoption take `{version, expected_base_fingerprint}`. Successful writes return 204: fetch the current catalog afterward. Reads are private/no-store; public login metadata includes no issuer, client/secret reference, subject map or administration fetch. The browser renders labels as text and accepts only exact same-origin provider start paths. ## Identity, session and logout isolation The callback verifies the selected issuer, sole client audience, optional authorized-party claim, signature, expiry, nonce, PKCE, browser state and current durable provider generation. A present authorization-response `iss` must match that issuer before code exchange. If trusted discovery declares support for this parameter, a missing `iss` is also refused. Different providers have different callback paths, flow cookies and cryptographic binding domains; parallel browser flows cannot borrow another provider's state. Named identities resolve **only** through that provider's current `subject_users` map. Two realms with the same subject or email can map to different local users. There is no email/domain merge, global SCIM `externalId` lookup, claim-to-role grant or automatic JIT creation on this path. An administrator may explicitly link an existing SCIM-created local user; that user's current active state remains authoritative. The [legacy JIT](/docs/features/jit-provisioning/) and singleton OIDC behavior are unchanged. Security edits advance persistent generations. Disable/re-enable, flag off/on, removal/recreation, mapping or group changes and baseline security drift cannot revive old flows or sessions by restoring an earlier value. Local role, membership, disabled state and custom ceilings are checked against current storage. A delayed discovery or callback cannot issue authority after its generation is withdrawn. Label-only edits retain sessions. Optional [RP and backchannel logout](/docs/features/oidc-logout/) select the authenticated named provider. Another provider and legacy/local-token sessions are independent. A logout token does not contain the gateway generation: a database-clock `iat` fence also considers the verifier's existing 30-second positive clock-skew allowance. Consequently, backchannel tokens are conservatively refused for up to 31 seconds after a security-generation change. This is a timestamp/skew safeguard, not cryptographic proof of when the token was minted; an IdP retry is not promised. Configuration-triggered session invalidation is immediate, and local/RP sign-out remains available. The tested [Keycloak logout profiles](/docs/features/oidc-logout/#named-providers-and-the-tested-keycloak-profile) distinguish session-specific notifications from subject-wide logout. Configure that distinction at the IdP; the gateway never guesses which unnotified sessions to revoke. The named issued-at precheck matches the existing SQL five-minute-plus30second past and30second future fence; nonce/state freshness and durable authority remain independent checks. A failed new login preserves a valid earlier session, with an explicit [console warning and finite diagnostics](/docs/features/oidc-vendors/#failed-sign-in-and-diagnostics). A page that still opens under the earlier cookie is not evidence that the new provider succeeded. ## Limits and failure behavior - At most eight named providers; IDs match `[a-z][a-z0-9_-]{0,63}` and cannot be `oidc` or `saml`. Reject duplicate IDs and duplicate active issuer/client pairs, including the legacy profile. - Labels: 80 UTF-8 bytes. Security epochs: 1–64 ASCII letters, digits, `_` or `-`. - Up to 1,000 subject links per provider, each subject at most 255 UTF-8 bytes. Local user IDs are generated by the gateway. - Up to 20 required groups, 256 UTF-8 bytes each, with a top-level claim name at most 64 bytes; reserved identity/security claim names are refused. - At most eight extra trusted endpoint origins per provider. Management JSON is limited to 1 MiB. The API publishes the exact current limits. - Existing bounded OIDC discovery, JWKS, token, callback admission and cancellation rules apply. Discovery failure, malformed state, invalid local authority or PostgreSQL outage issues no session. A flag or hidden button is never the authorization boundary. Request IDs and W3C trace context correlate safe start/callback activity, outbound calls and administrative audits. A newly issued named flow encrypts its origin IDs. After validating the callback flow, the contextual `oidc_callback_origin` event joins `origin_request_id`, `origin_trace_id` and `origin_span_id` to the callback’s own IDs. Existing JSON and OTLP log export carry these fields; this profile does not claim a separate OTLP span-link implementation. OAuth codes/state, verifiers, cookies, tokens, claims, secrets and subject maps are never telemetry payloads. See [OIDC](/docs/features/oidc/), [groups](/docs/features/oidc-groups/), [logout](/docs/features/oidc-logout/), [access control](/docs/features/access-control/), [configuration parity](/docs/reference/configuration-parity/) and the [OpenAPI contract](/docs/api/). # Google and Microsoft console login **Last updated:** 2026-11-13T20:33:20-03:00 (UTC-3) Use [named OIDC providers](/docs/features/oidc-providers/) to offer Google and Microsoft Entra ID beside other corporate login buttons. They reuse the gateway's server-side authorization-code flow, PKCE S256, state, nonce, signed ID-token validation and current local-user authority. No provider password or token is returned to the console. **Qualified profile:** real Google Web OAuth and Microsoft Entra organizational-tenant Web application logins were verified through the compiled gateway, PostgreSQL and the owner's Chrome on macOS. Each created its own expected viewer session; independent validation checked the current provider/generation, user and role, per-vendor flag isolation, CSRF and correlated request/trace metadata. The Microsoft run exercised the existing past clock-skew allowance. This does not certify Microsoft common/consumer/B2C/sovereign authorities, every tenant policy, or the final complete release. An enabled flag, configured secret or available button alone is not evidence of a valid login. ## Defaults and operational controls | Setting | Default | Effect | | --- | --- | --- | | `features.oidc_providers` | `false` | Parent switch for all named login profiles | | `features.google_oidc_login` | `true` | Admit official Google **named** profiles while the parent is enabled | | `features.microsoft_oidc_login` | `true` | Admit official single-tenant Microsoft **named** profiles while the parent is enabled | | `features.oidc_provider_management` | `false` | Allow current global administrators to manage declared profiles' access policies | The vendor switches are standby capabilities: their default does not configure a client or expose a login on its own. Use the existing **Settings & sources → Features** controls or versioned feature API for runtime changes, or set the same booleans in YAML. Edition-manifest defaults remain configurable at build time. False hides and denies the matching named login, rejects callbacks and invalidates that vendor's named sessions. Restoring it permits new sign-ins; it does not revive old sessions. Other named providers keep their sessions. A policy can still be reviewed while its vendor switch is off. These switches do not control the separate legacy `admin.oidc` singleton. Migrate that trust to a named entry if vendor-specific admission is required; never assume that turning off a named switch disables every legacy federation path. Flags do not grant roles, memberships or permission to manage federation. Named session admission uses the existing atomic PostgreSQL timestamp fence: an issued-at value no older than five minutes plus 30 seconds of skew and no more than 30 seconds in the future. The gateway applies the same precheck; it does not replace signature/nonce, the five-minute browser flow, current identity/generation checks or logout tombstones. Microsoft can backdate the issued-at claim: the verified real session used this allowance. Keep machine/database time synchronized; increasing a proxy timeout does not repair a stale or invalid assertion. These protocol checks are distinct from the local session's lifetime and an operator's client-secret expiry policy. ## Google Web OAuth client 1. In [Google Cloud credentials](https://console.cloud.google.com/apis/credentials), configure consent/branding and create a **Web application** OAuth client. An external application in testing needs an allowed test account. 2. Register the exact named callback, for example `https://gateway.example.com/api/v1/admin/auth/oidc/google/callback`. Scheme, host, port, path and trailing slash matter. This server-side flow needs no browser JavaScript origin. 3. Put the client secret in an operator-owned environment/Secret reference. Keep the secret out of YAML values, API examples, logs and screenshots. 4. Declare the disabled profile below, create the intended local user, then add its explicit immutable Google `sub` link and enable the profile through the named policy editor/API or reviewed YAML. ```yaml features: ui: true console_users: true oidc_login: true oidc_providers: true oidc_provider_management: true google_oidc_login: true admin: oidc_providers: - id: google label: Continue with Google disabled: true issuer_url: https://accounts.google.com client_id: YOUR_GOOGLE_WEB_CLIENT_ID client_secret_env: GATEWAY_GOOGLE_OIDC_SECRET redirect_url: https://gateway.example.com/api/v1/admin/auth/oidc/google/callback allowed_endpoint_origins: - https://oauth2.googleapis.com - https://www.googleapis.com allow_loopback_http: false session_epoch: google-v1 subject_users: {} group_policy: null ``` The issuer is configured exactly as shown. Its origin is implicit; the token and JWKS origins must be explicitly admitted. Other origins, wildcard hosts and noncanonical spellings are refused for an active official profile. Discovery and backend requests do not follow redirects. Google documents two possible ID-token issuer values: `https://accounts.google.com` and `accounts.google.com`. Only this named official Google profile accepts the bare alias, after cryptographic verification. It keeps one canonical private issuer/session namespace. This does not relax issuer checking for another provider or the legacy singleton. See [Google's OIDC contract](https://developers.google.com/identity/openid-connect/openid-connect). The gateway requests only `openid`; it does not request profile, email, offline access or call userinfo. Email, hosted-domain hints and display names never replace `sub`. Standard Google ID tokens do not provide this gateway's configurable group restriction; use a broker that supplies the required signed group claim when that restriction is needed. A global group policy cannot be bypassed by this profile. Google RISC and provider-wide logout are separate protocols, not implied by OIDC login or the gateway's generic logout routes. ## Microsoft Entra Web application 1. In [Microsoft Entra app registrations](https://entra.microsoft.com/), create an application for **accounts in this organizational directory only**. Use the public-cloud tenant's immutable lowercase GUID. 2. Add the **Web** platform and register the exact callback, such as `https://gateway.example.com/api/v1/admin/auth/oidc/microsoft/callback`. Keep implicit access/ID-token grants and public-client fallback disabled; this is a confidential authorization-code flow. 3. Create a client secret with the lifetime your operator chooses and store its value in the referenced Secret. No Microsoft Graph application/delegated permissions are required by this gateway's `openid` login. An organization's consent/assignment policies may still require its administrator. 4. Stage the profile below; replace the example tenant/client with your real application, then explicitly link its verified `sub` to an existing local user before enabling it. ```yaml features: microsoft_oidc_login: true admin: oidc_providers: - id: microsoft label: Continue with Microsoft disabled: true issuer_url: https://login.microsoftonline.com/11111111-2222-3333-4444-555555555555/v2.0 client_id: YOUR_ENTRA_APPLICATION_CLIENT_ID client_secret_env: GATEWAY_MICROSOFT_OIDC_SECRET redirect_url: https://gateway.example.com/api/v1/admin/auth/oidc/microsoft/callback allowed_endpoint_origins: [] allow_loopback_http: false session_epoch: microsoft-v1 subject_users: {} group_policy: null ``` Combine entries in the same `admin.oidc_providers` list and retain the parent flags from the Google example. Each ID determines its own callback. Adding a boot entry/issuer/client/secret reference requires a coordinated restart and reviewed baseline adoption; the API/console does not create external applications or silently expand network trust. The active issuer must be exactly `https://login.microsoftonline.com//v2.0`. The verified ID token's `tid` must match that tenant, in addition to signature, issuer, sole audience, authorized party when present and nonce checks. There is no `common`, `organizations`, `consumers`, tenant-domain alias, B2C or sovereign-cloud fallback in this profile. The consumer-account tenant is excluded; a permitted guest authenticates in the configured organizational tenant. Several explicitly configured tenant profiles form a bounded allowlist; they do not turn `common` into an unrestricted issuer. Microsoft `sub` is application-specific. Neither Graph `oid`, an email nor a username is a substitute. Signed groups may restrict an existing user's sign-in when the application emits the configured claim. Missing/overage group claims cannot be replaced by a Graph lookup or used to grant a local role. See [Microsoft's ID-token claims](https://learn.microsoft.com/en-us/entra/identity-platform/id-token-claims-reference) and [authorization-code flow](https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow). ## Explicit identity links, testing and recovery Obtain `sub` from a trusted, cryptographically verified identity assertion or the corresponding trusted existing IdP link. Do not decode an unverified token and treat it as identity, paste tokens into third-party decoders, or configure a placeholder email/ID. Google/Microsoft API keys used for model inference are unrelated to Web OAuth client credentials. Until the exact subject is linked to an active local user, the named callback grants no console session and creates no user automatically. For an isolated local test, use the exact callbacks `http://localhost:8845/api/v1/admin/auth/oidc/google/callback` and `http://localhost:8845/api/v1/admin/auth/oidc/microsoft/callback`, with a free owned port, `admin.allow_insecure_http: true` and that profile's `allow_loopback_http: true`. Register the same URLs at the IdP. Production keeps HTTPS; a private-network hostname is not a loopback exception. An operator supplies the OAuth clients, account consent and PostgreSQL; selecting this configuration does not provision them. Use a dedicated temporary OAuth client where possible. When deliberately adding a test redirect to an existing client, preserve every existing URI and secret; remove only the added URI afterwards. Delete only test-owned applications/secrets. Actual account login is performed by the account owner. Test successful login and denied identity, flag off/on without session resurrection, another provider's isolation and current local-user revocation. Record real-vendor proof separately from deterministic fixtures. The console's **Console users → Named OIDC providers** review shows the exact callback, `openid` scope, tenant where applicable and the effective named-vendor switch. These are configuration facts, not health indicators. Immutable trust stays read-only/restart-required; the existing five-field policy replacement, source, CAS/version/base adoption, audit, secret handling, correlation and failure semantics remain in the [named-provider contract](/docs/features/oidc-providers/). Keep a separate authorized recovery login before changing any federation policy. ## Failed sign-in and diagnostics A failed attempt does not revoke a valid earlier session: an unauthenticated request must not be able to sign someone else out. The console instead shows **“Sign-in failed; current session unchanged.”** when the failed-login response returns to an authenticated console. The notice survives navigation within that mounted console until explicit dismissal or a successful sign-in/new document; it is not stored across hard reloads. The prior user's role and permissions remain in force. Opening `/ui` alone therefore never proves that a requested new identity succeeded. Named callback failures emit the contextual `oidc_login_failed` event with finite `stage` and `cause`. Token exchange retains only the sanitized status/allowlisted OAuth code. `session_record` with `record_iat_too_old` or `record_iat_future` distinguishes the issuance fence from a signature, nonce, identity or current-authority failure. Raw claims, timestamps, subjects, callback URLs, tokens, codes and provider error bodies are not diagnostic payloads. Use request/trace correlation with the existing [log conventions](/docs/features/observability/); do not paste OAuth callback URLs into support reports. `/ui` and `/ui/` are supported aliases of the same renderer and CSP; both use the same `#/analytics` fragment. A trailing slash is unrelated to the selected identity or its permissions. For qualification, inspect the actual current provider/user session and authorization result, rather than relying on an open analytics page. # Require MFA proof from a federated identity provider **Last updated:** 2026-11-21T10:44:38-03:00 (UTC-3) Use an explicit assurance policy to require stronger authentication on a configured OIDC or SAML console login. The gateway verifies signed proof from the identity provider before granting a session; a successful SSO redirect, a requested authentication context or a configured feature flag is not proof of MFA. This feature covers federated login only. Local named-user credentials and the bootstrap recovery login remain separate paths. Native TOTP, passkeys and recovery codes are delivered separately: see [native MFA](/docs/features/native-mfa/). Preserve an authorized recovery administrator before changing federation. **Qualification:** the real Keycloak26.7.5 profile passed on two native gateway replicas with PostgreSQL and Chrome: password-only signed OIDC/SAML proof was denied, actual password + OTP admitted the linked viewer, and policy/flag changes revoked matching sessions without reviving saved cookies. Named and legacy OIDC plus SAML were exercised; an unprotected password-only neighbor retained its existing behavior. The Settings editor also passed real API write/readback and stable desktop1440/mobile390 inspection without hidden fields or horizontal overflow. This is focused T086.001 qualification, separate from final complete-branch release qualification. Microsoft Entra MFA-specific certification is pending a licensed/configured Conditional Access tenant. Earlier Google/Microsoft sign-in qualification does not certify MFA. ## Defaults and policy semantics | Parameter | Default | Meaning | | --- | --- | --- | | `features.federated_mfa` | `false` | Operator switch for enforcing configured requirements | | `admin.federated_mfa` | `[]` | No provider requirements configured | | `admin.federated_mfa[].provider_id` | Required | Existing named OIDC ID, `oidc` for the legacy singleton, or `saml` | | `admin.federated_mfa[].oidc.context_claim` | `acr` | Inspect the signed scalar `acr` or explicit signed array `acrs` | | `admin.federated_mfa[].oidc.allowed_acr` | `[]` | At least one exact listed context must match when configured | | `admin.federated_mfa[].oidc.required_amr` | `[]` | Every listed method must appear in signed `amr` when configured | | `admin.federated_mfa[].saml.allowed_authn_contexts` | Required | At least one exact allowed class reference | | `admin.federated_mfa[].oidc.max_auth_age_seconds`, `admin.federated_mfa[].saml.max_auth_age_seconds` | `null` | Optional freshness at callback; `null` omits the age condition | A policy has exactly one `oidc` or `saml` object. OIDC requires at least one context or method requirement: freshness alone is not MFA. Configured context and method dimensions combine with **AND**; context alternatives use **ANY**, required methods use **ALL**. Values are case-sensitive, bounded, unique and matched exactly. There is no inferred ordering between assurance strings, no role assignment from claims and no automatic interpretation of arbitrary method names as two factors. The operator must configure the IdP so an admitted context or method combination actually requires the intended factors. For example, an AMR mapper must report authenticators the user completed, rather than attach a constant `mfa` claim to every login. Accepting `pwd` alone does not establish a strong-authentication policy. A provider without a requirement retains its existing authentication behavior. A provider with a configured requirement **denies login and its affected sessions when `federated_mfa` is off**. Turning the flag off is not a way to bypass a required factor. Authorized administrators can still inspect, stage or revert policies while the runtime switch is off. The catalog exposes limits: at most 10 policies, 16 contexts or methods per list, 256 UTF-8 bytes per nonempty value, and authentication age from 0 to 86,400 seconds. A provider can appear only once and must already exist in the trusted configuration. This feature never creates an IdP, cloud application, user or provider trust. ## Declare a requirement After configuring an existing named OIDC provider `work` and its explicit user links, add: ```yaml features: federated_mfa: true admin: federated_mfa: - provider_id: work oidc: context_claim: acr allowed_acr: [] required_amr: [pwd, otp] max_auth_age_seconds: 300 ``` This example requires both actual password and OTP authenticator references from the trusted IdP. It is not portable merely because another IdP uses the same words. For Keycloak, configure the authentication executions' reference values and the built-in AMR protocol mapper for ID tokens. Do not use a static user attribute as proof that an OTP challenge occurred. To use context instead, configure an IdP flow that binds a reviewed context to strong authentication and set `allowed_acr` to its exact returned value. Both dimensions can be configured if the IdP emits both. Missing, wrongly typed or insufficient signed proof denies the login. For an existing SAML provider whose authentication flow genuinely requires the configured assurance context: ```yaml admin: federated_mfa: - provider_id: saml saml: allowed_authn_contexts: [https://refeds.org/profile/mfa] max_auth_age_seconds: 300 ``` Combine policies in the same list. The URI must be supported and correctly bound by your IdP; this example does not add that mapping. The gateway requests exact context comparison and verifies the returned class inside the selected signed assertion. Ambiguous statements or contexts are rejected; no favorable statement is selected from several alternatives. ## Configure an IdP that reports completed factors For the Keycloak profile used in qualification, the browser flow has a level-one subflow that executes the username/password authenticator and a level-two subflow that executes the OTP authenticator. Both levels use the conditional level-of-authentication execution. Map the OIDC client contexts `silver` to level1 and `gold` to level2; configure the strong request to require `gold`. Users must enroll their own OTP credential through the IdP's protected enrollment procedure before using that strong flow. Set the completed password authenticator's reference value to `pwd`, the completed OTP authenticator's reference value to `otp`, and add Keycloak's built-in AMR mapper to the **ID token**. Add its ACR mapper for the achieved context. Configure the gateway with `allowed_acr: [gold]` and `required_amr: [pwd, otp]`. This requires both the achieved level and the executed methods, rather than a constant user attribute. Keycloak's administrative API may mask authenticator reference settings; a masked read is not evidence of completed authentication. For SAML, bind PasswordProtectedTransport to the password level and `https://refeds.org/profile/mfa` to the OTP level in the client's context-to-level mapping, enable the achieved-context mapper and sign both the response and assertion as required by the [SAML profile](/docs/features/saml/). The gateway policy accepts only the strong URI. An unsigned change to the outbound request must never make the gateway accept a weaker signed response. These mappings are operator choices for an IdP flow whose authenticators were reviewed. They do not establish equivalent strength on another product or version. Validate actual password-only denial, real OTP success and the resulting current local-user session before enabling the policy for production users. Keep a separate authorized recovery path available. ## Authentication freshness and session lifetime OIDC freshness uses signed `auth_time`; SAML uses the signed authentication statement's `AuthnInstant`. Token issue time (`iat`), local browser time, userinfo and unsigned attributes are not substitutes. The requirement is checked at callback with the documented 30-second clock-skew allowance, independently of signature, audience, nonce/state, current user and provider-generation checks. `max_auth_age_seconds: 0` requests fresh authentication; it does not disable the condition. OIDC sends `max_age=0`; SAML requests `ForceAuthn` when an age requirement is present, since SAML has no identical `max_age` request parameter. The gateway still verifies the returned signed proof. An IdP that ignores a request hint cannot thereby bypass admission. This is a **login-time freshness** condition. It does not shorten the existing local session lifetime or silently implement periodic step-up on every console action. Policy, account, role and revocation changes continue to apply to live authority. ## Console and API management In **Settings & sources**, use the dedicated federated MFA policy editor beside the existing federation controls. Only a built-in global administrator with `federated_mfa:manage` can access this private catalog. A feature flag never grants that permission. The editor presents only already configured providers and their supported protocol, plus effective policies, YAML/console source, runtime-switch state and write authority. The separate catalog preserves the existing OIDC and SAML policy DTOs: | Method | Versioned route | Action | | --- | --- | --- | | GET | `/api/v1/admin/security/federated-mfa` | Read declared/effective/override policies, limits, defaults, source, epochs and access | | PUT | `/api/v1/admin/security/federated-mfa` | Replace the complete policy list | | DELETE | `/api/v1/admin/security/federated-mfa` | Remove an existing console override and restore the YAML base | | POST | `/api/v1/admin/security/federated-mfa/adopt-base` | Explicitly acknowledge the reviewed declared base | Mutation bodies use strict JSON with a 256 KiB limit (`413` when exceeded). Mutations require the current global control `version`, `expected_base_fingerprint`, same-origin session/CSRF and current write authority. GET the catalog immediately before preparing a mutation. PUT uses `{version, expected_base_fingerprint, federated_mfa}`; revert/adoption use the two guard fields only. The **API access** page provides runnable examples that read the current guards instead of embedding a fictitious version. A version/base conflict is `409`: reload and review before resubmitting. Malformed or noncanonical input, duplicate policies and structural/bounds violations are `400`; otherwise canonical policies incompatible with current provider references/configuration are `422`; unauthorized access is `403`; missing current authority/storage is `503`. If a mutation committed but synchronization is pending, read the current catalog before deciding whether to retry. A successful write returns `204` and is audited with request/trace correlation. There is no raw token, OTP, assurance-claim payload or provider credential in the catalog. ## Revocation and upgrades MFA authority uses a durable per-provider epoch. Newly issued federated session markers bind provider, epoch and the existing inner identity. Each federated session read and RP logout consults current database authority, including a process whose captured configuration has no requirement; another replica cannot silently bypass a newly added policy. Policy changes and relevant flag transitions revoke affected flows/sessions. Removing a policy or restoring a flag does not revive older cookies. Before a provider has ever acquired MFA policy, pre-upgrade unwrapped sessions can retain the prior compatibility path; after its epoch advances, those older markers remain denied. Other providers and the local recovery path retain their own authority checks. Upgrade every gateway replica while quiesced before activating this policy. Older binaries neither enforce these requirements nor understand the new federated marker. Back up the database and preserve session/encryption trust as described in the [operations guide](/docs/operate/operations/). A rollback must follow the documented migration/authority procedure; do not run older writers against the changed schema or present a mixed-version rollout as MFA protection. ## Microsoft Entra-specific boundary The native Microsoft sign-in profile uses a tenant-specific public-cloud v2 issuer. That alone does not establish MFA. Microsoft documents authentication contexts through the signed optional `acrs` claim; a context may be satisfied without an attached Conditional Access policy, so its mere presence is insufficient. For `context_claim: acrs`, the tenant administrator must bind each permitted context to an **enforced** Conditional Access MFA or authentication-strength policy, assign the intended application/account and configure the relevant ID-token claims. Tenant/account licensing, administrator rights, consent and registered factors are operator prerequisites. No Graph lookup or role promotion supplies missing proof. The available test tenant had no subscribed SKUs for this validation. The owner accepted real Keycloak qualification and left Entra MFA vendor certification pending. This does not remove the already tested Microsoft login, and it does not claim that an untested tenant policy works. Use [Microsoft's authentication-context guide](https://learn.microsoft.com/en-us/entra/identity-platform/developer-guide-conditional-access-authentication-context) and [optional-claims reference](https://learn.microsoft.com/en-us/entra/identity-platform/optional-claims-reference). The standard claim semantics are in [OpenID Connect Core](https://openid.net/specs/openid-connect-core-1_0.html). Configure [named OIDC trust](/docs/features/oidc-providers/), [Google/Microsoft login](/docs/features/oidc-vendors/) and [SAML trust](/docs/features/saml/) separately from these assurance requirements. # Native console MFA **Last updated:** 2026-11-27T14:16:11-03:00 (UTC-3) Native MFA adds a second factor after the console's first factor: an authenticator-app code (TOTP, RFC 6238), a passkey (WebAuthn), or a one-time recovery code. It protects console identity only; inference API keys, model requests and provider authentication are unchanged. For proof of MFA performed by an identity provider, see [federated MFA](/docs/features/federated-mfa/); both can apply to the same sign-in. Once an identity has a confirmed factor, every sign-in for it needs that factor: the shared admin or viewer token, a named user's personal token, OIDC (legacy and named providers) and SAML. A successful first factor opens only a restricted pending flow; the normal session cookie is issued when the second factor succeeds. The MFA response never grants a role, permission or team: the session has exactly the identity's existing authority. ## Enable it All four switches default to `false`. The method switches have no effect without `local_mfa`. | Flag | What it enables | | --- | --- | | `local_mfa` | Native MFA state, policy and the pending sign-in | | `local_totp` | Authenticator-app enrollment and verification (needs the provider encryption key) | | `local_webauthn` | Passkeys for an already identified user (needs `admin.local_mfa.webauthn` trust) | | `local_mfa_recovery` | One-time recovery codes | ```yaml features: local_mfa: true local_totp: true local_webauthn: true local_mfa_recovery: true storage: provider_encryption_key_env: GATEWAY_PROVIDER_ENCRYPTION_KEY # factor secrets are encrypted with it admin: local_mfa: required_roles: [admin] webauthn: rp_id: gateway.example.com origins: [https://gateway.example.com] ``` Turning a switch off never makes an enrolled or required identity sign in with one factor: its sign-in is refused (`403 native_mfa_unavailable`) until a usable method is back or an administrator resets it. Turn `local_mfa` off only after removing requirements and factors you no longer want. Authenticator secrets and passkey credentials are encrypted with the provider encryption keyring (labels `native-mfa:v1:::`) and are included in `gateway reencrypt`. Losing that key makes stored factors unreadable; affected users then need a reset. ## Policy fields `admin.local_mfa` is the YAML base. **Settings → Console MFA** and `PUT /api/v1/admin/security/local-mfa` store a complete override (current global `version` and `expected_base_fingerprint` required); `DELETE` returns to YAML. The WebAuthn block is boot trust: it is read only from YAML, never from a request's `Host` or forwarded headers, and changing it needs a restart. | Field | Default | Bounds and meaning | | --- | --- | --- | | `admin.local_mfa.required_roles` | `[]` | Built-in roles that must use MFA: `admin`, `viewer`, `operator`, `user`, `team_viewer`, `team_admin`, `org_admin` (an [organization admin](/docs/features/organization-admins/), with `organization_admins`). A custom role uses its base role | | `admin.local_mfa.protect_bootstrap` | `false` | Require MFA for the shared admin token. It also blocks that token's Bearer path | | `admin.local_mfa.protect_shared_viewer` | `false` | Same for the shared viewer token | | `admin.local_mfa.challenge_ttl` | `5m` | `30s`–`15m`; pending sign-in, TOTP enrollment and passkey prompt lifetime | | `admin.local_mfa.fresh_proof_ttl` | `5m` | `30s`–`15m`; lifetime of the one-use proof for a sensitive change | | `admin.local_mfa.enrollment_ticket_ttl` | `1h` | `5m`–`72h`; administrator reset ticket lifetime | | `admin.local_mfa.max_attempts` | `5` | `1`–`10` failed proofs per identity, across methods and replicas | | `admin.local_mfa.attempt_window` | `5m` | `30s`–`1h`; window that counts failures | | `admin.local_mfa.lockout_duration` | `5m` | `30s`–`1h`; even a right code is refused during the lockout (`429 mfa_locked`, `Retry-After`) | | `admin.local_mfa.max_pending_per_principal` | `3` | `1`–`10`; oldest pending sign-ins (and session prompts) beyond it are dropped | | `admin.local_mfa.max_pending_total` | `10000` | `100`–`100000`; beyond it new sign-ins get `503 mfa_capacity` | | `admin.local_mfa.max_passkeys` | `10` | `1`–`20` per identity | | `admin.local_mfa.recovery_code_count` | `10` | `5`–`20` codes per batch | | `admin.local_mfa.totp.issuer` | `m7gtw` | 1–80 bytes, no control characters or `:` | | `admin.local_mfa.totp.algorithm` | `SHA1` | `SHA1`, `SHA256`, `SHA512` | | `admin.local_mfa.totp.digits` | `6` | `6` or `8` | | `admin.local_mfa.totp.period_seconds` | `30` | `15`–`120` | | `admin.local_mfa.totp.skew_steps` | `1` | `0`–`2` adjacent timesteps accepted for clock drift | | `admin.local_mfa.webauthn.rp_id` | `""` | Lowercase DNS name or `localhost`; empty admits no passkey ceremony | | `admin.local_mfa.webauthn.origins` | `[]` | 1–8 exact `https://host[:port]` origins of `rp_id` or its subdomains; `http://localhost:` only with `admin.allow_insecure_http` | | `admin.local_mfa.webauthn.display_name` | `m7gtw` | 1–80 bytes shown by the browser | The TOTP algorithm, digits and period are stored with each factor: changing them affects new enrollments only. Most authenticator apps support only the defaults. Passkeys need a DNS name (not an IP address) as the relying party. When a policy write makes a role or shared token required, the time is recorded in PostgreSQL. Sessions issued before it are refused from then on and do not come back if the requirement is later removed. A write that would require MFA for the saving administrator without a usable method is refused with `422`. ## Sign in 1. The first factor answers `202` instead of a session: ```json {"authenticated": false, "stage": "verify", "purpose": "login", "methods": ["totp", "webauthn", "recovery"], "enroll_methods": ["totp", "webauthn"], "expires_at": "2026-11-14T16:05:00Z", "challenge_csrf_token": "", "principal_kind": "user"} ``` An HttpOnly, SameSite=Strict `gateway_mfa_pending` cookie binds the flow to this browser. OIDC and SAML callbacks redirect to `/ui/#login=mfa` (or `/ui/#login=mfa_unavailable` when the identity cannot use any method). `GET /api/v1/admin/session` returns the same `202` view, so a reload resumes the flow. 2. Pending calls send `X-MFA-Challenge: `: - `verify` stage: `POST /api/v1/admin/mfa/verify {"method":"totp","code":"123456"}`, `{"method":"recovery","code":"mfar_..."}`, or the passkey pair `POST /mfa/webauthn/authenticate/options` then `/finish {"credential": {...}}`. - `enroll` stage (a required identity without a factor): `POST /mfa/totp/begin` then `/mfa/totp/confirm {"factor_id","code"}`, or `/mfa/webauthn/register/options` then `/finish {"name","credential"}`. The first factor also returns the initial recovery codes once. - `ticket` stage (after an administrator reset): `POST /mfa/enrollment-ticket {"ticket":"mfae_..."}`, then enroll. - `POST /mfa/cancel` retires the pending flow only. 3. Success answers `{"authenticated": true, "csrf_token": "...", "mfa_method": "totp"}` and sets the normal session cookie; `/session` then reports `mfa_method`. A pending flow can only add the identity's first factor; once a factor exists, other pending flows of the same identity must verify it. Each TOTP timestep is accepted once per identity across all replicas, and each recovery code once. Every attempt, right or wrong, is counted before it is checked, so parallel guesses cannot exceed `max_attempts`. ## Manage your factors **Account security** (every console role, from a browser session) shows your factors, how this session was verified and the recovery codes left (`GET /api/v1/admin/mfa`). Enrolling the first factor needs no extra step; the session is reissued under the protected identity and other sessions opened with the first factor alone end. Removing a factor, replacing the recovery codes or adding another factor need a fresh proof: `POST /mfa/challenge {"purpose":"manage"}`, then a `verify` or passkey proof with the session's `X-CSRF-Token`. That proof grants one credit for `fresh_proof_ttl`; it never performs the change. Then `DELETE /mfa/totp`, `DELETE /mfa/passkeys/{id}` or `POST /mfa/recovery-codes`. Removing a factor ends every session verified before it; removing your last factor signs you out. A required identity cannot remove its last factor (`409 mfa_required`). ## Reset by an administrator A global administrator (`native_mfa:manage`) sees a user's status on **Console users → MFA** (`GET /api/v1/admin/users/{id}/mfa`, counts only) and can reset it with the user's current `version` (`POST /api/v1/admin/users/{id}/mfa/reset`). The reset deletes the user's factors and recovery codes, ends its sessions and returns a one-time `mfae_` ticket valid for `enrollment_ticket_ttl`. The user signs in with the first factor, presents the ticket (accepted for one pending sign-in) and must enroll a new factor; a reset never leaves the account with one factor. Administrators cannot reset their own factors; they use Account security. Hand the ticket over privately; it is not stored in clear or logged. Resets are audited as `native_mfa.reset`. The shared admin and viewer tokens have no administrator above them. If their factors and recovery codes are lost, an operator with the configuration and database runs: ```sh gateway native-mfa-reset --principal shared:admin --apply ``` It prints the ticket once as JSON (`--principal` also accepts `shared:viewer` or a `usr_` ID). The ticket lifetime is the YAML `enrollment_ticket_ttl`. There is no HTTP bypass. ## Upgrade and operations Migrations 140 and 141 add the factor, recovery, pending-flow and requirement tables and the policy override. Every session read now consults the identity's MFA state in PostgreSQL, including shared-token sessions and the shared-token Bearer path; when that state cannot be read, the request answers `503 authentication_state_unavailable` instead of being admitted. Older binaries ignore native factors, so upgrade every replica before enrolling anyone. Logs carry `native_mfa_verified`, `native_mfa_failed` (with a finite reason), `native_mfa_locked`, `native_mfa_enrolled`, `native_mfa_removed` and `native_mfa_reset` with the request ID; codes, secrets, tickets, challenges and WebAuthn parser errors are never logged. Identity audit rows record enrollment, removal, recovery use and regeneration, and resets. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `GET /api/v1/admin/security/local-mfa` | The YAML base, console override and effective MFA policy, with defaults and bounds | | `DELETE /api/v1/admin/security/local-mfa` | Removes the console override of the MFA policy | | `POST /api/v1/admin/mfa/challenge` | Opens a proof flow for a signed-in session; a verified factor then earns one credit for removing a factor, replacing recovery codes or adding another | | `POST /api/v1/admin/mfa/cancel` | Abandons a pending sign-in flow and clears its cookie; no session is revoked | | `POST /api/v1/admin/mfa/enrollment-ticket` | Redeems the one-time `mfae_` ticket an administrator issued after resetting the identity, so it can enroll again | | `POST /api/v1/admin/mfa/totp/begin` | Creates a pending authenticator app and returns its secret, URI and QR code once | | `POST /api/v1/admin/mfa/totp/confirm` | Activates the pending app with a code; the first factor also returns the recovery codes once | | `DELETE /api/v1/admin/mfa/totp` | Removes the authenticator app with a fresh proof, ending every session proven before | | `POST /api/v1/admin/mfa/webauthn/register/options` | Starts registering a passkey for the identity | | `POST /api/v1/admin/mfa/webauthn/register/finish` | Verifies and stores the new passkey | | `POST /api/v1/admin/mfa/webauthn/authenticate/options` | Starts a passkey proof for the identity already identified by its first factor | | `POST /api/v1/admin/mfa/webauthn/authenticate/finish` | Verifies the passkey proof: completes the sign-in or earns a fresh-proof credit | | `DELETE /api/v1/admin/mfa/passkeys/{id}` | Removes one passkey with a fresh proof | | `POST /api/v1/admin/mfa/recovery-codes` | Replaces the recovery codes with a fresh proof and returns the new batch once | # Group-restricted OIDC login **Last updated:** 2026-11-21T10:44:38-03:00 (UTC-3) Only people in the right IdP groups get into the console. With `oidc_group_policy`, the gateway reads the groups claim from the ID token and denies login to anyone who is not on the list. It is one more gate: the local user binding is still required, and the group does not create a user, grant a role or change teams. ## How to turn it on On top of a complete [SSO](/docs/features/oidc/) configuration: ```yaml features: oidc_group_policy: true # boot; requires oidc_login admin: oidc: session_epoch: groups-reviewed-v1 group_policy: claim: groups match: any # or all required_groups: [/gateway-users, /gateway-operators] ``` | Field | Rule | | --- | --- | | `session_epoch` | Required. An identifier of 1 to 64 characters (`A-Z`, `a-z`, digits, `_`, `-`); see [rollout](#rollout) | | `admin.oidc.group_policy.claim`, `admin.oidc_providers[].group_policy.claim` | Literal name of a top-level claim, 1 to 64 characters. No JSONPath: a dot is part of the name. Identity, protocol and roles claims are reserved | | `admin.oidc.group_policy.match`, `admin.oidc_providers[].group_policy.match` | `any` (one group is enough) or `all` (all of them) | | `admin.oidc.group_policy.required_groups`, `admin.oidc_providers[].group_policy.required_groups` | 1 to 20 unique groups, up to 256 bytes each | The comparison is **exact**: case-sensitive, with no prefix, regex or hierarchy. Use the full path the IdP emits (in Keycloak, `/gateway-users`). In the IdP, emit the groups claim **in the ID token**. In Keycloak, use the group membership mapper and check the names. **Settings & sources** shows whether the policy is on and whether it needs a rollout. The policy does not appear in logs, exports or public discovery. ## How it works - The claim must be a list of up to 128 strings, with no repeats. Missing, null, a bare string, an object or a mixed list deny the login. - Signature, issuer, audience, nonce and the local binding are verified before the groups. - A failure returns the generic login error, without exposing the groups. - **The check happens at login.** Removing someone from the group in the IdP does not end an open session. For that, use [backchannel logout](/docs/features/oidc-logout/), deactivate the local user or require a new login. ## Rollout 1. In a test environment, check the claim the IdP actually emits, without logging ID tokens. 2. Choose a **new** `session_epoch` and keep a local administrative access path for emergencies. 3. Publish the policy, the flag and the same epoch on all replicas. 4. Require a new login and confirm acceptance and denial with test users. 5. To roll back, advance or preserve the epoch deliberately. Never go back to an old epoch while cookies from that time may still be valid. Changing the policy or the epoch invalidates flows and sessions created under the previous configuration. ## Limits - It does not query an external directory: only the token's claim. Google Workspace groups and nested roles have not been validated. - A group does not become a role or a team. For teams coming from the IdP, use [SCIM groups](/docs/features/scim/#groups). - The group policy never creates a user. [JIT provisioning](/docs/features/jit-provisioning/) can, for allowlisted identities, after this policy admits the login. [SAML](/docs/features/saml/) login has no group restriction. ## See also - [SSO](/docs/features/oidc/) and [logout](/docs/features/oidc-logout/). - References: [OpenID Connect Core](https://openid.net/specs/openid-connect-core-1_0.html), [Keycloak protocol mappers](https://www.keycloak.org/docs/latest/server_admin/index.html). ## Typed policy and rollout `match` is required in a group-policy block and accepts only `any` or `all`; it has no implicit choice. The same typed backend constraint is used during configuration validation. A supplied group-policy object is validated even when its feature is disabled, while general OIDC trust retains its existing flag-dependent validation. Group names, claim restrictions and subject-to-local-user mapping remain separate rules. This adds no group-policy editor, applied-value summary or role grant; update the boot configuration and roll it out using the existing epoch procedure. # Logout with SSO **Last updated:** 2026-11-16T20:23:26-03:00 (UTC-3) Two logout directions for those who sign in to the console through [SSO](/docs/features/oidc/): | Feature | What it does | Flag | | --- | --- | --- | | **Backchannel logout** | The IdP notifies the gateway when the session ends there (logout, employee offboarding), and the console session drops on the next request, on any replica | `oidc_backchannel_logout` | | **Sign out of the console and the IdP** | When you click sign out, the console also ends the session at the IdP | `oidc_rp_logout` | Both affect only federated sessions. Local login, the bootstrap token and inference keys are not touched. ## Backchannel logout ### How to turn it on ```yaml features: oidc_login: true oidc_backchannel_logout: true # boot; requires PostgreSQL admin: oidc: # other OIDC login fields session_epoch: oidc-bc-rollout-v1 ``` `session_epoch` is required: an identifier of 1 to 64 characters (`A-Z`, `a-z`, digits, `_`, `-`). It is not a secret; it marks the generation of federated sessions (see [rollout](#rollout-and-rollback)). In the IdP client, register the URL: ``` https://gateway.example.com/api/v1/admin/auth/oidc/backchannel-logout ``` In Keycloak, configure the client's backchannel logout URL and include `sid` in the tokens to log out a specific session. If the IdP sends only `sub`, all of that user's sessions drop. Tested with Keycloak 26.4: an administrative logout in Keycloak brought down the console session on the next request. Google sign-in does not imply backchannel support. ### Named providers and the tested Keycloak profile For a [named provider](/docs/features/oidc-providers/), register `/api/v1/admin/auth/oidc/{id}/backchannel-logout` instead of the legacy singleton URL. Its durable provider generation isolates this client/issuer from other profiles; local and legacy sessions are not implicitly revoked. Named forms are limited to 20 KiB (the legacy form limit is 64 KiB); both keep the 16 KiB token limit. The validated Keycloak 26.4.0 profile supports two genuine notification shapes: | Intended action | Keycloak client/operation | Gateway result | | --- | --- | --- | | End one SSO session | **Backchannel logout session required** enabled; end that session through its Sessions view or a separate `DELETE /admin/realms/{realm}/sessions/{sid}` request | The signed `sub`+`sid` event revokes that session on both replicas; the other SSO session stays valid | | End every SSO session for this user/client | **Backchannel logout session required** disabled (`backchannel.logout.session.required=false`); administrative user logout | Keycloak sends a signed `sub`-only event; all matching user sessions in that named provider are revoked, while other profiles remain valid | Keep this distinction when configuring Keycloak 26.4.0. Its administrative user-logout loop can reuse one logout authentication context and deduplicate notifications by client: with session-required enabled and two SSOs, the observed run removed both IdP sessions but sent only one SID notification. The gateway correctly revoked only the notified session. The two configurations above were then tested with real signed notifications; no SID was discarded or replaced with a subject wildcard. See the pinned [logout context](https://github.com/keycloak/keycloak/blob/26.4.0/services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java#L320) and [client deduplication](https://github.com/keycloak/keycloak/blob/26.4.0/services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java#L479). A valid `200` acknowledges processing of a signed notification, including a notification whose session was already absent. It does not assert that the IdP notified every session. Preserve exact issuer/client/generation and every supplied `sub`/`sid`; never broaden a received SID event to work around missing IdP notifications. Named security changes also have the documented [timestamp/skew fence](/docs/features/oidc-providers/#identity-session-and-logout-isolation); this does not promise provider retries. ### How it works The IdP sends a `POST` with `Content-Type: application/x-www-form-urlencoded` and a `logout_token` in the body. The signed token is the authentication; there is no cookie or CSRF. The gateway validates: - an RS256, ES256 or PS256 signature against the login JWKS (never against keys indicated in the token itself), issuer, audience and `azp`; - `iss`, `aud`, `iat`, `exp`, `jti`, `events` with the backchannel logout event, and `sub` or `sid`; - the absence of `nonce`, which distinguishes the logout token from an ID token; - dates: `iat` at most 5 minutes in the past and at most 30 s in the future, `exp` in the future and up to 5 minutes after `iat`. Keep clocks synchronized. | Result | Response | | --- | --- | | Valid, even for a session that no longer exists | `200` | | Invalid token or repeated `jti` | `400` | | Flag off | `404` | | Capacity, JWKS or database unavailable | `503`; nothing is treated as done | After the logout: - the next request from that session is denied on any replica; requests already in progress may finish; - a login that was in progress at the time of the logout does not recreate the session; - the session cookie carries neither `sub`, `sid` nor tokens; the database stores only hashes. The federated session queries the primary PostgreSQL on every request. A lagging read replica does not work for this. ### Limits | Resource | Limit | | --- | --- | | Concurrent logouts per replica | 4; the excess gets 503 | | Form / token / token header | 64 KiB / 16 KiB / 2 KiB | | Total logout time | 10 s | | Sessions, replays and tombstones | up to 100,000 of each in the database | | Session duration | up to 8 hours | Cleanup of expired records happens alongside logins and logouts, without a dedicated process. When the ceiling is reached, new sessions fail closed instead of deleting valid protection. ### Rollout and rollback 1. Apply the migration (additive). 2. Enable it with a **new** `session_epoch`, the same on every replica. Federated users have to sign in again. 3. Register the URL in the IdP and test signature, audience, dates, `sid`/`sub` and retry. 4. To turn it off, **preserve** the epoch or advance to another new one. Never remove it or go back to an old value: that could re-enable old cookies still within their 8 hours. 5. When re-enabling, advance the epoch again. Never delete the revocation tables to work around an outage: revoked sessions could become valid again. ### Make the epoch monotonic `oidc_epoch_guard` (off by default; requires `oidc_login` and PostgreSQL; read at startup) turns step 4 from a procedure into a check: ```yaml features: oidc_login: true oidc_backchannel_logout: true oidc_epoch_guard: true admin: oidc: session_epoch: "2026-11-a" # advance to a never-used value; never go back ``` - At startup the gateway checks the epoch first and records it only after every other startup step has passed, so a startup that fails later never advances the history and never blocks a rollback to the epoch before it. It records a SHA-256 digest of `admin.oidc.session_epoch` (never the value) in `gateway_oidc_session_epochs`, in order, under a database lock, so replicas starting together agree on one order. - The **latest** epoch starts again. A **never-used** epoch becomes the latest and is logged as `oidc_session_epoch_advanced` with its sequence number. - An **earlier** epoch, or an **empty** one after any was recorded, stops startup with `oidc session epoch check failed`, before the server listens. Advance to a new value instead. - It covers the legacy `admin.oidc` profile; [named OIDC profiles](/docs/features/oidc-providers/) already keep monotonic database generations. - Turning the flag off skips the check (and records nothing) until it is on again; the recorded history stays and still applies when it is. - During a rolling update, replicas already running keep their epoch; a replica restarted with the old epoch after the new one was recorded is refused, which is the point. Roll forward, not back. - Migration 169 adds the table; nothing is written until the flag is on. ## Sign out of the console and the IdP With `oidc_rp_logout`, signing out of a federated session returns an `end_session_url` and the console navigates to it. The URL comes from the IdP's discovery (a trusted origin) and carries the `client_id` and, if configured, a `post_logout_redirect_uri` on the console's origin. The gateway does not store the ID token, so it does not send `id_token_hint`. Some providers ask for confirmation because of this (Keycloak asks "Do you want to log out?"), and those that require the hint keep their own session. ## General limits - No front-channel logout. [SAML](/docs/features/saml/) has no Single Logout. - The log records the request ID and the result, without IdP identifiers; it is not an immutable audit. ## See also - [SSO](/docs/features/oidc/) and [group-based login](/docs/features/oidc-groups/). - Specification: [OpenID Connect Back-Channel Logout 1.0](https://openid.net/specs/openid-connect-backchannel-1_0.html). # SSO login (SAML) **Last updated:** 2026-11-21T09:54:10-03:00 (UTC-3) Optional [federated MFA policy](/docs/features/federated-mfa/) requests an exact authentication context and checks the returned class and optional authentication freshness inside the selected signed assertion. This is distinct from assertion age and session lifetime; the existing SAML trust DTO remains unchanged. Console users sign in with a corporate SAML 2.0 identity provider (Keycloak, Microsoft Entra ID, Okta, ADFS, or any IdP that signs its responses). The gateway never sees the user's password. Flags: `saml_login` (the login itself) and `saml_management` (editing the trust from the API and console). SAML does not grant a role or team access. By default, sign-in resolves an existing local gateway user, with the role and teams an administrator assigned. Optional [JIT provisioning](/docs/features/jit-provisioning/) can create an allowlisted identity pending approval; only that profile reads its configured verified e-mail and group attributes. IdP role attributes never grant local roles. Prefer [OIDC](/docs/features/oidc/) when the IdP offers both: it is simpler to operate. Use SAML when the company requires it. ## How to turn it on ```yaml features: ui: true console_users: true saml_login: true saml_management: true # optional: edit the trust from the API/console admin: saml: label: Corporate SAML entity_id: https://gateway.example.com/saml acs_url: https://gateway.example.com/api/v1/admin/saml/callback idp_entity_id: https://identity.example.com/realms/company idp_sso_url: https://identity.example.com/realms/company/protocol/saml idp_signing_certificates_pem: - | -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- subject_users: persistent-name-id-from-the-idp: usr_0123456789abcdef0123456789abcdef session_epoch: 2026-11-rollout-1 ``` - Requires PostgreSQL and the console session key. Local login and the admin bootstrap token keep working, for recovery. - `acs_url` is HTTPS and its path is exactly `/api/v1/admin/saml/callback`. `idp_sso_url` is HTTPS. The gateway itself listens on HTTP behind your TLS ingress, as in any production profile. - `idp_signing_certificates_pem` pins up to eight IdP signing certificates (RSA, 2048 bits or more). A certificate in the response never adds trust. List the next certificate before the IdP rotates its key, then remove the old one. Responses with or without a KeyInfo certificate work during rotation; if the response and the assertion are signed by two different keys, the IdP must include KeyInfo. - `subject_users` binds the IdP's **persistent** NameID to an existing local user (the `usr_…` ID shown in **Console users**). Unmapped subjects are refused. Transient, email and unspecified NameID formats are refused. - `session_epoch` is a label you choose; changing it ends every SAML session. - The console shows the SAML button on the login screen with the configured `label`. With `saml_management`, **Settings & sources → SAML single sign-on** edits the same fields, and so does the API. Only a global administrator can read or change it. The console value overrides the YAML until you choose **Revert SAML to YAML**. Saving rejects a binding to a missing or disabled user. | Parameter | Default | Range | Meaning | | --- | --- | --- | --- | | `label` | `Corporate SAML` | up to 80 characters | Login button text | | `entity_id` | required | an absolute URI | The gateway's own SAML entity ID: the audience the assertion must name, and the Client ID at the IdP | | `acs_url` | required | HTTPS, path `/api/v1/admin/saml/callback` | Where the IdP posts its response | | `idp_entity_id` | required | an absolute URI | The IdP's entity ID, compared exactly with the response and assertion issuer | | `idp_sso_url` | required | HTTPS | The IdP's single sign-on address the login redirects to | | `request_ttl` | `5m` | 1m–10m | How long a started login waits for the IdP | | `assertion_max_age` | `5m` | 1m–10m | Oldest accepted response and assertion | | `clock_skew` | `30s` | 0s–2m | Tolerance for the IdP clock | | `max_response_bytes` | `262144` | 16 KiB–1 MiB | Largest decoded response | | `max_xml_tokens` | `20000` | 1000–50000 | Largest XML document, in tokens | | `max_concurrent_callbacks` | `4` | 1–64 | Responses validated at once per process; the excess gets 503 | ### Keycloak Create a SAML client whose **Client ID** is `entity_id`, then set: - **Valid redirect URIs** and **Assertion Consumer Service POST Binding URL**: the exact `acs_url`. - **Name ID format** `persistent`, with **Force name ID format** on. - **Sign documents** and **Sign assertions** on, algorithm `RSA_SHA256`, canonicalization *Exclusive*. - **Client signature required** off (the gateway does not sign its AuthnRequest). **Encrypt assertions** off, unless you turn on [encrypted assertions](#encrypted-assertions). - The signing certificate is in the realm descriptor, `https:///realms//protocol/saml/descriptor`. `idp_entity_id` is `https:///realms/` and `idp_sso_url` is `…/protocol/saml`. Keycloak generates the persistent NameID on the user's first login and keeps it as a user attribute. Read it from the user's attributes in Keycloak and add it to `subject_users`. ### Other identity providers Use the gateway's metadata (`GET /api/v1/admin/saml/metadata`) to register it. The IdP must sign both the response and the assertion with RSA-SHA256 and exclusive canonicalization, release a persistent NameID, and post to the ACS URL. Microsoft Entra ID, Okta and ADFS can do this; they were not connected in testing. ## How it works - **Flow:** SP-initiated, HTTP-Redirect to the IdP and HTTP-POST back. A login started at the IdP (IdP-initiated) is refused. - **Binding to the browser:** the start sets a short `__Host-` cookie, sealed with AES-GCM, that holds the request ID and a hash of a random RelayState. Nothing is stored on the server for a started login, so abandoned or anonymous starts cannot fill anything. The callback needs that cookie and the exact RelayState; the request ID is then consumed once. - **Validation:** both signatures by a pinned certificate, exact issuer, destination, recipient, audience and `InResponseTo`, bearer confirmation, time windows within `assertion_max_age` and `clock_skew`, one assertion, no DTD. An encrypted assertion is refused unless [encrypted assertions](#encrypted-assertions) are on. The request, response and assertion IDs are remembered in PostgreSQL only after both signatures verify, so a replay is refused even on another replica. - **Session:** eight hours, or less if the IdP sets `SessionNotOnOrAfter`. The user's role, teams and status are reread on every request. Disabling the user ends the session on the next request. - **Configuration change:** any change to the SAML trust, `saml_login` or the YAML baseline ends every SAML session and every started login, on all replicas. - **Failure:** the callback answers a generic 401 or 403. Logs and JIT creation audit keep the callback HTTP `request_id`; `saml_request_id` separately identifies the SAML AuthnRequest, and successful login also links `initiating_request_id`. Trace/span IDs follow the request context. Logs never include the response, NameID or user attributes. | Endpoint | What it does | | --- | --- | | `GET /api/v1/admin/auth/providers` | Public list of login buttons; includes SAML when it is on and configured | | `GET /api/v1/admin/saml/start` | Starts the login and redirects to the IdP | | `POST /api/v1/admin/saml/callback` | Assertion Consumer Service; creates the session and returns to `/ui` | | `GET /api/v1/admin/saml/metadata` | Service provider metadata for the IdP; with the T168 flags, the SP certificates (encryption, signing) and the SingleLogoutService | | `GET`, `POST /api/v1/admin/saml/slo` | The IdP's LogoutResponse (`saml_single_logout`) | | `GET`, `PUT`, `DELETE /api/v1/admin/saml/settings` | Read, save or revert the trust (`saml_management`, administrator, CSRF and `version`) | ## Encrypted assertions Flag `saml_encrypted_assertions` (off by default, requires `saml_login`). With it on, the IdP may encrypt the assertion to the gateway's certificate. Nothing about signatures changes: the response and the assertion are both signed by a pinned IdP certificate, exactly as for a plain assertion. ```yaml features: saml_encrypted_assertions: true admin: saml_service_provider: key_env: GATEWAY_SAML_SP_KEY # PEM RSA private key, 2048 bits or more certificate_env: GATEWAY_SAML_SP_CERTIFICATE # PEM certificate of that key previous_key_env: GATEWAY_SAML_SP_PREVIOUS_KEY # optional, during rotation previous_certificate_env: GATEWAY_SAML_SP_PREVIOUS_CERTIFICATE # set together with previous_key_env saml: # ...the trust above... require_encrypted_assertions: false # true refuses plain assertions ``` | Key | Default | What it does | | --- | --- | --- | | `saml_service_provider.key_env` | required with the flag | Variable holding the current PEM RSA private key (2048 bits or more); it decrypts assertions and signs the LogoutRequest | | `saml_service_provider.certificate_env` | required with the flag | Variable holding the PEM certificate of that key, published in the metadata | | `saml_service_provider.previous_key_env` | empty | Variable holding the key being retired during a rotation; it only decrypts | | `saml_service_provider.previous_certificate_env` | empty | Variable holding the certificate of the previous key; set together with `previous_key_env` | - The key pair is a boot reference to secrets: environment variables, or `_FILE` files with `secret_files` (a Kubernetes Secret mounted as files). It is never stored in YAML values, the database or the API, and is read when used, so replacing a mounted file takes effect without a restart. A key that cannot be read refuses encrypted responses only; startup with the flag on refuses a missing, mismatched or expired pair. - **What is accepted:** one `EncryptedAssertion` with its `EncryptedKey` inside `EncryptedData/KeyInfo` or beside `EncryptedData`. Content AES-128-GCM, AES-256-GCM, AES-128-CBC or AES-256-CBC; key transport RSA-OAEP (`xmlenc#rsa-oaep-mgf1p`, or `xmlenc11#rsa-oaep` with MGF1 SHA-1 or SHA-256), digest SHA-1 or SHA-256. RSA 1.5 key transport, Triple DES, AES-192, OAEP labels, `CipherReference`, `EncryptedID`, `EncryptedAttribute` and any other algorithm are refused before the key is used. - **Order of checks:** the response signature, which covers the ciphertext, is verified first. Only then is the assertion decrypted, with the current key and then the previous one. The decrypted assertion must be signed by a pinned certificate and pass every check of a plain assertion. Every failure is the same generic 401, so a changed ciphertext can never be used to probe the key (no padding or Bleichenbacher oracle). - **Rotation:** publish the new pair as current and keep the old one as previous. Metadata lists both certificates for encryption until you remove the previous pair, after the IdP moved to the new certificate. A previous pair that expires or cannot be read is dropped (no longer decrypts or appears in metadata); the current pair keeps working. An expired or unreadable current pair refuses encrypted responses and Single Logout. - XML Encryption identifiers (`Id` on `EncryptedData` and `EncryptedKey`, as OpenSAML and Shibboleth send) are accepted; every identifier in the document must still be unique. - `require_encrypted_assertions` refuses a plain assertion; it is ignored while the flag is off. - **Keycloak:** in the client's **Keys** tab, turn on **Encrypt assertions** and import the gateway's certificate (from the metadata, or `certificate_env`). Keycloak's defaults (AES-256-GCM, RSA-OAEP with SHA-256) are accepted. ## Single Logout Flag `saml_single_logout` (off by default, requires `saml_login`). Signing out of the console then also ends the session at the IdP, started from the gateway (SP-initiated). ```yaml features: saml_single_logout: true admin: saml_service_provider: # the same key pair signs the LogoutRequest key_env: GATEWAY_SAML_SP_KEY certificate_env: GATEWAY_SAML_SP_CERTIFICATE saml: # ...the trust above... idp_slo_url: https://identity.example.com/realms/company/protocol/saml slo_url: https://gateway.example.com/api/v1/admin/saml/slo ``` | Parameter | Default | Rule | | --- | --- | --- | | `idp_slo_url` | none | HTTPS, no query: the IdP's SingleLogoutService for the HTTP-Redirect binding | | `slo_url` | none | HTTPS, the ACS origin, path exactly `/api/v1/admin/saml/slo` | | `require_encrypted_assertions` | `false` | Refuse plain assertions (with `saml_encrypted_assertions`) | Set both URLs or neither; with neither, sign-out stays local. The console edits them in **Settings & sources → SAML single sign-on → Encryption and Single Logout**; the key stays in YAML. 1. At sign-in the gateway keeps the NameID and `SessionIndex` in a sealed `__Host-` cookie (AES-GCM, HttpOnly, SameSite=Strict) bound to that session, written only once the sign-in succeeds; the signed session cookie is unchanged. 2. **Sign out** clears the local session first. Then the gateway answers with a signed `LogoutRequest` on the HTTP-Redirect binding (RSA-SHA256 over the query, current key) and the console follows it to the IdP. A sealed `__Host-` cookie binds the request ID and a random RelayState to this browser. 3. The IdP answers at `slo_url` with a `LogoutResponse`, on the Redirect binding (query signature) or the POST binding (enveloped signature). The gateway checks the signature with a pinned certificate, the issuer, `Destination` = `slo_url`, `InResponseTo`, the issue time and the browser cookie, spends the request and response IDs once across replicas and redirects to `/ui`. The local session ends even if the IdP is down, refuses the request or never answers: the browser is already signed out of the console before it leaves. An IdP failure status is logged (`saml_logout_completed`, `outcome: idp_refused`); a forged or replayed response gets a generic 401. A session signed in before the flag was turned on, or without its logout cookie, signs out locally only. **IdP-initiated logout is not adopted.** A `LogoutRequest` sent by the IdP to `slo_url` is refused with 400: ending sessions that way needs a server-side index of every console session by NameID, which this profile does not keep (sessions are signed cookies). Sign-out started elsewhere at the IdP does not end a console session; it ends at its own expiry, at most eight hours or `SessionNotOnOrAfter`. **Keycloak:** in the client, set **Logout Service Redirect Binding URL** (or POST) to `slo_url`, turn on **Front channel logout** and import the gateway's signing certificate in **Keys**. Leave **Client signature required** off: the AuthnRequest is unsigned, so Keycloak would refuse logins, and it then accepts the signed LogoutRequest without checking it. `idp_slo_url` is the realm's `…/protocol/saml`. ## Limits - Each process validates at most `max_concurrent_callbacks` signed responses at once; reading the request body does not take a slot. - No IdP-initiated login or logout, signed AuthnRequests or metadata download from the IdP. Without `saml_single_logout`, signing out of the console ends only the local session. - Encrypted assertions and Single Logout were tested against a local fake IdP (signature wrapping, ciphertext tampering, algorithm downgrade, replay and forged logout responses), not against a real IdP. - No role from attributes. First-login user creation is opt-in through [JIT provisioning](/docs/features/jit-provisioning/), which reads the e-mail and groups attributes of the signed assertion; [SCIM](/docs/features/scim/) also provisions users. - Tested against real Keycloak 26.4 through a TLS front end, with Chromium. ## See also - [OIDC](/docs/features/oidc/) · [Access control](/docs/features/access-control/) · [Security](/docs/security/security/) - References: [SAML 2.0 core](https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf), [SAML 2.0 profiles](https://docs.oasis-open.org/security/saml/v2.0/saml-profiles-2.0-os.pdf), [Keycloak SAML clients](https://www.keycloak.org/docs/latest/server_admin/#_client-saml-configuration). # Just-in-time user provisioning **Last updated:** 2026-11-21T09:07:48-03:00 (UTC-3) With `federated_jit`, the first [OIDC](/docs/features/oidc/) or [SAML](/docs/features/saml/) login of a person who has no local user creates one, as long as the identity is on an allowlist. The new user waits for an administrator: until approved, the login says the account is pending and nothing else. It is created with the `user` role and **no teams**, exactly as [SCIM](/docs/features/scim/) creates users; nothing the identity provider sends grants a role or a team. ## How to turn it on On top of a working OIDC or SAML login: ```yaml features: federated_jit: true # boot; requires console_users, granular_rbac, team_scoped_console and oidc_login or saml_login admin: jit: allowed_email_domains: [example.com] # a verified e-mail of one of these domains, or allowed_groups: [/gateway-users] # one of these groups # require_approval: true # default; false creates the user active (still without teams) # oidc_groups_claim: groups # ID-token claim with the groups # saml_email_attribute: email # assertion attribute with the e-mail # saml_groups_attribute: groups # assertion attribute with the groups # saml_email_verified_attribute: '' # optional attribute whose value must be "true" for the e-mail to count # max_pending: 1000 # users waiting for approval; past it, new first logins are refused ``` | Field | Rule | | --- | --- | | `allowed_email_domains` | Up to 50 unique lowercase DNS names. The e-mail domain must match exactly: `sub.example.com` is not `example.com` | | `allowed_groups` | Up to 50 unique groups, up to 256 bytes each, compared exactly (case-sensitive) | | `require_approval` | `true` when omitted: a first login creates a pending user that an administrator approves; `false` creates the user active, still without teams | | `oidc_groups_claim` | A top-level claim name; identity, role and protocol claims are reserved | | `saml_email_attribute`, `saml_groups_attribute`, `saml_email_verified_attribute` | Distinct attribute `Name`s of up to 256 characters; the last is optional | | `max_pending` | 1 to 100000; `1000` when omitted. A bound on the users waiting at once, not exact under concurrent first logins | With JIT enabled, the configured OIDC issuer must fit within 2048 UTF-8 bytes. SAML entity IDs retain their 2048-byte bound. Migration 115 widens the original JIT issuer constraint without changing existing identity links, approval decisions or migration 108 history. At least one domain or group is required; without an allowlist the gateway refuses to start. PostgreSQL holds the users and their links. ## What the identity provider must send - **OIDC:** an e-mail counts only with `email_verified: true`. When domains are listed, the gateway also asks for the `email` scope, which providers such as Google need to send it; enabling this changes the OIDC configuration and requires a new login. Groups come from `oidc_groups_claim`; a claim that is not a list of up to 128 strings counts as no groups. - **SAML:** the e-mail is the single value of `saml_email_attribute` and the groups the values of `saml_groups_attribute` (values of a repeated name merge), both from the signed assertion. **The IdP must release only verified or administrator-managed e-mails**, because SAML carries no standard verified flag: an e-mail a user can change unverified would let them match a domain. If the IdP sends one, set `saml_email_verified_attribute` and only `true` counts. Values that do not fit (more than one e-mail, more than 128 groups, an invalid group) count as absent, so they only narrow admission, and attributes are read only for JIT: a statically mapped login never depends on them. The assertion is spent before anything is created, so a replayed response never creates a user. The NameID must be persistent, as for every SAML login. The identity is the protocol, the issuer (OIDC) or IdP entity (SAML), and the subject (OIDC `sub` or SAML NameID). A static `subject_users` entry and a SCIM link take precedence over JIT. ## Approving **Console users** lists the new user as **Pending approval**, created on first OIDC or SAML login. The same person signing in through both protocols is two identities, so two users, each decided on its own. **Approve** enables it; **Reject** keeps it disabled for good: JIT never recreates that identity and SCIM cannot reactivate the user. A static `subject_users` entry or a SCIM link for the same subject still takes precedence, as everywhere else. The API is `POST /api/v1/admin/users/{id}/approve` and `/reject`, with the `users:manage` permission. Approval alone does not open the console: like every `user`, the account needs a team, which an administrator assigns in **Console users**. The display name is the e-mail the IdP asserted, so check it against the IdP before approving: names are not unique. Disabling it later ends its sessions as for any user. ## Limits - No role, team or permission comes from the identity provider, by design; use [SCIM groups](/docs/features/scim/#groups) for teams that follow the IdP. - A person removed from the group or domain in the IdP keeps the local user; disable it in the console, or use SCIM. - Decision 3 (the IdP never grants a team) is revised for team membership only by [IdP groups to team membership](/docs/features/idp-team-sync/) (`idp_team_sync`): mapped groups add and remove `idp:` member memberships. The IdP still never grants a role. - Real acceptance covered Keycloak; other providers follow the same claims and attributes but have not been certified. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `POST /api/v1/admin/users/{id}/reject` | Rejects a pending user created by a first SSO login | # Invitations by e-mail **Last updated:** 2026-11-27T14:16:11-03:00 (UTC-3) With `invitation_email`, a [console invitation](/docs/features/access-control/#invitations-and-import) can go straight to the invitee over SMTP. The message carries only the single-use invitation link: never an API key, a console token or a password. When console single sign-on is configured, an invitation only **pre-provisions** the user, who then signs in through SSO; no console token is ever issued. ## How to turn it on ```yaml features: console_users: true user_invitations: true invitation_email: true # operator control, default false; requires user_invitations and PostgreSQL admin: invitation_email: host: smtp.example.com port: 587 tls: starttls # starttls (default) | implicit | plaintext username: gateway password_env: GATEWAY_SMTP_PASSWORD from: "m7gtw " console_url: https://gateway.example.com default_expiry_hours: 72 # Boot-only network trust, never editable from the console: allow_plaintext_loopback: false allowed_private_cidrs: [] # e.g. [10.0.0.0/8] for an internal relay ``` The delivery settings can also be set, replaced and reverted in the console (**Console users → Invitation e-mail**) or through the API. A console override replaces the whole YAML delivery block; **Revert to YAML** drops it, together with its stored password. | Field | Default | Bounds and meaning | | --- | --- | --- | | `host` | — | DNS name or IP address of the SMTP server. It passes the same IP guard as alert webhooks: loopback, link-local and other private addresses are refused unless allowed below. | | `port` | — | 1–65535. Usually 587 for STARTTLS and 465 for implicit TLS. | | `tls` | `starttls` | `starttls`: the server **must** offer STARTTLS; if it does not, the send fails with `tls_required` before any credential or address is sent. `implicit`: TLS from the first byte. `plaintext`: accepted only for a loopback host with `allow_plaintext_loopback: true` (a local relay or a test). Certificates are verified against the system roots, TLS 1.2 or later. | | `username` | empty | Up to 256 characters. With a username the gateway authenticates with `AUTH PLAIN`, always after TLS. | | `password_env` (YAML) / `password` (console, API) | empty | In YAML, the name of the environment variable that holds the password. Set from the console, the password is encrypted with the control-plane provider key (`storage.provider_encryption_key_env`) and is **write-only**: the API and the console only say whether one is stored. An empty password on save keeps the stored one, but only while `host`, `port`, `tls` and `username` stay the same: changing any of them answers `400 password_required` until the password is typed again or cleared, so a stored password can never be steered to another server. `clear_password` removes it. | | `from` | — | One address, with an optional display name. | | `console_url` | — | Absolute `https` URL of the console the link opens, without credentials, query or fragment; an optional path prefix is kept. `http` is accepted only for a loopback host with `allow_plaintext_loopback`. The gateway never builds the link from the request's `Host` header. | | `default_expiry_hours` | 72 | 1–168. Used when an invitation omits `expires_in_hours`. | | `allow_plaintext_loopback` (YAML only) | `false` | Allows `tls: plaintext` and an `http` console URL for loopback hosts. | | `allowed_private_cidrs` (YAML only) | `[]` | Up to 32 private canonical prefixes the SMTP host may resolve to. | | `require_verified_email` (YAML only) | `true` | An SSO claim needs a verified e-mail from the identity provider (step 3 below); `false` restores claims by link possession alone when the IdP sends no e-mail. The settings API returns it under `trust`, and the console shows it. | Changes apply on every replica at the next send: the settings are read from PostgreSQL each time. A block that only declares the boot trust is valid; the delivery settings can then come from the console alone. ## Sending an invitation In **Console users → Invitations**, fill in the e-mail field and press **Send invitation**. Through the API, add `email`: ```http POST /api/v1/admin/invitations Content-Type: application/json X-CSRF-Token: {"name": "Alice Example", "role": "team_viewer", "team_ids": ["team_platform"], "email": "alice@example.com"} ``` ```json {"invitation": {"id": "inv_…", "name": "Alice Example", "role": "team_viewer", "email": "alice@example.com", "status": "pending", "expires_at": "…"}, "emailed": true} ``` - The answer has **no token and no link**: an e-mailed invitation reaches only its recipient. Without `email`, the answer is unchanged (token and `accept_path` once). - `expires_in_hours` is optional while `invitation_email` is on; it defaults to `default_expiry_hours`. - The token is 32 random bytes. Only its SHA-256 is stored; it is single use, expires to the second and can be revoked from the list. - If the SMTP server refuses or cannot be reached, the answer is `502 invitation_email_failed` with the class (`destination_rejected`, `tls_required`, `tls_failed`, `upstream_rejected`, `upstream_retryable`, `timeout`, `network`, `settings_invalid`) and the invitation is **revoked** in the same step, so no token that never arrived stays usable. Create it again once the cause is fixed. - Bulk import does not send e-mail; it keeps returning links. The message is plain text: a greeting with the invitee's name, the role, the link `/ui/#invite=`, the expiry in UTC and a warning not to forward it. The token travels in the URL fragment, which browsers never send to a server. ### The mail system sees the link Anyone who can read the message can accept the invitation until it is used or expires: the sending relay, the recipient's mail provider, a forwarding rule, a mail archive or a security scanner that opens links. Keep the expiry short, revoke an invitation that went to a wrong address, and prefer SSO pre-provisioning (below), where the link alone is not enough to sign in. ## Test message **Send test** (or `POST /api/v1/admin/invitation-email/test` with `{"to": "ops@example.com"}`) sends one fixed message, without any link, with the saved effective settings. The answer is `{"delivered": true}` or `{"delivered": false, "error_class": "…"}`. Only a global administrator (`users:manage`) can read, change or test the settings; operators, viewers and team roles are refused. ## With single sign-on: pre-provisioning When console OIDC (`oidc_login` with `admin.oidc`) or SAML (`saml_login` with `admin.saml`) is configured, every invitation created while `invitation_email` is on is **SSO-only** (`"sso_only": true`, for e-mailed and link invitations alike): 1. The invitee opens the link. Accepting it creates no user and no token: the gateway answers `202 {"sso_required": true}` and sets a 15-minute claim cookie (`HttpOnly`, `Secure`, `SameSite=None`, sealed with the session key) that binds this browser to the invitation. 2. The console offers the console OIDC or SAML sign-in. At that sign-in, if the verified identity has no local user yet, the gateway creates the invited user with the invitation's role and teams (checked again at that moment), links that identity to it and marks the invitation accepted, in one transaction. 3. With `require_verified_email` (the default), a sign-in without a verified e-mail never claims an invitation. For an e-mailed invitation, when the identity provider sends an e-mail at all (OIDC `email`; for SAML the e-mail attribute, `email` or `admin.jit.saml_email_attribute`), it must be verified (OIDC `email_verified: true`; for SAML one value and, if configured, `admin.jit.saml_email_verified_attribute` set to `true`) and equal to the invited address. An unverified, multi-valued or different e-mail refuses the claim and the invitation stays pending. Only with `require_verified_email: false` and no e-mail sent does possession of the link plus the federated sign-in complete it. 4. Later sign-ins resolve the user through that link, like a [JIT](/docs/features/jit-provisioning/) user. Role, teams and deactivation stay with the console. An identity that already has a user ignores the claim. A refused or expired claim fails the sign-in with the generic federated failure, never falls through to JIT, and the invitation stays pending until it expires or is revoked. Every OIDC and SAML callback clears the claim cookie, whatever its outcome. The claim runs under the same federated MFA fence as a JIT creation. Links created by an invitation are honored only while `invitation_email` is on, and links created by JIT only while `federated_jit` is on: turning one feature on never revives the users the other one's flag cut off. Named OIDC providers (`oidc_providers`) keep their explicit subject links and do not claim invitations: they resolve a user only through a subject link an administrator declared and never create a user or a federated link, while a claim creates both. Invite such users directly and declare their subject link. ## Audit Every step is in the identity audit trail (and its hash chain): `invitation.create`, `invitation.email_sent`, `invitation.email_failed` (which also revokes), `invitation.revoke`, `invitation.accept` (with `:oidc` or `:saml` in the actor for an SSO claim), `invitation.expire` (recorded once by a sweep that runs every minute on each replica, actor `system`) and `invitation_email.update` / `invitation_email.revert` for the settings. Logs record `invitation_email_sent`, `invitation_email_failed` with the class, `invitation_sso_accepted` and `invitation_sso_refused`, never the token, the address list or the password. ## Limits - One recipient per invitation; no HTML, branding or localization of the message. - No API mail providers yet, only SMTP. - Delivery is synchronous (up to 20 seconds) and not retried: a temporary SMTP failure revokes the invitation, which you create again. - The SSO claim needs the console's own OIDC or SAML login; named OIDC providers do not claim invitations (see above). - An [organization admin](/docs/features/organization-admins/) sends invitations for its organization with the same settings. - Turning `invitation_email` off stops sign-ins through the links it created, even with `federated_jit` on; turning it back on restores them. ## Upgrade Migration 172 adds the settings table, the invitation columns `email`, `sso_only`, `emailed_at` and `expiry_audited_at`, and the `origin` column of federated identities (existing links are `jit`). An SSO-only invitation stores a domain-separated digest of its token, so an older binary cannot redeem it for a console token during a rollback; it just reports the link as invalid. Upgrade every replica before turning the flag on, and remove `invitation_email` and `admin.invitation_email` from YAML before rolling back. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `GET /api/v1/admin/invitation-email` | The effective SMTP settings, their source and the YAML base; the password is never returned | | `PUT /api/v1/admin/invitation-email` | Replaces the console override of the delivery settings at the current version | | `DELETE /api/v1/admin/invitation-email` | Drops the console override and its stored password, so the YAML applies | # IdP groups to team membership **Last updated:** 2026-11-17T01:26:21-03:00 (UTC-3) With `idp_team_sync`, exact group IDs from your identity provider decide part of each user's **team memberships**: an OIDC claim, a SAML attribute or SCIM groups. A mapped group makes its members **members** of an existing team. Every membership records where it came from, `manual` or `idp:`; a sync adds and removes only `idp:` memberships and never touches manual ones. The IdP never grants a console role (admin, viewer, operator, team admin) and never creates a team: groups to roles stay out of scope, as decided in [JIT provisioning](/docs/features/jit-provisioning/). ## How to turn it on ```yaml features: console_users: true team_management: true team_scoped_console: true oidc_login: true # or saml_login, or scim_groups (source: scim) idp_team_sync: true # operator control, default false; requires PostgreSQL admin: idp_team_sync: source: login # login (OIDC claim / SAML attribute at sign-in) or scim oidc_groups_claim: groups # top-level ID-token claim with an array of strings saml_groups_attribute: groups # assertion attribute; its values are merged mappings: - {group: "gateway-engineering", team: team_platform} - {group: "00000000-1111-2222-3333-444444444444", team: team_research} # Entra object ID ``` The mapping can also be edited, and reverted to YAML, in **Console users → IdP groups to teams** or with `GET`/`PUT`/`DELETE /api/v1/admin/idp-team-sync` (global admin, `users:manage`, CSRF, versioned). | Field | Default | Bounds and meaning | | --- | --- | --- | | `source` | `login` | `login`: each console OIDC or SAML sign-in syncs the user from the groups of that sign-in. `scim`: each SCIM group change syncs every user it adds or removes. Only one source drives the sync, so two sources can never undo each other. | | `oidc_groups_claim` | `groups` | A top-level claim name; identity and protocol claims (`sub`, `email`…) are refused. | | `saml_groups_attribute` | `groups` | An attribute name of up to 256 characters. | | `mappings[].group` | — | The **exact** group ID, compared byte for byte: no prefixes, globs or case folding. 1–256 bytes, no control characters. For SCIM, a group is identified by its `externalId`, or by its `displayName` when the IdP sent none. | | `mappings[].team` | — | An existing team ID. The console and the API refuse a team that is not active; a YAML mapping to a missing or deleted team is skipped at sync time. | Up to 200 mappings. One group may map to several teams and several groups to one team. ## What a sync does For one user, from the groups the IdP asserts now: - **Add:** each mapped team the user does not hold yet becomes a `member` membership tagged `idp:`. - **Remove:** each `idp:` membership whose group is no longer asserted is deleted. A claim that is missing or malformed counts as no groups, so it can only remove. - **Keep manual:** a team the user already holds manually stays manual, with its role; a sync never adds, changes or removes it, even when its group disappears. - **Ignore the unknown:** groups without a mapping are ignored. Nothing creates a team. - **Retag:** when another asserted group still maps the same team, the membership stays and names that group. - Only users with the read-only team roles `user` and `team_viewer` are synced. Team administrators and global roles are never synced: without `membership_roles` every membership of a team administrator administers its team, so a group would grant administration. A sync never takes a user above 20 memberships. - A disabled user loses synced memberships but never gains one, so a group removal made while it was disabled is not undone by its reactivation. At sign-in the sync runs after the identity is verified and before the console checks the user's teams, so a removed group never survives into the new session; a SAML assertion is spent first, so a replayed one cannot restore an old group set. If the sync cannot be stored, the sign-in fails. With `source: scim`, a SCIM group create, update, patch or delete syncs every member before and after the change; if the sync fails the SCIM call answers 503 and the IdP retries it. While `idp_team_sync` is on, a console edit of a `user` or `team_viewer` replaces only manual memberships: synced ones stay synced, always with the `member` role; remove one by changing the mapping or the IdP group. Changing the user to `team_admin` or a global role, or any edit while the flag is off, replaces every membership, synced ones included, so turning the flag off never freezes a synced membership. A retag is audited as `membership.idp_retag`. Sessions reread teams on every request, so a removal applies to the next request. ## Console and API **Console users** shows, for each team of a scoped user, where it comes from: `team_x (IdP group gateway-engineering)` or `(SCIM group)` for a [bound SCIM group](/docs/features/scim/#groups); manual teams show the bare team ID. The API returns the same in `memberships[].source` (`manual`, `idp:` or `scim_group`), which requests never accept. The user editor leaves synced teams out of the selection and lists them apart: while the sync manages the user (`user` or `team_viewer` with the flag on) they are sent back unchanged; otherwise (promotion to `team_admin` or a global role, or the flag off) the edit drops them instead of rewriting them as manual memberships. Migration 175 removes, audited, the synced memberships that a team administrator or global role still held. ```http PUT /api/v1/admin/idp-team-sync Content-Type: application/json X-CSRF-Token: {"version": 0, "source": "login", "mappings": [{"group": "gateway-engineering", "team": "team_platform"}]} ``` ## Audit Every add and remove is in the identity audit trail (and its hash chain), in the same transaction: `membership.idp_add` and `membership.idp_remove`, with target `/` and actor `idp:@`. Mapping changes are `idp_team_sync.update` and `idp_team_sync.revert`. Logs record `idp_team_sync` with counts, never the groups. ## Limits - Membership only, always with the `member` role; groups to roles, including admin, are not supported. - Named OIDC providers (`oidc_providers`) keep their explicit subject links and do not sync groups: one source drives the sync (`login` is the console's own OIDC or SAML sign-in, or `scim`), and a second login path would remove the memberships the first one added whenever its token carries other groups. - With `source: login`, a user's teams change only when they sign in again; remove access immediately with SCIM, by disabling the user or by removing the membership in the IdP and asking for a new sign-in. - Nested groups are not expanded: map each group the IdP actually asserts. - SCIM groups without an `externalId` are matched by `displayName`, which the IdP can rename; prefer IdPs that send `externalId`. - A SCIM group replacement that races with another change of the same group may leave one user unsynced until its next group change or sign-in. - While the flag is off, existing synced memberships stay in force until a console edit or the user's next sync after the flag is turned back on. ## Upgrade Migration 173 adds the `source` column to team memberships (existing rows become `manual`), the source in the effective-membership view and the mapping table. An older binary treats synced memberships as manual ones, and any user edit it makes rewrites them as manual for good: the IdP can no longer remove them after rolling forward again. Upgrade every replica before turning the flag on; before rolling back, turn the flag off, remove `idp_team_sync` and `admin.idp_team_sync` from YAML and review the `idp:` memberships. # Provisioning with SCIM **Last updated:** 2026-11-21T09:54:10-03:00 (UTC-3) The IdP (Entra ID, Okta, authentik, Keycloak with an extension) creates and deactivates console users on its own. When someone leaves the company and is deactivated in the IdP, their console session drops on the next request and that person's keys stop working. With SCIM groups, teams can also come from the IdP, once an admin links each group to a team. | Resource | Flag | | --- | --- | | Users (`/scim/v2/Users`) | `scim` | | Groups linked to teams (`/scim/v2/Groups`) | `scim_groups` (requires `scim` and `team_management`) | **No SCIM attribute grants a role.** `roles`, `title` and similar attributes are accepted and discarded. Roles and teams are decided in the console. ## How to enable it ```yaml features: console_users: true granular_rbac: true # the user role only exists with granular RBAC scim: true scim_groups: true # optional admin: scim_token_sha256_env: GATEWAY_SCIM_SHA256 ``` - The IdP authenticates with `Authorization: Bearer `. The gateway stores only the token's SHA-256: put its hex digest in `GATEWAY_SCIM_SHA256`, the variable `admin.scim_token_sha256_env` names in the shipped YAML (or in a file, with `GATEWAY_SCIM_SHA256_FILE`). It must be different from the admin and viewer tokens. - The flag can be turned on and off without a restart, in **Settings & sources**. When it is off, the routes respond 404. - In the IdP, point the base URL to `https://gateway.example.com/scim/v2`. ## Users | Route | Support | | --- | --- | | `GET /scim/v2/ServiceProviderConfig` and `/ResourceTypes` | Yes | | `GET /scim/v2/Users` | Filters `userName eq "..."` and `externalId eq "..."`; `startIndex`/`count` up to 200 | | `POST /scim/v2/Users` | Creates an active user, with the `user` role and **no teams** | | `GET /scim/v2/Users/{id}` | Yes | | `PATCH` / `PUT /scim/v2/Users/{id}` | Only `active` (`true`/`false`, or Entra ID's `"True"`/`"False"`) | | `DELETE /scim/v2/Users/{id}` | Deactivates; history and audit are kept | Any other filter is refused with `invalidFilter`, because an ignored filter would return every user. - **`externalId` = the IdP's `sub`.** On [OIDC](/docs/features/oidc/) login, the SCIM link wins over the `subject_users` map, which can stay empty. - A provisioned user can only sign in through SSO: their local token is random and is never returned. - **Without a team, login is denied.** Assign a team in the console or use groups. - **Deactivate** (`active=false` or `DELETE`): sessions drop on the next request, and the keys the user [owns](/docs/features/identity-ownership/) are refused. - **Reactivate** (`active=true`): only users deactivated through SCIM come back, with the same role, teams and keys. Keys revoked by an admin and old sessions stay invalid. A user deactivated by an admin in the console gets `400 mutability`. The keys work again at once on the replica that handled the request, and within 5 seconds on the others (a replica briefly remembers a key it found unusable). - `userName` and `externalId` are unique and immutable; creating again returns `409 uniqueness`, including for simultaneous creations. In the console, **Console users** marks users managed by the IdP with "Provisioned by SCIM". ## Groups With `scim_groups`, the IdP manages groups and members at `/scim/v2/Groups` (list with the `displayName eq` and `externalId eq` filters, create, read, `PUT`, `PATCH` of members and name, delete), in the Entra ID, Okta and authentik formats. The effect is decided in the console: 1. The group arrives from the IdP and is stored **without granting anything**. 2. A global admin links the group to a team in **Console users → SCIM groups** (or `PUT /api/v1/admin/scim-groups/{id}/team`). 3. From then on, the group's members are **members** of that team. A group never grants the admin role. - Removing someone from the group in the IdP revokes access immediately, without touching teams assigned by hand. - Teams assigned by hand take precedence over group teams; an `admin` membership only exists when assigned by hand. - A group does not bring into the team a user created by hand in the console (`400 invalidValue`). - A group links to one team. ## Audit Creation and deactivation go into the identity audit with `actor = scim` and the call's `X-Request-Id`. ## Tested with authentik 2025.10 With authentik's native SCIM client and the default user and group mappings: - the created user arrived through `POST /Users`, with `externalId` equal to the OIDC provider's `sub`; - login only worked after the user had a team; - deactivating in authentik dropped the open session (401 on the next request), and reactivating restored the role, team and keys; - the group arrived and only granted access after it was linked; removing and adding members in authentik revoked and granted access immediately. Things to watch for in authentik: - it rejects emails on reserved domains (`.test`, `.example`) before calling the gateway; - it does not propagate group deletion: remove the members or unlink the group in the console before deleting it; - without `scim_groups`, remove the group mapping, or the sync fails on `/Groups` (404). ## Limits - No Bulk, sorting, ETag, password or nested groups. - SCIM does not create users on first login; that is [JIT provisioning](/docs/features/jit-provisioning/) (`federated_jit`), where an administrator approves each new federated user. SCIM-provisioned users can sign in with [OIDC](/docs/features/oidc/); [SAML](/docs/features/saml/) needs an explicit NameID binding. - Entra ID and Okta have not been connected; the tests use requests in their formats. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `GET /api/v1/admin/scim-groups` | The groups the identity provider pushed, with their team binding | ## See also - [SSO](/docs/features/oidc/). - [Access control](/docs/features/access-control/). # Organizations **Last updated:** 2026-11-25T18:37:43-03:00 (UTC-3) An organization sits above teams: a business unit, a customer, a subsidiary. It defines a **model ceiling** that applies to every key of every one of its teams, and it lets you filter usage and cost by organization. **Every team belongs to exactly one organization.** `org_default` exists from installation, cannot be deleted, and receives the teams that do not yet have another one. ## How to enable it ```yaml features: team_management: true organizations: true # boot organization_management: true # edit through the console and the API organizations: - id: platform-org # lowercase, no "_" name: Platform allowed_models: [chat-default] teams: [platform] ``` | Key | What it does | | --- | --- | | `organizations[].id` | Unique lower-case identifier, 2–64 characters of letters, digits and `-` (no `_`) | | `organizations[].name` | Display name, 1–80 characters without control characters | | `organizations[].allowed_models` | Up to 200 aliases or `group:` references the organization's keys may ever use; omit it for no ceiling | | `organizations[].teams` | The teams that belong to the organization; they are reassigned to it at every boot | `organization_management` lets global administrators create and rename organizations, set their model ceiling and move teams between them from the console and the API. Organizations declared in the YAML are read-only in the console and the API (`409 organization_declared`), and the teams listed in them cannot be moved through the console. ## Model ceiling - `allowed_models` accepts aliases and access groups (`group:`). `*` is not accepted. - A ceiling entry may be a `prefix/*` alias (a model declared with a `prefix/*` ID, which serves any model under the prefix). A key keeps what both it and the ceiling allow, the narrower of the two: under a ceiling of `groq/*`, a key that names `groq/llama` keeps `groq/llama`, a key with `*` or `groq/*` keeps `groq/*`, and a key that names only models outside the prefix keeps none. Under a ceiling of `groq/llama`, a key with `groq/*` keeps `groq/llama` alone. The result is never wider than the ceiling. - Without `allowed_models`, there is no ceiling. An empty list blocks all models. - The ceiling applies **on every request**, after the key, the groups and the team policy. Removing a model from the ceiling, or moving the team to another organization, takes effect on the next call. - Only the global admin defines the ceiling. ## When a team moves A team keeps its ID, its keys and its configuration when a global administrator moves it to another organization. What it recorded stays where it was recorded: a request, its spend, its capture and spans, a session, a trace, an evaluation result, a comment and an experiment run belong to the organization they ran in, and nothing is rewritten by the move. **Spend stays with the former organization.** - Every request is recorded with the organization its team was in when the request was admitted. That organization is read from the team on each request, never from a copy kept on the key: the first request after the move is recorded in, and charged to, the new organization. - The totals of **Usage** and **Analytics**, the daily rollups, the cost report (`/valuation`), the budget charge comparison, the request log and its export, and the `organization` dimension and filter of the [usage query](/docs/features/analytics-experience/#any-grouping-the-structured-query) all count a request for the organization it ran in. An organization's totals hold what was spent in it, by the teams it has now and by the teams that left; they never hold what a team spent before it arrived. - A request recorded with no organization (written with `organizations` off, or before the gateway recorded it) stays with its team and counts for the organization the team is in now. | Who reads | `?team=` names the moved team | `?organization=` | | --- | --- | --- | | A team role of the team, and the administrators of its new organization | What the team recorded since the move, and its rows that record no organization | Its own organization only: what was recorded there | | The former organization's administrator | What the team recorded in that organization, and nothing since | Its own organization only: its teams' rows and what the teams that left recorded there | | The global administrator | The team in its current organization, as its own roles see it | The rows recorded in the organization named | **Budgets.** - An organization's budget, TPM and TPD (the [`tenant` subject](#budget-per-organization)) count what its teams spent while they were in it. The former organization's window keeps what the team spent there and is not freed: a move cannot be used to empty an exceeded budget. The new organization's window is not charged for the past and counts the team from the move on. - The team's own budget, and those of its keys and users, do not look at the organization: they run across the move. A team at 90% of its monthly budget is still at 90% in its new organization. - A realtime session is admitted once: one that was open when the team moved keeps recording and charging the organization of its admission until it ends. **The former organization's administrators keep reading what was recorded there.** With [organization admins](/docs/features/organization-admins/), the administrator of the former organization reads everything the team recorded in that organization, and nothing it records after leaving: - **What.** Totals, rollup days, the cost report, the budget charge comparison and the request log (page and export); a request with its journey, trace and spans, and the [trace explorer](/docs/features/trace-explorer/); captures and their content; evaluation results, their revision history and scores, the statistics of one score and the agreement of two, experiment runs, comment threads; [agent runs](/docs/features/agent-recognition/) with their steps; the [usage query](/docs/features/analytics-experience/#any-grouping-the-structured-query); durable receipts; the team's and its keys' detail and savings; the team's alerts, also among the records of a trace. - **How it is read.** Through the organization recorded on each row, never through the team. Lists that are not narrowed to a team include it. To narrow to the team, name it: `?team=` on the usage, log, durable receipt, agent run and detail routes, `team_id` on evaluation results, experiment runs (`/evals/runs`), scores (`/evals/scores`), evaluation captures (`/evals/captures`), score analytics, agreement and comment threads, a `team:` term in the [trace explorer](/docs/features/trace-explorer/), a `team` filter in the usage query. A team that was never in the organization answers with nothing; a team the session may not name is refused (`403` or `404`), not answered empty. - **Where each row belongs.** Every row records the organization it was written in, when it is written: a request log row, a span, a score and an experiment run the organization the request or the run was admitted under; a content capture, an evaluation capture, a durable receipt, a quota reservation and an agent step the one of their request; a comment and a review queue item the team's organization when it was written (or, for a global administrator writing about what the team recorded before it moved, the organization that recorded the target); a mention its comment's. The decision never compares two clocks, so a request ID or a session the client sends again after the move cannot carry a row to the other side. Rows written before this rule (migration 270), and rows replicas of the earlier release write during a rolling upgrade, are placed once, in the background, by the rule the release before applied (the request log row nearest in time); until then, and for a row that cannot be placed that way, that rule still applies (see the upgrade notes below). - **With the query language.** The request log's `q`, its facets and a [saved view](/docs/features/query-language/) read the same rows as the list they narrow: the team the request names (`?team=`, the form's team in the console) or, with `?organization=`, the whole organization, where `team:` names the team that left. Evaluation, span and text terms are resolved under that same scope, so a term never matches a row the list could not show. A saved view keeps the query, not the team: it is applied over the team the screen has selected. On the routes that take `?organization=`, the administrator's own organization shows the team in the by-team ranking. - **Which teams.** `GET /api/v1/admin/config` lists them for the administrator as `former_teams` (`id`, the `name` the team had when it left, `left_at`), and the console's team selector on **Usage**, **Logs**, **Durable usage**, **Evals** (the "Recorded by team" selector over experiments, scores and captures, and the team of score analytics and agreement) and **Traces** offers each as " (left on )". The team's detail answers with `status: left` and `left_at`, the usage it recorded there, and none of its configuration or its keys' (that is another organization's now). A key's detail and savings are read the same way when the key served requests recorded in the organization; a key the team got after it left answers `404`. - **With which permissions.** The ones the administrator already holds, under its [custom role](/docs/features/custom-roles/) ceiling if it has one: `analytics:read`, `logs:read`, `evals:read`, and for captured content the same [content permissions](/docs/features/access-control/) it has over its own teams (structure, sent view, reasoning, media, received view). No new permission exists for this, and it is a read: the administrator cannot score, comment on, queue or replay what the team recorded, and cannot act on its alerts. - **With feature plans.** Rows belong to the organization they were recorded in, so that organization's own plan, as it is now, governs these reads (`organization_plan_entitlements`): the route's features must be in it. Without such a plan, with a disabled one, or with organization plans off, the path is closed and the administrator reads only its teams of now, each under its own plan. A team that is in the organization now is never opened by the organization's plan: left out by its own plan, it stays out. The organization is read whole (`?organization=`) only when, in addition, none of its teams of now is left out of the route by the team's plan. When one is, the plan of a team that stays does not close the path to a team that left: the lists still hold what each team that left recorded there (the teams of `former_teams`, at most 500), and such a team is still read by naming it. The same holds for a feature inside a route: a team of now without `evaluation_results` keeps its results out of every list, facet and query term, also through the organization, while the results a team that left recorded there stay. - **What follows the team instead.** Its configuration: datasets, evaluators, score configs, rules, queues, prompts, keys and policies move with it and are not the former organization's any more. See [targets after a team moves](/docs/features/evals/#targets-after-a-team-moves) for the team's own side. **Alerts.** A team's [alert rule](/docs/features/alert-rules/) scans what the team recorded in the organization it is in now; an organization's rule scans what was recorded in that organization. An alert of a team belongs to the organization the team was in when it last fired: the team's alert list shows the alerts raised in its current organization, and the former organization's administrators keep the ones raised there (to read, not to acknowledge or resolve). The query of a scheduled rule counts the rows of the rule's scope, and its evaluation and span terms are resolved under it: an organization's rule counts what a team that left recorded there, a team's rule what the team records in its organization of now. The counters of a live evaluation rule (pending, done, failed) and its job list count the requests of the team's current organization. **Audit.** A move writes three events with the same request ID, from the console and the API (actor: the administrator) and from a YAML declaration that takes a team from another organization (actor `system:config`): | Action | Target | Shown to | | --- | --- | --- | | `team.organization` | the team | The new organization's administrators and the global audit view | | `team.organization_leave` | the team | The former organization's administrators and the global audit view | | `team.organization_move` | `//` | The global audit view only, so neither organization learns the other's ID | **Upgrade (migrations 213, 214, 235 to 238 and 270).** All run at start and read no request log row. - **Rollups (213).** The organization joins the rollup key. Every day built before is taken out of use and queued; the gateway rebuilds the queue in the background, newest day first, at most 31 days every five minutes and each day in its own transaction, so a restart loses nothing. Until a day is rebuilt, reports answer it from the request log (correct, and as slow as without `analytics_rollup_reads`), and `GET /api/v1/admin/analytics/rollups` lists it under `missing_days`. A day costs one aggregate over that day's request log rows, what the periodic build already pays for today and yesterday: measured on one machine (PostgreSQL 16 in a local container), 30 days of 100,000 requests each were rebuilt in 16 s (0.55 s a day), and 30 days of 20,000 requests each in under 2 s. A run has four minutes; a day that needs longer stays queued and keeps being answered from the request log. The log line `rollup_organization_rebuild` reports the days done and left. The migration also rebuilds the table's primary key under a lock: measured, 1.1 s for 1.2 million rollup rows and 4.8 s for 5 million. - **Usage copy (214).** With an [analytics store](/docs/features/analytics-store/), the copied request log carries the organization too. Rows copied by the earlier release that record an organization are copied again once, in batches of `analytics_store.copy.batch_size`; a deployment that never had `organizations` on has none. Until that ends, Usage, the request log and alert scans read PostgreSQL, and `GET /api/v1/admin/analytics-store` shows `state: copying` with `copy.organization_backfill_pending: true`. Measured on the same machine against ClickHouse 25.12, 600,000 such rows were copied again in 29 s and 2.4 million in 2 min 13 s (18,000 to 21,000 rows a second, against 125,000 to 147,000 a second for a first copy: each batch is deleted and written again). - **A very large day (235, 238).** A day whose rebuild does not finish in one statement within a minute is rebuilt in slices: each slice is aggregated in its own transaction into a staging table, progress is kept between runs and across restarts (a cursor into the day), and the day's rollup rows and its marker are replaced together when the last slice is done, so no report ever reads half a day. Slices start one hour wide; a slice that does not aggregate within a minute is halved, down to one second, and the width that worked is remembered for the day. A day known to need slices is no longer tried whole at every build: the periodic build and `POST /api/v1/admin/analytics/rollups/rebuild` queue it at once, and the background rebuild, which alternates between today and yesterday and the older days, stages it. A day whose build fails is left out for that run and the others go on. The manual rebuild answers `202` with `{"queued": true, "from", "to", "days"}` when days were left to the background rebuild (a range that did not fit its two minutes, or a day built in slices) and `204` when the range was built; a day asked for while its slices are being staged runs once more after that pass, so events written during it are counted. The log line `rollup_organization_rebuild` reports `staged_slices`, and `rollup_build_queued` a periodic build that ran out of its time. Measured on one machine: a day of 240,000 requests took 0.5 s as one statement, 1.0 s in 24 hour slices and 3.3 s in 96 quarter-hour slices. What remains unbounded is one second of requests that does not aggregate within a minute; the rebuild then reports that second and the day stays answered from the request log. - **Alerts (236) and teams that left (237).** `gateway_alerts` gains the organization an alert was raised in; earlier alerts have none and stay with their team. `gateway_team_departures` records each team that leaves an organization, with its name and the time. Moves made before the upgrade are rebuilt from the audit log (a team's creation and each of its moves), as far as audit retention kept those events; a team whose earlier move is no longer in the audit log is not listed in `former_teams`, and its rows are still read through the organization by naming it. - **The organization on every row (270).** Comments, review queue items, content and evaluation captures, durable receipts, quota reservations and agent steps gain `organization_id` and `organization_unplaced`; the migration only adds the columns (no table scan). With organizations on, the retention worker then places, every minute and in short transactions that never hold a table, the rows that record none, by the rule the earlier release applied (the request log row nearest in time). First the page sweep of what existed at the upgrade, up to 8 MB of a table per transaction (a step that takes longer than 4 seconds, or meets a locked row, is undone and the next one reads half as much). Once it is done, an index sweep, for good, of every row still to try: rows that were too recent or pending at the page sweep, old rows moved to a page it had already read, and what replicas of the earlier release keep writing during a rolling upgrade. A row is tried once it is six hours old (the window the rule looks in), and placed or marked unplaceable, so none is tried twice. Until a row is placed, and for good when it is marked, its readers apply the earlier rule. Progress: `gateway_recorded_organization_backfill` (pages read, rows placed and marked); the log lines `recorded_organization_backfill` and `recorded_organization_backfill_failed` (with its `stage`). The index sweep's partial indexes (`*_organization_pending`) are built `CONCURRENTLY` by one replica after the page sweep. - **Rolling upgrade.** A replica still on the earlier release cannot build a rollup day or copy to the analytics store any more: it logs `rollup_build_failed` and `analytics_copy_failed`, and its copy status view answers `503`, until it is replaced. The upgraded replicas do that work meanwhile. A replica of a release between 235 and 238 does not know the slice cursor either: its queue writes fail, and a day it builds whole takes that day out of the queue, so a day built in slices may start over while both releases run. Finish the rollout before relying on any of it. ## Console and API | Action | API | Console | | --- | --- | --- | | List | `GET /api/v1/admin/organizations` (admin, viewer) | **Organizations** | | Create, rename, set the ceiling | `POST`, `PUT /api/v1/admin/organizations/{id}`, with version | Organization form | | Delete | `DELETE …/{id}`; refused with active teams, for `org_default` and for organizations from the YAML | **Delete** | | Move a team | `PUT /api/v1/admin/teams/{id}/organization`, with the team's version; refused (`409 team_has_organization_members`) while a member belongs to the current organization | Selector on the team | | Route JIT users | `jit_email_domains` on create or update (with `organization_admins`), or in YAML | **JIT e-mail domains** in the organization form | | Create a team in an organization | `POST /api/v1/admin/teams` with `organization_id` | — | | Filter usage | `?organization=` in logs, log export, analytics and valuation | — | The `organization` filter selects what was recorded in that organization ([when a team moves](#when-a-team-moves)). It does not combine with `team` for a global administrator and does not widen what a team session can see; an organization administrator may name its own organization, alone or with `team`. Every change goes into the audit. ## Budget per organization A budget, TPM or TPD for every key of an organization's teams uses the `tenant` subject of the [quota policies](/docs/features/quota-governance/#tenant-ceiling) with the organization ID, and a request rate the `tenant` subject of the [rate policies](/docs/features/rate-limits/). Both are ceilings the global administrator sets; an organization admin reads them. The older `organization` quota subject is a financial account a key is attributed to, not this tenant. ## JIT routing With `organization_admins`, an organization may list `jit_email_domains` (up to 50 lowercase domains, YAML or API). A new [JIT](/docs/features/jit-provisioning/) user whose verified e-mail has one of those domains joins that organization, so its [organization admin](/docs/features/organization-admins/) approves or rejects it; a domain listed by no organization, or by more than one, leaves the user gateway-wide for the global administrator. Omitting `jit_email_domains` on update keeps the stored list. ```yaml organizations: - id: acme name: Acme jit_email_domains: [acme.example] ``` ## Limits - With `organization_admins` (T168), the `org_admin` role administers one organization's teams, team-scoped users, keys and audit view; see [organization admins](/docs/features/organization-admins/). There is no per-organization viewer role, and ceilings stay with the global admin. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `PUT /api/v1/admin/organizations/{id}/model-aliases/{alias}` | Creates or replaces a console model alias of the organization | | `DELETE /api/v1/admin/organizations/{id}/model-aliases/{alias}` | Deletes a console alias at its current version | | `POST /api/v1/admin/organizations` | Creates a console organization; omit `allowed_models` for no ceiling | | `DELETE /api/v1/admin/organizations/{id}` | Deletes an organization with no active teams; YAML organizations and `org_default` are refused | ## See also - [Access control](/docs/features/access-control/). - [Plans](/docs/features/entitlements/). ## Organization schema and ceilings Organization display names follow the existing one-to-eighty Unicode code-point (Go rune) limit. The console preserves valid astral characters; the server remains authoritative for the boundary and reference checks. Shared [parameter definitions](/docs/reference/parameter-registry/) do not generate an organization identity or grant its models. A missing model ceiling and an explicit empty allowlist retain their distinct semantics; team ownership and every additional authorization ceiling remain in force. ## Concurrent team links and organization deletion Creating or moving a team locks its active target organization through the transaction, so a concurrent logical deletion cannot leave the team attached after the target disappears. A refused link preserves the prior tenant, version and audit state. If stored team authority already references an inactive organization, inference fails closed with `organization_unavailable`; it does not become unrestricted. A global administrator can use the existing versioned team-organization selector to move the team to an active organization. An unknown declarative bootstrap team still resolves through `org_default`. ## Plan ceiling Organizations can optionally receive a feature-plan ceiling under `organization_plan_entitlements`, separate from their model ceiling. It intersects the team plan and never grants scopes, membership or model access; no assignment preserves team-only entitlement behavior. Assignments use the active organization ID and live team ownership. Manage source/version/revert in Plans & entitlements; see [plan enforcement and upgrade](/docs/features/entitlements/#optional-organization-ceiling). Removing a restrictive organization assignment restores an unrestricted layer and can grant rights. In a classified edition, that transition is checked for new licensed grants, including YAML removals and runtime boundary deactivation. It is not treated as an empty grant. Existing admitted operations and the instance security controls remain independent. # Organization admins **Last updated:** 2026-11-27T11:44:32-03:00 (UTC-3) With `organization_admins`, the gateway runs in a **multi-tenant mode**: the `org_admin` console role administers exactly one [organization](/docs/features/organizations/) and nothing outside it. Without the flag (the default, single-tenant), nothing changes: the role does not exist and administrators can do everything. ## How to turn it on ```yaml features: organizations: true organization_management: true console_users: true granular_rbac: true team_scoped_console: true team_admin_console: true organization_admins: true # operator control, default false; requires PostgreSQL ``` A global administrator creates an organization admin in **Console users** (role **Organization admin**, then the organization) or through the API: ```http POST /api/v1/admin/users Content-Type: application/json X-CSRF-Token: {"name": "Acme admin", "role": "org_admin", "organization_id": "org_acme"} ``` `org_admin` takes no `team_ids`: its teams are always every active team of its organization, read again on every request, so a team created, moved or deleted later is covered at once. Users can also be placed in an organization by a global administrator with `organization_id` on create or update; every team of such a user must belong to that organization. Placement rules: - Only team-scoped users (`user`, `team_viewer`, `team_admin`) and `org_admin` belong to an organization. `organization_id` with a global role answers `400`; changing a user to a global role drops its organization. - On update, omitting `organization_id` keeps the stored one, and `"organization_id": ""` clears it (also while the flag is off, so a single-tenant edit is never blocked by an earlier placement). - A user of an organization holds only that organization's teams: manual and IdP-synced memberships are checked on every write (`403 organization_forbidden`), an IdP sync drops a synced membership of another organization, and a [SCIM group](/docs/features/scim/#groups) bound to another organization's team gives nothing to a user of an organization. An organization admin gets its teams only from its organization, never from a SCIM group. - When its organization is deleted, a team-scoped user is gateway-wide again at its next edit. - Moving a team to another organization is refused with `409 team_has_organization_members` while a member belongs to the team's current organization; remove those memberships first. Gateway-wide users stay: they belong to the global administrator, and the new organization's admin neither lists nor edits them. - A global administrator edits an organization admin without resending `organization_id`, and can remove a user from its organization in the console editor (**Remove from organization**) or with `"organization_id": ""`. ## What an organization admin can do Inside its own organization, an organization admin is a team administrator over every team, plus: | Area | Routes | Rule | | --- | --- | --- | | Teams | `POST /api/v1/admin/teams`, `PUT`/`DELETE /api/v1/admin/teams/{id}` | Created teams always belong to its organization; `organization_id` may be omitted or its own. A team of another organization answers `404`. | | Users | `GET /api/v1/admin/users`, `POST`, `PUT /api/v1/admin/users/{id}`, `DELETE /api/v1/admin/users/{id}` | It lists only the users of its organization. It creates and edits only `user`, `team_viewer` and `team_admin` users, in its organization's teams; the users it creates belong to its organization. A user of another organization or a gateway-wide user answers `404`. | | Invitations | `GET`, `POST /api/v1/admin/invitations`, `DELETE /api/v1/admin/invitations/{id}` | It lists and revokes only its organization's invitations. An invitation it creates has a team-scoped role and only its organization's teams, and the invited user joins its organization on acceptance (teams checked again then). With `invitation_email` it can send it by e-mail; the SMTP settings stay global. | | Bulk import | `POST /api/v1/admin/users/bulk` | The same rules per row; a row naming another organization's team is invalid in the dry run. A reused `idempotency_key` never reads another organization's rows. | | JIT decisions | `POST /api/v1/admin/users/{id}/approve`, `…/reject` | Only pending JIT users routed to its organization by its [`jit_email_domains`](/docs/features/organizations/#jit-routing); others answer `409 jit_not_pending`. An approved user then needs teams, which it assigns with `PUT /api/v1/admin/users/{id}`. | | User inventory and detail | `GET /api/v1/admin/users/page`, `GET /api/v1/admin/users/{id}/detail` | Only its organization's users (with `identity_inventory` and `identity_details`). | | Keys, logs, analytics and the other team screens | the existing team-scoped routes | The team administrator rules, on its organization's teams. | | What was recorded in the organization | The read routes of usage, logs, traces, captures, evaluations, durable receipts, alerts and team or key detail | Everything recorded in its organization, read through the organization on each row: its teams' rows, and what a team recorded there before it moved away (never what that team records since). `?team=` narrows to one team, also one that left (`former_teams` in `GET /api/v1/admin/config` lists them, and the console's team selectors show them as "left on "); `?organization=` reads all of it on the usage routes; another organization's ID answers `403 organization_forbidden`. Reads only, with the permissions it already holds. See [when a team moves](/docs/features/organizations/#when-a-team-moves). | | Budgets | `GET /api/v1/admin/quota-policies`, `PUT`/`DELETE /api/v1/admin/quota-policies/{id}`, `PUT`/`DELETE /api/v1/admin/rate-policies/{id}` | Quota policies (budget, TPM, TPD) and rate policies on its teams, managed keys and team-scoped users (and, with `membership_budgets` and `quota_subject_lists`, their memberships and subject lists of only its own subjects), within its tenant ceilings. See [Budgets inside the organization](#budgets-inside-the-organization). | | Model aliases | `GET /api/v1/admin/organizations/{id}/model-aliases`, `PUT`/`DELETE …/model-aliases/{alias}` | With `organization_model_aliases`: client names only its organization's keys resolve. Another organization's ID answers `404`. See [Organization aliases](/docs/features/model-aliases/#organization-aliases). | | Manual release of unknown reservations | `GET /api/v1/admin/quota-finance/unknown-reservations`, `POST …/release-unknown`, `GET …/manual-releases` | With `quota_manual_release`: it lists and [releases by hand](/docs/features/quota-finance/#releasing-an-unknown-reservation-by-hand) only reservations of its organization's teams, with a written reason, and reads only its own trail. A reservation that also holds a ceiling set above the organization (a tenant ceiling, a global or provider budget in force, a group, a subject list or an account) is the global administrator's to release. Another organization's reservation answers `409 reservation_not_unknown`, as one that does not exist. | | Audit | `GET /api/v1/admin/audit` | Only events recorded for its organization: identity events store the organization of their target (team, user, key or membership) when they are written, so the view does not follow a team or a user that changes organization later. Control-plane events appear only when they were recorded for it (migration 177): quota and rate policy writes on its subjects (its own or the global administrator's), its tenant ceilings and its model aliases. | Every write checks the organization of the **target as stored**, inside the same database transaction, never an organization ID taken from the request. A request that names another organization (`organization_id` on a team or user) is refused with `403 organization_forbidden`; it is never followed. ## Tenant ceilings A global administrator bounds the whole organization, on every request of every key of its teams: | Ceiling | Where it is set | | --- | --- | | Models | `allowed_models` of the [organization](/docs/features/organizations/#model-ceiling). | | Budget, TPM, TPD | A [quota policy](/docs/features/quota-governance/#tenant-ceiling) with `subject: tenant` and the organization ID. | | Requests per minute | A [rate policy](/docs/features/rate-limits/) with `subject: tenant` and the organization ID. | Teams and keys inside the organization are enforced within those ceilings: their own policies apply on top, never instead. The organization admin reads them in **My organization** (console) or `GET /api/v1/admin/organization`, which returns its organization, its ceilings (`read_only: true`) and its teams; every write to a ceiling answers `403`. ## Budgets inside the organization An organization admin manages the budgets of its organization with the global administrator's routes and editors (console: **My organization → Budgets** and **Rate limits**). It needs `quota_management` for quota policies and `rate_policy_management` for rate policies, like the global administrator. | It may write | It may not write (`403 organization_forbidden`) | | --- | --- | | Quota policies with `subject: team`, `key` (a managed key) or `user` (a team-scoped user of its organization, not an organization admin) | A `tenant` ceiling, a `global`, `provider`, `model`, `project`, `organization`, `end_user` or group policy, a per-child template, a YAML policy | | Rate policies with `subject: team`, `key`, `key_model` or `end_user` (of its teams) | A `tenant` or `model` rate policy, a YAML policy | Rules, checked in the store transaction on the subject **as stored**: - The subject must belong to its organization before the write (when the policy exists) and after it. Moving a policy's subject to another organization's team, or taking over the ID of another organization's policy, is refused; an unknown subject answers the same `403`, so the answer does not reveal other organizations' team, key or user IDs. Policy IDs are gateway-wide: an ID another organization already uses answers `403` too, so prefix yours (for example with your organization's name). - A policy it writes never allows more than an enabled tenant ceiling of its organization (`422 exceeds_tenant_ceiling`): TPM and TPD at most the tenant's; a budget, plus its temporary increase, at most a tenant budget of the same or a longer period (a daily team budget is compared with a monthly tenant budget; a yearly one is not). Rate policies admit at most the tenant's requests per minute (a request-window policy counts its requests per window as a per-minute rate). A disabled policy limits nothing and is not compared. - The tenant counter still caps every request: a team policy larger than the tenant (for example one the global administrator set) never lifts it. - It lists (`GET /api/v1/admin/quota-policies`, and the `budgets` of `GET /api/v1/admin/organization`) only the policies whose subject belongs to its organization now, never the gateway's prices, settings or connections. - **A team moved out later.** When the global administrator moves a team to another organization, its policies stay and keep applying. The old organization's admin no longer lists or edits them; the new organization's admin may, and the global administrator always can. - The global administrator is not bound by tenant ceilings when it writes. ## Isolation between organizations In multi-tenant mode an organization is a tenant. Apart from the limits listed after the table, its organization admin, its team users and its keys never read, count, export, search or change another organization's data, and never reach it through a cache: | Data | What another organization gets | | --- | --- | | Request logs, log export, request detail and journey, sessions, analytics, valuation, savings and durable usage | Only its own teams' rows, filtered before every count, total and page, whether the view reads PostgreSQL or the [analytics store](/docs/features/analytics-store/). A team that moved from one organization to another is split by the organization each request ran in: neither organization reads or counts the other's side ([when a team moves](/docs/features/organizations/#when-a-team-moves)) | | Traces and spans | Only its own spans, also for a W3C trace both organizations share and for spans read from the analytics store copy | | Evaluations: datasets, runs, scores, captures, rules and their jobs, annotation queues, comments and mentions | Only its own teams'. When both organizations send the same request ID, each keeps its own capture, and a rule only ever judges its own team's ([evals](/docs/features/evals/#evaluating-real-traffic-eval_capture)) | | Prompts, skills, vector stores, files, batches, containers, fine-tuning jobs, stored responses and conversations, customers, budgets, audit and the recycle bin | Only its own. A team or organization admin shares a vector store only inside its organization | | Chat answer cache and exact cache | A cached answer is served only inside the team, or inside the organization with `share: organization` | | `previous_response_id` on `/v1/responses` and `/v1/responses/input_tokens`, with `responses_lifecycle` on | Only the key's own signed IDs; a raw provider ID answers `404` ([capabilities](/docs/features/capabilities/)) | | Other state held at the provider under its own ID | Refused before the provider with `422 provider_state_not_isolated` and the setting that fixes it: a raw `previous_response_id` without `responses_lifecycle`, a raw `conversation` without `conversations`, a container ID in Responses tools or input without `containers`, an item reference input (typed or not) or a reasoning item sent by ID without its `encrypted_content`, a provider file the request makes the provider read (a Responses `input_file` or `input_image` `file_id`, also inside a tool call output, a Chat Completions `file` part's `file_id`, a Messages `file` source or `container_upload`, a Gemini `fileData.fileUri` in the contents, the system instruction or a function response), an Anthropic Messages `container` ID, a Gemini `cachedContent`, and, on passthrough actions with a Responses, Messages, Chat or Gemini usage profile, a subpath, a body naming such state or a body the gateway cannot read. File IDs a client only replays (citations and annotations in earlier output, code-execution results) stay accepted. Stored provider prompts (`prompt.id`) and provider vector stores (`file_search`) are created by the global administrator in the shared account, not by organizations, and stay usable | | A2A agents shared by several organizations | Only its own tasks and contexts: another team's task, or a task ID the gateway never handed to the team, answers `404` (JSON-RPC `-32001`) before the agent, and `ListTasks` shows only the team's tasks, without `totalSize` ([A2A agents](/docs/features/a2a-agents/)) | Another organization's team, user, key, request, trace, capture, store or other object answers like one that does not exist: usually `404`, and `400 team_not_found` when named as a vector store's shared team. What stays shared, on purpose, because it belongs to the global administrator and makes no sense per organization: providers and their credentials, models, gateway-wide aliases, routing, guardrails, MCP servers, A2A agents, flags, plans, log destinations, retention, alert channels and the `/metrics` endpoint. Team-scoped sessions see only what they use of these (the models their keys may call, for instance), never a secret, and a few infrastructure status views (log destination delivery counters, span store and analytics store status) count every organization's traffic together. To keep the guarantee: - **Turn on `responses_lifecycle`, `conversations` and `containers` with the Responses API.** Without them, a request that continues stored state is refused in multi-tenant mode, since the gateway could not tell whose state the provider's ID names. - **Do not set `share: all` with `chat_cache_cross_tenant`** unless every organization trusts the others: it serves one organization's cached answers to all of them. - **Mind passthrough actions without a usage profile.** Their bodies are opaque to the gateway; an action the global administrator configures to address stored provider objects reaches them with the provider's own IDs. - **Prefix the IDs you choose.** Prompt, policy, score, skill-submission, MCP-submission and extension-submission IDs are unique across the gateway: an ID another organization already uses is refused (`404`, `403` or `409`), so prefix yours with the organization's name. Let the gateway generate request IDs, or prefix your own. ## What stays with the global administrator - Creating, renaming and deleting organizations, and their ceilings: allowed models, [plan ceilings](/docs/features/entitlements/#optional-organization-ceiling), budgets and rate limits. - Moving a team between organizations. - Gateway-wide settings: flags, providers and shared provider credentials, models and gateway-wide aliases, routing, guardrails, SSO, SCIM, invitations, custom roles, audit export. - Creating or changing an organization admin and any global role. ## Limits on the organization admin - It never grants more than it holds: only team-scoped roles, never `org_admin`, `admin`, `viewer` or `operator`. - It cannot edit or disable its own user (`403 own_role`). - No route makes it a global administrator. Routes outside the table above are denied (`403 role_forbidden`), as for every role (default deny). - It takes no [custom role](/docs/features/custom-roles/): binding one answers `400`, and a YAML binding makes its session invalid (fail closed). - [Native MFA](/docs/features/native-mfa/) names it `org_admin`: `admin.local_mfa.required_roles` may list `org_admin`, at sign-in and on every request alike. A policy that lists only `team_admin` does not cover organization admins; list both. - The invitations it issued are accepted only while it is still an active organization admin of that organization and the mode is on; disabling or demoting it, or turning the flag off, makes them invalid. - It never invites `org_admin` (`400`); a global administrator creates organization admins directly. - In the user inventory it sees neither itself nor other organization admins; a global administrator sees them with the role `org_admin`. - A user detail shows only that user's usage on the organization's teams, never its history elsewhere. - When the flag is turned off, or the organization is deleted, its sessions stop at the next request, and the [customer credentials](/docs/features/customer-portal/) it issued stop working (they are revoked, as when a team administrator is demoted). ## Limits - An organization admin writes no per-child quota template and no budget on YAML keys (keys declared in YAML belong to the operator); it budgets its managed keys. - A global administrator may also place a single invitation in an organization with `organization_id`; bulk rows take none. - Events written before migration 175 carry no organization; for them the audit view still matches the target's current organization. ## Upgrade Since T192, in multi-tenant mode: - a team or organization admin can no longer add another organization's team to a vector store's sharing (teams already in the list, for example shared by a global administrator, may stay); - a raw `previous_response_id` answers `404` when `responses_lifecycle` is on, so a provider whose responses the gateway cannot sign (no `"object": "response"`) cannot be continued; with `responses_lifecycle` off it, a raw `conversation` without `conversations`, container IDs without `containers`, `item_reference` inputs, Anthropic Messages `container` IDs and passthrough Responses or Messages subpaths and state-naming bodies answer `422 provider_state_not_isolated`, naming the setting that fixes it; - A2A tasks created before the upgrade are not bound to a team and answer `404` until the team starts new ones; - the durable usage view's background responses count only the reader's team, and the GitOps dry run hides rate policies, the digest and the control version from team-scoped sessions. In both modes, each team keeps its own evaluation capture of a request ID and a rule judges only its own team's. Migration 199 re-keys captures by team and request ID (existing captures keep their team and stay readable) and redacts the comment of each older judge score whose job had read another team's capture: the value stays, the comment becomes a fixed marker, `redacted_reason` is `judged_another_team_capture`, and every redaction plus the total is in the audit (`eval.score_redact`, `eval.capture_remediation` by `system:migration-199`). A score whose capture or job had already expired cannot be told apart and is left as it was. Migration 200 adds the A2A task ownership table. Migration 199 also renames the capture table, so an older replica still running during the upgrade stops capturing, judging, reviewing and erasing captures (it logs errors such as `capture_store_failed`) rather than read a capture by request ID alone, which could now be another team's; end-user erasures it fails are run again by an upgraded replica. Upgrade every replica promptly. Nothing else changes in single-tenant mode. Migration 177 adds the nullable `organization_id` to control-plane audit rows; older rows keep `NULL` and stay out of organization admins' audit views. Migration 178 adds the organization model aliases table ([Organization aliases](/docs/features/model-aliases/#organization-aliases)). Both are additive. Migration 174 adds `organization_id` and `organization_admin` to console users and adds the organization admins' teams to the effective-membership view. Migration 175 then: - confines the view: a user of an organization counts only that organization's teams, an organization admin only the teams of its organization (not when disabled, not deleted teams), with no per-row probes; - clears `organization_id` from users with a global role and adds a check that keeps it on team-scoped users; - allows `org_admin` as a native MFA subject; - adds the recorded organization to identity audit events (a trigger fills it on insert); - removes, audited as `membership.idp_remove` by `system:migration-175`, IdP-synced memberships held by a role the sync never manages (team administrators and global roles), which would otherwise administer the team. **Rollback.** The view lives in the database: an older binary sees an organization admin as a team administrator of **every** team of its organization, with no flag and no deleted-organization check. Before rolling back, disable every `org_admin` user or change its role, then remove `organization_admins` from YAML. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `POST /api/v1/admin/users/{id}/enable` | Enables a disabled console user again | # Feature plans for teams and organizations **Last updated:** 2026-11-21T09:54:10-03:00 (UTC-3) Plans add a feature ceiling to authorization. They never grant a role, route scope, model, membership or provider credential. Operational flags enable the installation; a team plan and its optional organization plan must permit the tenant operation too. The vendor's signed license controls **new classified grants and activation**, separately from the operator's plans. ## Two compatible enforcement profiles | Flag | Default and behavior | | --- | --- | | `plan_entitlements` | False. Enables the legacy four rights: MCP execution, explicitly requested exact cache, scoped prompt reads and scoped skills under their existing opt-ins. Requires PostgreSQL. | | `feature_plan_entitlements` | False. Requires `plan_entitlements`; expands admission to tenant features from the applicability catalog, including ordinary inference and public resources. Also enables the scoped prompt/skill ceilings. | | `organization_plan_entitlements` | False. Requires `organizations` and `plan_entitlements`; intersects the current organization plan with the mandatory team plan. | | `entitlement_management` | False. Requires `plan_entitlements` and `ui`; permits the existing versioned editor/API for global administrators. | All four are runtime-mutable through the feature API and Settings & sources, with dependency validation, versioning and audit. The separate `organizations` flag is boot-only. Prepare assignments before enabling either admission profile: an unassigned team or a missing right is denied. An organization without an assignment adds no extra ceiling. With the expanded mode off, ordinary inference retains its previous behavior. The legacy rights are `mcp_execution`, `exact_cache`, `prompt_scoped_read` and `skill_registry`; prompt/skill reads additionally need `prompt_entitlements`/`skill_entitlements` respectively. The expanded mode does not silently add those rights to an existing plan. ## Feature applicability The console shows the complete server-owned feature catalog with search, group and applicability filters. GET `/api/v1/admin/entitlements` publishes it as `feature_catalog` alongside the assignable `rights`. The compiled catalog classifies every flag and exposes its assignable tenant rights; GET `/api/v1/admin/entitlements` is authoritative for the current edition. | Scope | Examples | Enforcement | | --- | --- | --- | | Tenant ingress/resources | Chat, embeddings, native protocols, media, files/batches, vectors, public evals, MCP, agents, conversations and containers | Authenticated request admission; nested resource families and stateful Responses fields are checked too. | | Tenant alias policies | Auto-routing, semantic/exact cache, latency/weighted/strategy routing, retry and semantic fallback | Required configured policy rights before helper, cache or provider effects. | | Tenant scoped views | Analytics/logs and exports, scoped prompts and skills | Current eligible teams filter queries before counts/pagination; prompt/skill grants keep their transaction snapshot. Optional outputs/filters and UI presentation have their own availability. | | Operator controls | Authentication/RBAC, model/tag restrictions, quotas/budgets, guardrails, telemetry, admission, stream clocks, storage and installation administration | Remain mandatory instance policy. They are visible in the catalog but cannot be put in a tenant plan. Vendor classification can protect their administrative activation/actions. | A new flag must explicitly choose applicability; unknown/operator IDs in a plan are refused. Operator controls are never switched off for a tenant who lacks a right. Classification does not select a commercial plan: the shipped enterprise catalog is still empty. **Alias-policy contract:** a configured, enabled optional tenant policy makes its right mandatory for that alias, even if a particular stream or payload would skip the policy's execution profile. The gateway refuses instead of silently changing routing or cache behavior. Translated requests also check the canonical Chat policies they consume. Auto-routing/semantic-cache embedding helpers require the embeddings right; an operator-required moderation guardrail remains an operator action and cannot be disabled through a tenant plan. ## Declare a plan ```yaml features: plan_entitlements: true feature_plan_entitlements: true entitlement_management: true # also requires ui plan_entitlements: plans: - id: chat-team name: Chat team rights: [chat_completions] disabled: false team_bindings: - team_id: existing-team-id # actual active ID, not its name plan_id: chat-team disabled: false organization_bindings: [] # optional extra ceiling ``` | Key | Default | What it does | | --- | --- | --- | | `plan_entitlements.plans[].id` | required | Lower-case identifier the bindings name, up to 64 characters | | `plan_entitlements.plans[].name` | required | Display name, 1–120 characters without control characters | | `plan_entitlements.plans[].rights` | `[]` | The rights the plan includes; an empty list grants nothing | | `plan_entitlements.plans[].disabled` | `false` | A disabled plan denies: the teams bound to it get none of its rights | | `plan_entitlements.team_bindings[].team_id` | required | Actual ID of an existing team | | `plan_entitlements.team_bindings[].plan_id` | required | The plan that sets the team's ceiling | | `plan_entitlements.team_bindings[].disabled` | `false` | A disabled binding denies: the team gets none of the plan's rights until it is enabled again | | `plan_entitlements.organization_bindings[].organization_id` | required | Actual ID of an existing organization, including `org_default` | | `plan_entitlements.organization_bindings[].plan_id` | required | The plan that sets the organization's ceiling, intersected with each team's plan | | `plan_entitlements.organization_bindings[].disabled` | `false` | A disabled binding denies: the organization's teams get none of the plan's rights | This is a policy fragment, not a full installation. Configure the ordinary operational flags, keys, scopes and models independently. Limits: 100 plans, 5,000 team bindings and 5,000 organization bindings; removed binding rows still count. An empty-rights plan grants nothing. Binding an ID does not create the team or organization. ## Optional organization ceiling An organization's enabled plan must include the same right as the team's plan. A disabled assignment/plan denies. Use actual IDs from Organizations, including `org_default`, never a display name. The current team→organization link is read from PostgreSQL; moving a team changes the ceiling on its next admission. An absent organization assignment means **unrestricted at this layer**, not an empty grant. Consequently, removing a restrictive assignment can grant rights. Revert, YAML removal and runtime disabling of plan boundaries participate in classified-grant checks; they are not licensing bypasses. Disabling just the organization flag makes saved assignments dormant, while team enforcement remains active. Dormant assignments still protect referenced plans from deletion. Absent/empty YAML organization bindings preserve the earlier base fingerprint. Console changes override YAML per entity. Revert restores the YAML or absence, with a versioned tombstone. ## API and console Global administrators manage Plans & entitlements. Viewer/operator/team roles cannot access the global catalog. CSRF, same origin, strict canonical JSON and a 16 KiB mutation limit apply. A stale entity version or YAML fingerprint is 409; the editor retains the reviewed draft until an explicit reload/review. Creation starts at version 0. | Endpoint | What it does | Body | | --- | --- | --- | | `GET /api/v1/admin/entitlements` | Effective plans, assignments, rights, applicability and safe license availability | none | | `PUT /api/v1/admin/entitlements/plans` | Creates or replaces a plan | `{base_fingerprint,version,plan:{id,name,rights,disabled}}` | | `DELETE /api/v1/admin/entitlements/plans` | Removes a console plan or reverts a YAML one | `{base_fingerprint,version,id}` | | `PUT /api/v1/admin/entitlements/teams` | Binds a team to a plan | `{base_fingerprint,version,binding:{team_id,plan_id,disabled}}` | | `DELETE /api/v1/admin/entitlements/teams` | Removes a team's console binding or reverts it to the YAML | `{base_fingerprint,version,team_id}` | | `PUT /api/v1/admin/entitlements/organizations` | Binds an organization to a plan, its ceiling | `{base_fingerprint,version,binding:{organization_id,plan_id,disabled}}` | | `DELETE /api/v1/admin/entitlements/organizations` | Removes an organization's console binding or reverts it | `{base_fingerprint,version,organization_id}` | API access provides complete examples that obtain current fingerprints/versions and require explicit active IDs. Mutations revalidate the administrator and applicable live entity, then commit CAS, licensing admission and correlated audit atomically. A referenced console-only plan cannot be removed. No credential appears in the catalog. Scoped configuration adds `feature_access`: a boolean union of the session's own eligible teams, used for visibility and presentation. Operational `features` remain unchanged. A union does not authorize a selected team: the API narrows current memberships for each action before querying. Missing/malformed projection denies scoped UI availability; role/flag/projection changes clear held reports, exports, details and drafts. ## Admission, failure and revocation - Public requests load one bounded coherent team/organization rights snapshot after identity/scopes, before dispatch. Configured policy/cache checks reuse it only for that admission. Fresh internal jobs/helper HTTP calls replace inherited decisions; there is no cross-request positive-grant TTL cache. - Models and model details hide aliases outside the plan before external wildcard discovery. Plans never broaden a key's model allowlist. - In expanded mode, stateless Responses use explicit `store:false`. Stored/default-stored/background/previous-response operations require `responses_lifecycle`; conversation and hosted-container use require their corresponding rights, including token-count bodies. Existing signing/ownership checks remain mandatory. - Every new Realtime response checks current rights, including the busy client branch, independently of quota activation. Existing in-flight responses retain their admitted state. A provider-initiated turn can start before the gateway observes `response.created`; denial follows the existing cancellation/accounting path, not a zero-provider-effect guarantee. - Normal entitlement denial is 403; hidden prompt/skill/model detail keeps 404. Malformed assigned state fails closed with denial or hidden detail; unavailable storage/catalog produces 503. Live revocation applies to the next admission, even for a warm cache. Actual request/trace correlation is preserved without recording prompt content. ## License and activation The [vendor commercial catalog](/docs/operate/licensing/#enterprise-classification-at-build-time) stays empty until the owner defines the cutoff. Once classified, adding/reactivating rights, assigning plans, broadening reverts and removing ceilings need an available signed license. Free additions and restrictive recovery remain possible; the existing classified administrative-action policy still applies. Plan/license status never grants RBAC. Grant checks run at the locked transaction boundary. A control-version/shared lock detects concurrent license replacement; terminal trial state is checked under its lock. Expiry is evaluated there rather than captured before waiting. An unchanged established grant is not removed merely because a license expires; ordinary authorization, policy and budget checks still apply. YAML is also an activation boundary. Migration 104 records approved effective plan bases and active classified flag IDs. First/new classified activation requires a valid license. Unchanged approved activation survives expiry and restart. Dormant YAML plan definitions are not activated merely by booting with plan enforcement off. Feature activation, its YAML approval, CAS and audit share one transaction, so rejected activation leaves no unusable persisted override. A nonempty commercial edition requires PostgreSQL approval storage even when classified features are currently off; the default empty edition is unchanged. ## Upgrade and recovery Migration 103 added organization assignments; migration104 adds private durable approval state. Neither rewrites existing bindings, usage, trial records or commercial classification. Back up and roll out compatible binaries before enabling the new mode; all replicas need the same YAML. Older binaries refuse newer schema history. Revert changes policy, not database schema. For a rejected new YAML activation, restore the last approved configuration or supply valid signed activation and restart. Never reset trial/approval rows to extend access. Use the normal license API/console for managed renewal. Operator-controlled full backup/binary rollback remains the documented offline trust limitation. Scoped task evidence is separate from final branch/release qualification. ## See also - [Access control](/docs/features/access-control/). - [Organizations](/docs/features/organizations/). - [Licensing](/docs/operate/licensing/). - [Console](/docs/features/console/). # Key expiry, tags and lifecycle policy **Last updated:** 2026-11-21T10:44:38-03:00 (UTC-3) A key can have **no expiration**, an explicitly selected duration or an absolute UTC deadline. Creation and rotation default to **Never**. An operator policy can limit a duration the user explicitly selects; it never makes a nonexpiring choice expire. There is no automatic90-day default or mandatory1-year rotation ceiling. ## Choose an expiry For managed creation or immediate rotation, send at most one of: | Choice | Request | | --- | --- | | Never | Omit both expiry fields, or send one as `null` | | Relative duration | `"expires_in": "7d"` | | Absolute date | `"expires_at": "2030-04-20T15:30:00Z"` | `expires_in` accepts a positive integer followed by `s`, `m`, `h`, `d` or `w`, within the published signed-duration representation bound. Empty strings, zero, negative, fractional and overflowing durations are rejected. Both field names together are rejected even when one is null. Absolute dates must be valid RFC3339 timestamps after the database clock; timezone offsets are compared as UTC instants. Responses may carry a valid RFC3339 offset; compare the instant rather than a string prefix. The API supports fractional precision; the console preserves an existing timestamp when it is untouched rather than silently rounding it. Relative time uses PostgreSQL time after the mutation locks, not the browser or gateway host clock. A configured finite maximum rejects an excessive selected expiry; it does not clamp it or inject an expiry into Never. With no maximum, there is no configured lifetime ceiling; a syntactically representable future absolute date remains a user choice. **In Virtual keys:** choose Never, Duration or Date in the creation/rotation form. The date field is explicitly UTC. Switching to Never clears the other choice; a hidden stale field cannot quietly keep an expiry active. For [scheduled rotation](/docs/features/key-rotation/#scheduled-activation), a relative duration begins at **actual activation**. An absolute date stays fixed; an activation delayed beyond that date is blocked without retiring the old credential. ## Declarative defaults ```yaml features: key_policies: false key_metadata_tags: false scheduled_key_rotation: false key_expiry_warnings: false security: key_policy: max_expiring_lifetime: 0s require_owner: false required_tags: [] key_lifecycle: interval: 30s state_timeout: 5s batch_size: 100 warning_before: [168h, 24h, 0s] ``` The four flags default off. Policy and warning processing are operator controls; metadata tags and scheduling also require applicable tenant/organization plan rights and the action's live permissions. A flag grants no permission. Scheduling requires the existing `key_rotation` feature; creation still uses `identity_management`. The compiled defaults work without declaring these blocks. An explicit YAML value wins over its default; a versioned console/API override wins over the YAML until reverted. File edits need rollout; the managed override applies through normal replica refresh. New operations capture the effective policy. The console shows effective values, defaults, source and override/base conflicts; metadata never proves a worker or notification succeeded. ## Governance policy Keys of the `security.key_policy` block: | Setting | Default | Meaning | | --- | --- | --- | | `security.key_policy.max_expiring_lifetime` | `0s` | No finite maximum. A nonzero single-unit duration constrains only an explicitly expiring managed issuance | | `security.key_policy.require_owner` | `false` | Optional prospective requirement for an active authorized owner | | `security.key_policy.required_tags` | `[]` | Optional required static key-tag names; at most16 unique valid names | This is a global policy. It does not add another team-policy override system. Existing team model/scope limits remain cumulative and unchanged. Full governance is checked on managed creation, immediate rotation and scheduled activation. Enabling a requirement does not silently revoke existing traffic. A legacy key missing both owner and tags can be repaired one field at a time: owner changes check the owner requirement; tag changes check tag requirements. Untouched legacy drift remains visible until repaired. A required valid owner/tag cannot be removed, and full issuance/rotation waits until all requirements are satisfied. Owner assignment retains its existing global-administrator authority. Static tag edits use the existing scoped `keys:rotate` authority, plus the metadata feature and applicable plan/license ceilings; this grants no model, route, team membership or console role. Operators retain their established lack of key-management authority. A required-tag policy can be staged with `key_policies` off. Activating it requires `key_metadata_tags`; whole-configuration validation prevents turning off that feature beneath an active requirement. The same applies to the existing ownership feature when requiring an owner. Existing tag metadata is preserved when controls are off. Explicit tag writes and clears remain guarded; omission in unrelated actions preserves authoritative metadata. ## Static key tags Tags are administrative metadata on the key, such as: ```json {"app":"support-api","environment":"production"} ``` At most16 name/value pairs are accepted, each using the published64-byte token grammar. Keep secrets out of tags. These are separate from client-supplied `X-Gateway-Tags`, request attribution requirements, routing conditions and spend tracking; the gateway never copies them into those surfaces or telemetry. `GET /api/v1/admin/keys/{id}/tags` returns the key ID, tags, current `version` and a safe write capability. `PUT` replaces the map with that captured version. A conflicting edit returns409; it never overwrites an unseen change. Team access is checked before returning metadata, and IDs from other teams remain404. ## Policy API and console The global editor lives in **Virtual keys**. Authorized administrators edit; global readers inspect. Scoped users receive only safe applicable policy/action notices, never the global override or lifecycle administration. | Endpoint | Action | | --- | --- | | `GET /api/v1/admin/security/key-policy` | Effective policy/lifecycle, defaults, sources, base fingerprints and safe edit rights | | `PUT /api/v1/admin/security/key-policy` | Save an override with current `version` and `expected_base_fingerprint` | | `DELETE /api/v1/admin/security/key-policy` | Revert to YAML/defaults with the same guards | Writes retain live role/license checks, global CAS, same-origin session/CSRF and audit. Equivalent duration units have the same baseline identity; a real YAML policy change requires explicit review of a stale override. A draft never silently rebases after409 or survives known permission loss. Reload after restoring access. ## Expiry notifications Keys of the `security.key_lifecycle` block: | Lifecycle setting | Default | Bounds | | --- | --- | --- | | `security.key_lifecycle.interval` | `30s` | 1s–1h | | `security.key_lifecycle.state_timeout` | `5s` | 100ms–1m, whole milliseconds; one state operation | | `security.key_lifecycle.batch_size` | `100` | 1–1000 | | `security.key_lifecycle.warning_before` | `[168h,24h,0s]` | At most8 unique thresholds,0–8760h; empty disables notices | With `key_expiry_warnings`, the worker records durable notices for the current explicitly expiring managed credential. Never produces no expiry event. The zero threshold is an expired notice, so a missed earlier window can still produce an accurate event after recovery. Events are deduplicated by key, credential generation, actual expiry and threshold, then delivered through existing [alert channels](/docs/features/alerting/). Payloads contain identifiers/deadlines and request/trace correlation, never a secret, confirmation nonce, arbitrary tag value or inference content. External channels require their existing flags, policy and configuration; generating an event does not certify delivery. The console/audit/delivery state makes these stages distinct. Disabled processing pauses future evaluation; it never changes a credential's chosen deadline or revocation. Existing notification retry/delivery semantics apply; a transport retry does not create another expiry event. ## YAML bootstrap keys Static keys can declare an optional fixed deadline: ```yaml keys: - id: local-app principal: example-app team: platform kind: service_account sha256_env: GATEWAY_CLIENT_KEY_SHA256 allowed_models: [chat-default] scopes: [route:chat] expires_at: 2030-04-20T15:30:00Z ``` Omit it for no expiration. A static deadline is startup-owned and read-only in the console; edit YAML and roll out. There is no relative boot duration that renews on restart. Managed secret issuance and confirmation remain authenticated API/console actions; YAML does not execute a secret issuer or bypass possession confirmation. ## Upgrade and recovery Upgrade all replicas before using the new flags/fields, back up PostgreSQL and apply the new key-lifecycle migration through the existing [procedure](/docs/operate/operations/). Earlier binaries cannot enforce or interpret the new schema/profile; use the pre-upgrade backup/configuration procedure for rollback. Authentication still applies credential expiry, parent/team revocation, ownership, route/model rights and existing cache visibility. Pending prepared credentials never authenticate. No policy makes an expired or revoked credential valid again. See [rotation](/docs/features/key-rotation/) for lost-response recovery, cancellation and the safe handoff sequence. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `PUT /api/v1/admin/keys/{id}/tags` | Replaces a key's static metadata tags; `{}` clears them | # Key rotation **Last updated:** 2026-11-21T09:54:10-03:00 (UTC-3) Change a virtual key's secret without taking applications down. The gateway issues a new secret, and the old one keeps working during an overlap window you choose, until the applications migrate. The key stays the same: ID, team, models, scopes, RPM and usage history do not change. The replacement may have no expiry; Never is the default unless you explicitly choose a duration or date. Flag: `key_rotation`, which requires `identity_management`. For operator encryption/session keys, use the separate [keyring maintenance guide](/docs/security/keyring-rotation/). The workflows below rotate an inference client credential. ## How to use it **In the console:** **Virtual keys → Credential rotation** shows the key's secret history, generates a new one with overlap and retires the old one before its deadline (**Retire now**). **Through the API:** | Endpoint | What it does | | --- | --- | | `GET /api/v1/admin/keys/{id}/credentials` | History and the current `version` | | `POST /api/v1/admin/keys/{id}/rotate` | Generates the new secret | | `POST /api/v1/admin/keys/{id}/credentials/{credential_id}/retire` | Retires an old secret now | `rotate` takes: | Field | Values | | --- | --- | | `version` | The version read from the history | | `overlap_seconds` | 0 to 86,400 (up to 24 h) of coexistence between the old and the new | | `expires_at` | Optional absolute UTC deadline; omit/null for Never | | `expires_in` | Optional positive integer duration with s/m/h/d/w; exclusive with expires_at, resolved from database time | The `201` response carries the new secret **only once**, with `Cache-Control: no-store`. Distribute it to the applications during the overlap. ## How it works - At the end of the overlap, the old secret stops authenticating on every replica. By default, the database checks the deadlines on each authentication, without a scheduled job. The optional [managed credential cache](/docs/features/managed-key-cache/) preserves the credential expiry/retirement deadline captured by that same SQL lookup; it never extends the overlap. Local successful rotation/revocation invalidates the serving replica, while earlier changes on another replica have the explicitly configured bounded cache visibility window. - The overlap never extends the old secret: it goes away at whichever comes first, the end of the overlap or its original expiration. - **Up to two secrets** are valid at the same time. A new rotation while an old one is still active returns `409 rotation_pending`: retire the old one or wait. - Two simultaneous rotations of the same version: one succeeds, the other gets `409`. - Only active, unexpired keys can be rotated. - A managed key's [source CIDR ceiling](/docs/security/source-ip-controls/) and independent source-policy version remain on the parent key; credential rotation does not clear or broaden them. - **Retire now** retires an old secret, idempotently. To invalidate the current one, revoke the key. - Revoking the key or deleting the team invalidates every secret. Requests already authenticated may finish. - Only the SHA-256 hashes of the secrets are stored. The history shows, with no secret or hash: ID, generation, predecessor (`replaces_id`), creation, expiration, scheduled or completed retirement and the state (`active`, `retiring`, `retired`, `expired`, `key_revoked`). Each generation keeps the issuance `request_id`, which links to the `key.rotate` event in the audit trail. Pagination by `limit` (1 to 100) and `next_before_version`. ## Who can do it - Reading with `keys:read` (viewer reads the metadata); rotation with `keys:manage`, a same-origin session and CSRF. Operator has no access to keys. - Team roles see only their own teams' keys; IDs from other teams return 404. - A `team_admin` does not rotate keys with `*`, `route:*` or `mcp:read`, and the key must stay within the team policy: rotation does not broaden access. ## Limits - YAML keys are not rotated from the console: change the hash in the Secret and roll out. Do not put a managed key's secret in the YAML. - Scheduled activation is the explicit prepared/confirmed profile below. There is no blind recurring key generation or secret delivery to Vault/KMS, email or generic webhooks. Expiry notices are metadata-only. - Analytics keeps using the key's stable ID, not the ID of each secret. - Turning off the flag hides management and history, but the deadlines and revocations still apply. - Going back to a gateway version without rotation ends the overlap: old secrets may stop before their deadline. Do not restore an old backup to recover a secret, because that can reactivate revoked keys. ## Scheduled activation Prepare the next credential in advance, distribute its secret, then explicitly confirm possession before it can activate at the chosen time. This is a one-shot schedule. It never generates an undistributable secret in a background job. 1. Read `GET /api/v1/admin/keys/{id}/rotation-schedule` and credential history. Keep the schedule `version` and active `credential_version`. 2. `POST` that endpoint with both versions, future `activate_at`, explicit `overlap_seconds` and an optional expiry choice. The201/no-store response shows the new secret and an independent confirmation nonce once. Save them securely. The staged secret does not authenticate and the old credential is unchanged. 3. After distributing the secret, `POST /api/v1/admin/keys/{id}/rotation-schedule/confirm` with the current schedule `version` and `confirmation_nonce`. Live permissions, plan/license, policy and nonce are checked again. Unconfirmed preparation cannot retire the current credential. 4. At or after the chosen time, the worker atomically activates the known hash using PostgreSQL time and rechecks current actor/team/parent/policy/entitlement state. The overlap starts at actual activation, so a delayed worker does not consume it before the new secret works. 5. `DELETE /rotation-schedule` with the current version cancels a pending schedule; it never retires the current credential or reactivates old material. The console places these actions in the existing **Credential rotation** panel. Secret/nonce state is volatile: abandonment, logout and authority changes clear it. No read endpoint retrieves either value. A lost prepare response leaves an unarmed schedule: inspect its metadata, cancel it and prepare again. Do not confirm a schedule whose secret was not retained. A scheduled `expires_in` means validity **after actual activation**. A fixed absolute deadline never moves; if it has passed when the worker executes, activation is blocked and the old credential is not retired. Never remains Never. The selected prospective [key policy](/docs/features/key-policy/) is revalidated; it never injects an expiry or silently clamps the user's choice. Named-user demotion/disable, team deletion, parent revocation, stale parent versions or unavailable grants block activation. A schedule prepared with the shared/bootstrap administrator is durable operator intent: rotating/disabling that interactive console token does not cancel it. Use explicit cancellation or operator feature controls; named-user schedules retain their live identity check. Transient database/configuration-refresh faults leave an armed intent eligible for retry. An explicit authorization/policy/grant failure records a blocked intent: correct the cause, cancel it and prepare/confirm a fresh schedule. Restoring a permission alone never silently resumes a business-blocked rotation weeks later. A finite old deadline still applies if chosen earlier; preparation rejects a desired activation at or after that known deadline. Monitor blocked schedules rather than assuming a desired date proves execution. Preparation, confirmation and execution under `scheduled_key_rotation` require `key_rotation`, a live scoped rotation permission and applicable team/organization plan rights. Historical scoped reads and cancellation of a pending schedule remain available under the existing live key authority when new processing/grants are off or unavailable; cancelling never changes the current credential. A flag or coarse console capability grants no selected team's access. Disabling processing leaves the current credential intact. The worker performs no secret delivery; existing [expiry notices](/docs/features/key-policy/#expiry-notifications) contain identifiers/deadlines only. Prepared material is excluded from every authentication path and the optional managed credential cache. Only the hash and confirmation hash are stored. Credential generations remain unique across cancellation; the active parent version changes only on actual activation. Concurrent prepare/confirm/cancel/activation uses its own schedule CAS and the existing user→control→team→key lock order. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `POST /api/v1/admin/keys/{id}/rotation-schedule` | Prepares the next credential now and returns its secret and confirmation nonce once | | `DELETE /api/v1/admin/keys/{id}/rotation-schedule` | Cancels a pending schedule; the working credential stays | ## See also - [Key expiry, tags and policy](/docs/features/key-policy/). - [Access control](/docs/features/access-control/). - [Key owners](/docs/features/identity-ownership/). # Disable and trash **Last updated:** 2026-11-22T06:50:00-03:00 (UTC-3) Disabling is the everyday, reversible action for managed keys, teams and console users: the object stops working at once and comes back unchanged when you enable it. Deleting stays a separate action: it revokes at once and keeps a tombstone for audit in the [recycle bin](/docs/features/access-control/). With `trash_restore`, an administrator can restore a tombstone within a retention window; a restored key always gets a **new** secret, so the old one never works again. ## How to turn it on ```yaml features: identity_management: true reversible_disable: true # off by default; disable/enable keys, teams and users recycle_bin: true # the read-only tombstone list trash_restore: true # off by default; requires recycle_bin and reversible_disable trash: retention_days: 30 # 1 to 365; how long a tombstone can be restored ``` | Flag | Default | What it turns on | | --- | --- | --- | | `reversible_disable` | `false` | Disable and enable as the reversible action for managed keys, teams and console users: a disabled key, or every key of a disabled team, stops authenticating at once and works again with the same secret when enabled; delete stays the separate tombstone action. Requires `identity_management` | | `recycle_bin` | `false` | The read-only list of tombstones of deleted keys, teams and workloads, with who deleted them | | `trash_restore` | `false` | Restores a deleted key or team, or a disabled user, within `trash.retention_days`; a restored key always gets a new secret. Requires `recycle_bin` and `reversible_disable` | The three are operator flags and can be switched in the console. They need PostgreSQL (migration 185 adds `disabled_at` to keys and teams). ## Disable and enable | Object | Disable | Enable | While disabled | | --- | --- | --- | --- | | Managed key | `POST /api/v1/admin/keys/{id}/disable` | `POST .../keys/{id}/enable` | The key answers `401`; the same secret works again after enable | | Team (console) | `POST /api/v1/admin/teams/{id}/disable` | `POST .../teams/{id}/enable` | None of its keys authenticate; nothing else changes | | Console user | `DELETE /api/v1/admin/users/{id}` (as before) | `POST .../users/{id}/enable` | No token or session works; sessions issued before the disable stay invalid after enable | - In the console: **Disable** / **Enable** in Virtual keys, **Disable team** / **Enable team** in Teams and **Enable** on a disabled console user. - A revoked key cannot be enabled (`409 key_state`); revoke stays final. A YAML team is changed in YAML (`409 yaml_owned`). A SCIM-managed user follows its identity provider (`409 scim_managed`), and a user awaiting a JIT decision is approved or rejected instead (`409 jit_pending`). `POST /users/{id}/enable` itself has no window: disabling a user is the reversible action. - A disabled key or team is also refused for JWT inference and customer portal credentials. The replica that handles the change drops its cached key lookups at once; with the [managed key cache](/docs/features/managed-key-cache/) another replica may keep a verified entry until its window ends, as for any revocation. - Who: key actions need `keys:manage` (team administrators for their teams, with membership delegation); teams need `teams:manage`; users need `users:manage`. An organization admin acts only inside its organization. - **Enable needs the disabling scope.** A disable records the scope of its actor (migration 186, `disabled_scope` on keys and teams): `global` (a global administrator, an operator or the shared bearer), `organization` (an organization admin) or `team` (a team administrator or a member with the delegated key action). Enable needs an actor of at least that scope: a team administrator cannot enable a key that an organization or global administrator disabled, and an organization admin cannot enable a key or team that a global administrator disabled (`403 disabled_by_wider_scope`). Each scope can undo its own disables and narrower ones. A key or team disabled before migration 186 has no recorded scope and counts as `global`. Delete and restore do not undo it either: a key disabled by a wider scope than the restoring administrator is restored with its new secret but still disabled. - Audit: `key.disable`, `key.enable`, `team.disable`, `team.enable` and `console_user.enable`, with the actor and the request ID. ## Delete and the recycle bin Delete keeps its current meaning: a key is revoked and tombstoned, a team is tombstoned and its keys revoked, a user is disabled. **Settings → Recycle bin** (`GET /api/v1/admin/recycle-bin`) lists the tombstones with who deleted them and the request ID. An organization admin sees only its organization's tombstones. ## Restore With `trash_restore`, the list answers `"restore": true`, `"trash": {"retention_days": 30}` (the effective `trash.retention_days`, also shown on the page), and a `restorable_until` on each key, team or user still inside the window. **Restore** (`POST /api/v1/admin/recycle-bin/{kind}/{id}/restore`) does: | Kind | Result | | --- | --- | | `key` | The key is live again with a **new secret**, shown once (`no-store`). Every earlier credential is revoked, so the old secret never authenticates again; pending rotation schedules are cancelled and JWT bindings that named the key are disabled until bound again. The key's team must be live (`409 parent_deleted`). A key revoked before it was deleted stays revoked (`409 key_revoked`) | | `team` | The team is live again. The keys revoked when it was deleted stay revoked and its workloads stay deleted: issue new keys. The organization must be live; the name must be free (`409 name_taken`) | | `user` | The same as enable, but only inside the window: sessions from before stay invalid | ```json POST /api/v1/admin/recycle-bin/key/vk_3f1c.../restore 200 {"key": {"id": "vk_3f1c...", "team": "team_7a...", ...}, "secret": "gw_..."} ``` - Who: a global admin, or an organization admin for its own organization (`recycle_bin:restore`). Team administrators, viewers and operators cannot restore. Another organization's tombstone answers `404`. - Outside the window the answer is `409 restore_window_passed`; the tombstone stays for audit. Workloads cannot be restored. - Audit: `key.restore`, `team.restore` and `console_user.enable`. ## Other objects Aliases, providers, MCP servers and guardrails already have a reversible off switch (`enabled: false` or `disabled`) and a delete; they are not part of the recycle bin. ## Upgrade notes - An older binary ignores `disabled_scope` (migration 186): it lets any administrator who can reach the key enable it again. An older binary also ignores `disabled_at`, so a disabled key or team would authenticate again: enable them (or delete them) and turn the flags off before rolling back. Remove `trash` and the flags from YAML too. ## See also - [Keys, teams and roles](/docs/features/access-control/) · [Key lifecycle](/docs/features/key-policy/) · [Organizations](/docs/features/organizations/) # Managed credential cache **Last updated:** 2026-11-22T06:50:00-03:00 (UTC-3) The optional managed credential cache reduces repeated authentication lookups for previously verified managed bearer keys. It keeps bounded private snapshots in the running gateway process. It does not cache prompts, model responses, administrative sessions or cleartext API keys, and needs no additional cache service. The default is unchanged: `features.managed_key_cache: false`, fresh TTL `0s` and stale-on-database-error window `0s`. Valid managed credentials are checked against PostgreSQL on each request by default; the existing short negative cache for unusable credentials remains separate. ## Configure the profile ```yaml features: managed_key_cache: true security: managed_key_cache: ttl: 5s stale_on_database_error: 0s max_entries: 4096 max_bytes_mib: 8 ``` This example enables a five-second fresh authentication cache. Stale acceptance remains off. An operator may explicitly select a bounded stale window, for example `30s`, when the limited availability profile below is appropriate. A flag enables behavior; it never grants routes, models, a team, a role or a plan right. | Parameter | Default | Accepted values | | --- | --- | --- | | `features.managed_key_cache` | `false` | Operator control; YAML, feature API and **Settings & sources** | | `security.managed_key_cache.ttl` | `0s` | Go duration 0–60s, in whole milliseconds; empty means 0s | | `security.managed_key_cache.stale_on_database_error` | `0s` | Go duration 0–5m, in whole milliseconds; empty means 0s | | `security.managed_key_cache.max_entries` | `4096` | Effective 1–65536; omitted/raw 0 selects 4096 | | `security.managed_key_cache.max_bytes_mib` | `8` | Effective 1–64 MiB; omitted/raw 0 selects 8 | Unknown/duplicate/wrong-case/null fields and fractional or nondecimal capacity inputs are refused. YAML uses a natural mapping with typed values. PUT replaces the complete four-field policy; it is not a partial patch. Effective durations are normalized. Cache byte accounting bounds retained snapshots; it is not a measurement of the process's resident memory. ## Which lookups are eligible The profile applies to **new plain managed-bearer authentication lookups** with a PostgreSQL-produced credential deadline proof. It never invents an identity for an unknown key. Readers that do not supply the required proof remain live. Declared YAML keys keep their existing behavior; JWT mapping, ephemeral realtime issuing-key validation and administrative sessions keep their live checks. Positive caching is bypassed whenever any feature below is on, even if a particular key appears to have no requirements or owner: - `attribution_requirements`: key/team attribution rules must stay authoritative so a new end-user requirement cannot be missed. - `identity_ownership`: financial ownership must stay authoritative so a rebind cannot charge an old owner or miss a new owner's budget. - `mcp_user_oauth`: selecting a user's OAuth credential must use the current key owner, including when financial ownership is off. - `source_ip_controls`: a newly tightened managed-key source ceiling must be read from the authoritative lookup; an older unrestricted cache entry cannot grant admission. The normal team, organization, RPM, quota and plan checks also remain live. If they need PostgreSQL and it is unavailable, the request still fails closed even when authentication used a cached snapshot. Enabling the cache therefore does not promise that every inference survives a database outage. The safe policy panel explains each bypass reason. ## Freshness, failures and revocation A successful lookup anchors both windows at the **start of that lookup**. Fresh hits may use that snapshot before its TTL ends. Afterward, a stale snapshot may be used only after an actual permitted transient database/network failure or internal database lookup timeout, and only while the original request is still active. With TTL 0 and a positive stale window, healthy requests keep refreshing storage; there is no fresh-hit window. For example, a five-second TTL plus 30s stale allowance permits at most 35s of cache-induced age from that successful lookup's start. A credential that expires or retires earlier wins: the cache never extends its deadline. The proof uses the same credential SQL's earliest expiry/retirement and database observed time, combined with local elapsed/wall deadlines. Slow reads, hits, retries, failed refreshes, ordinary host suspend or wall-clock changes cannot renew acceptance. Authoritative absence/revocation, caller cancellation, exhausted lookup admission and nontransient SQL authorization/schema failures never authorize stale fallback. An expired proof is unusable. A successful refresh replaces the snapshot; a failed refresh does not move either deadline forward. Database recovery returns requests to normal authoritative lookup/refresh. The replica handling a successful authentication-affecting key/team/owner mutation invalidates its local state and fences older in-flight fills. Other replicas may retain a previously verified snapshot until its explicit cache window and credential deadline expire; there is no immediate cross-replica revocation guarantee for this opt-in profile. The bound concerns this cache, not replication lag in an independently configured database. Use the authoritative PostgreSQL endpoint for identity decisions. Snapshots and results are deep-cloned. Digests, private proof metadata and mutable caller fields cannot leak through shared returned objects. Plaintext bearers are never retained, logged, exported or persisted by the cache. Restart loses every positive entry; a cold process cannot authenticate an uncached managed key during a database outage. PostgreSQL remains mandatory at startup and for the platform's persistent state. ## Manage through the console or API **Settings & sources → Managed credential cache** shows the configured/effective policy, source, reviewed base, eligibility and process-local counters. A global administrator may stage a policy while the operational flag is off. Global viewers and operators get the safe read-only panel; operators do not gain access to unrelated configuration panels or private values. Conflicts preserve the originally reviewed version/fingerprint until explicit reload and review. Loss of authority discards pending edits and rejects late replies. | Method | Endpoint | Purpose | | --- | --- | --- | | `GET` | `/api/v1/admin/security/managed-key-cache` | Safe effective policy, source, eligibility and local counters | | `PUT` | Same | Replace all four fields with global version and current YAML semantic fingerprint | | `DELETE` | Same | Revert the policy to YAML/defaults with both guards | Writes require global administrator `features:manage`, the existing same-origin session and CSRF controls. Successful PUT/DELETE returns 204; fetch GET afterward for the new version/state. A scoped inference key does not authorize these administrative routes. GET returns `version`, `base_fingerprint`, `stored_base_fingerprint`, `base_mismatch`, `source` (`default`, `yaml`, `console`), `override` (policy or null), normalized `effective` (`ttl`, `stale_on_database_error`, `max_entries`, `max_bytes_mib`; the console shows the capacity as **Effective capacity**), `enabled`, `active`, `bypass_reasons`, `restart_required: false`, `applies_to: new_managed_bearer_lookups` and `cache`. Here `enabled` is the operational flag and `active` means policy eligibility, not healthy storage, a valid current credential or a permission grant. Finite bypass reasons are `feature_disabled`, `zero_windows`, `attribution_requirements`, `identity_ownership`, `mcp_user_oauth`, `source_ip_controls` and `base_mismatch`. `cache` contains `entries`, accounted `bytes`, `hits`, `misses`, `stale_hits` and `evictions` for the serving replica/cache instance. A stale authentication hit is not proof that subsequent policy checks or inference succeeded. Counters contain no key IDs, digests, tokens or tenant inventory and do not aggregate other replicas. ### Complete policy update example Use your existing authenticated console cookie file and CSRF token. The snapshot contains safe policy metadata only; both guards come from that exact read. ```sh BASE_URL='http://localhost:8080' : "${COOKIE_JAR:?Set the authenticated console cookie file}" : "${CSRF_TOKEN:?Set the session CSRF token}" SNAPSHOT=$(mktemp) trap 'rm -f "$SNAPSHOT"' EXIT curl --fail-with-body -sS -b "$COOKIE_JAR" \ "$BASE_URL/api/v1/admin/security/managed-key-cache" > "$SNAPSHOT" python3 -c 'import json,sys; s=json.load(open(sys.argv[1])); json.dump({"version":s["version"],"expected_base_fingerprint":s["base_fingerprint"],"managed_key_cache":{"ttl":"5s","stale_on_database_error":"0s","max_entries":4096,"max_bytes_mib":8}},sys.stdout)' "$SNAPSHOT" | \ curl --fail-with-body -sS -b "$COOKIE_JAR" -X PUT \ -H "X-CSRF-Token: $CSRF_TOKEN" -H 'Content-Type: application/json' \ --data-binary @- "$BASE_URL/api/v1/admin/security/managed-key-cache" ``` Review the policy before executing it. It does not enable the flag. For DELETE, submit only `version` and `expected_base_fingerprint` from the current GET. Authentication/CSRF/permission failures retain their usual 4xx; version or base mismatch returns 409; invalid policy is refused; storage/control refresh failure returns 503. No secret is part of this policy API. ## Policy changes and recovery A policy publication flushes local positive state, including an explicit identical PUT. Other replicas apply the new control version through the existing refresh loop. Requests with older captured configuration cannot reconfigure the shared cache backward. New policies apply to new lookups without a restart; existing admitted requests retain their normal operation semantics. A semantic YAML base change does not silently preserve a broader console override: `base_mismatch` disables positive cache use/fill and shows the desired override for review. Explicitly review/save against the current fingerprint, or DELETE to revert. Flags, sensitive-feature bypasses and credential proof remain separate gates. Migration 117 adds only the dedicated typed policy override. Use the normal backup/migration procedure before the new release when automatic migration is off. Upgrade all replicas before enabling the feature. No cache entries, bearer secrets or deadline proofs are stored in that table. Older binaries do not understand the new configuration/schema; use the established pre-upgrade backup/configuration rollback procedure. Real local PostgreSQL and controlled gateway/provider fixtures validate this boundary; they do not certify an external provider account or a managed-cloud deployment. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `PUT /api/v1/admin/security/managed-key-cache` | Replaces the managed key cache policy at the current version | | `DELETE /api/v1/admin/security/managed-key-cache` | Reverts the cache policy to the YAML and drops this replica's cached positive answers | ## See also - [Access control](/docs/features/access-control/) and [credential rotation](/docs/features/key-rotation/). - [Financial ownership](/docs/features/identity-ownership/) and [attribution/budget controls](/docs/features/quota-governance/). - [Response cache](/docs/features/feature-cache/), a separate feature. # Key owners and workloads **Last updated:** 2026-11-22T07:30:00-03:00 (UTC-3) Every key can have an **owner**: a console user or a **workload** (agent, job, service) on the same team. That way, when a cost spike shows up or a key leaks, you know who is accountable for it, you can filter the logs by owner, and, if needed, revoke all of a workload's keys at once. Flag: `identity_ownership`. The owner **does not change what the key can do**: models, routes, team policy, RPM, quotas, and cache still come from the key and the team. The only access rule tied to the owner only takes away: a key whose owner is a deactivated user is refused. ## How to turn it on ```yaml features: identity_ownership: true # requires identity_management, team_management, console_users, and PostgreSQL workloads: - id: billing-batch # declared IDs cannot start with wl_ team: finance name: Billing batch responsible: usr_0123456789abcdef0123456789abcdef keys: - id: billing-yaml team: finance owner: {kind: workload, id: billing-batch} ``` | Key | Default | What it does | | --- | --- | --- | | `workloads[].id` | required | Unique identifier; declared IDs cannot start with `wl_`, which marks console-created workloads | | `workloads[].team` | required | The team that owns the workload; a declared workload cannot move to another team | | `workloads[].name` | required | Display name, 2–128 bytes of UTF-8 on one line | | `workloads[].description` | empty | Up to 512 bytes | | `workloads[].responsible` | empty | Optional `usr_…` ID of the console user answerable for the workload; the user must exist | | `workloads[].disabled` | `false` | A deactivated workload keeps its keys working and accepts no new links. The workload objects of the API carry the same `disabled` beside `status` | You can turn the flag on without restarting, in **Settings & sources**. The gateway does not start if the YAML points to a user that does not exist or moves a declared workload to another team. ## How to use it | What | API (`/api/v1/admin`) | Console | | --- | --- | --- | | List workloads, with their responsible user and owned key count | `GET /api/v1/admin/workloads` | **Workloads** | | Read one workload with its recent keys and the YAML keys that reference it | `GET /api/v1/admin/workloads/{id}` | Workload detail | | Create or edit a workload | `POST /api/v1/admin/workloads`, `PUT /api/v1/admin/workloads/{id}` with `version` | **Workloads** → Create / Edit | | Delete a workload | `DELETE /api/v1/admin/workloads/{id}` (no active keys) | Delete | | Revoke all of the workload's keys | `POST /api/v1/admin/workloads/{id}/revoke-keys` | Revoke keys | | Owner of a new key | `owner` in `POST /keys` | key creation → Owner | | Change the owner | `PUT /keys/{id}/owner` with `owner_version` | Owner action | | Investigate usage | `GET /logs?owner=user:` or `workload:` (also as CSV); `GET /users/{id}/detail` | Request logs → Owner filter and column; user detail | Workloads from the YAML show up in the console read-only; to change them, edit the YAML. ## Rules - The workload must belong to the key's team and be active at the time it is linked. An owning user must be active and, if they have a team role, be a member of the key's team. - Only the global admin assigns owners and manages workloads; the global viewer can read. `team_admin` issues keys without an owner. - A **deactivated workload** keeps its keys working and accepts no new links. To cut off access, use **Revoke keys**. - A **deactivated owning user** (from the console or through [SCIM](/docs/features/scim/)): their keys are refused for as long as it lasts. Reactivating the user does not undo a key revocation. - The owner is recorded in every usage event and in the durable receipt. Changing the owner later does not rewrite the past. ## Limits - The analytics query API groups by owner (`GET /api/v1/admin/analytics/query?group_by=owner`, also used by m7 ai) and by `owner_kind` (`user`, `workload`, or empty for no owner), and filters by both (`owner=workload:batch-jobs`, `owner_kind=user`). - **Usage → Consumers → Usage by owner** (T168) shows that breakdown on the Analytics screen: group by owner, owner and model, or owner and team; narrow to people, workloads or requests with no owner; filter one exact owner (`user:usr_…` or `workload:…`, or **Filter** on a row); **Logs** opens the request logs of that owner for the same window. It follows the screen's window and filters (team, model, provider, key, principal, operation, end user; tag filters do not apply to it, and the panel says so) and shows the top 50 groups by requests. It reads the analytics query API, so the same rules apply: `analytics:read`, `usage_analytics` and `identity_ownership` (the panel is hidden without it), team-scoped roles and organization admins see only their teams, and with plan entitlements only teams whose plan includes `identity_ownership`. Saved views do not offer an owner grouping. - Video jobs use the owner of the request that queries the job, unless `video_job_owner` is on (off by default; requires `identity_ownership` and `quota_video`): then a job keeps the owner its key had when the job was created, shows it as `owner_kind`/`owner_id` (console: **Owner at creation**; hidden again when either flag is off), and its status reads and refreshes are attributed to it even if the key's owner changes before the job ends. Jobs created without the flag keep the polling key's current owner. Migration 171 adds the two nullable columns. - Turning the flag off stops recording owners and hides the screens, without deleting the links. ## See also - [Access control](/docs/features/access-control/). - [Key rotation](/docs/features/key-rotation/). ## Owner schema and attribution An absent owner remains absent. When an owner object is supplied, its kind must be `user` or `workload` and its ID must satisfy the corresponding typed shape. Shared [parameter definitions](/docs/reference/parameter-registry/) publish only those compiled choices, with no invented owner default. Shape validation does not establish existence, team membership, active state or permission: existing authoritative transactional checks still decide those. Clearing an owner in the console represents outer absence, not another kind or an access grant. # JWT for inference **Last updated:** 2026-11-22T07:30:00-03:00 (UTC-3) Instead of distributing virtual keys, your applications can call the gateway with a **JWT access token** issued by your identity provider. The gateway checks the signature and binds the token's `sub` to an existing virtual key, which defines models, scopes and team. Flag: `jwt_inference`. The gateway does not issue tokens and does not turn claims (`roles`, `scope`, `groups`, `team`) into permissions: everything comes from the bound key. ## How to turn it on ```yaml features: identity_management: true jwt_inference: true # boot; requires PostgreSQL jwt_auth: issuer_url: https://identity.example.com audience: ai-gateway-inference jwks_url: https://identity.example.com/keys algorithms: [RS256, ES256] allowed_origins: [https://identity.example.com] allowed_private_cidrs: [] allow_loopback_http: false max_ttl_seconds: 900 clock_skew_seconds: 30 bindings: [] ``` | Field | Rule | | --- | --- | | `issuer_url` | The trusted issuer, compared exactly with the token's `iss`; HTTPS | | `audience` | Exact. Must be different from the client ID of the [console SSO](/docs/features/oidc/) | | `jwks_url` | A fixed URL, with no query or fragment. The gateway never discovers keys from the token | | `algorithms` | The signature algorithms the gateway accepts: `RS256` and/or `ES256`; any other `alg` is refused | | `allowed_origins` | Exact origins, no wildcards | | `allowed_private_cidrs` | Allowed private networks (RFC 1918 or ULA), listed explicitly | | `allow_loopback_http` | HTTP only for localhost, in development | | `max_ttl_seconds` | 60 to 3,600; `exp - iat` cannot exceed this | | `clock_skew_seconds` | 0 to 60 seconds of tolerance for the identity provider's clock when the gateway checks `exp`, `nbf` and `iat` | | `bindings` | `subject` → `key_id` bindings to an existing managed key | Changing the issuer, audience, JWKS, algorithms, limits or network is a trust change: it requires a rollout and a review of the bindings. The issuer must produce this format on purpose: a generic JWT or an IdP's default configuration is not automatically compatible. ## Bind subjects to keys **In the console:** **Virtual keys → Inference JWT bindings**, for the global admin only (`jwt:manage`). It shows the issuer, audience, trust fingerprint and up to 1,000 subjects. **Through the API:** | Endpoint | Body | | --- | --- | | `GET /api/v1/admin/jwt-bindings` | — | | `PUT /api/v1/admin/jwt-bindings` | `{subject, key_id, disabled, version, trust_fingerprint}` | | `DELETE /api/v1/admin/jwt-bindings` | `{subject, version, trust_fingerprint}`; reverts to the YAML or removes the binding | - What is edited in the console takes precedence over the YAML. `disabled: true` denies the subject even if the YAML has a binding. - A stale version, changed trust or exceeded capacity return `409`; a key that does not exist returns `404`. - `key_id` is the real ID of a managed key, as it appears in **Virtual keys**. YAML keys cannot be bound. - Every change goes into the audit log; tokens are never stored. ## How to use it ```bash curl http://localhost:8080/v1/models \ -H "Authorization: Bearer $ACCESS_TOKEN" ``` On every request, the gateway resolves the binding and checks the key (expiry, revocation, active team) in the database. It then applies the same models, scopes and team policy as an ordinary key. Disabling the binding, revoking the key or changing the policy takes effect on the next request. ## What is validated - **Format:** compact JWS of up to 16 KiB; a header with only `alg`, `kid` and `typ`; `typ` equal to `at+jwt` or `application/at+jwt`. ID tokens (`typ: JWT`) are refused. - **Refused:** `none`, HMAC, JWE, embedded keys, key URLs (`jku`, `x5u`) and JSON with duplicate keys. - **Claims:** exact `iss`; `aud` equal to the audience (or a list containing only it); `sub` required; `exp`, `iat` and `nbf` required. - **JWKS:** up to 32 keys and 256 KiB, unique `kid`, `use: sig`. RSA from 2,048 to 8,192 bits or EC P-256. Private and symmetric keys are refused. | Situation | Response | | --- | --- | | Invalid token, signature or subject; expired or revoked key | `401` | | JWKS, trust or database unavailable; more than 32 concurrent verifications | `503` | Errors do not expose the token, the claims or the JWKS. ### Key cache - The JWKS is cached for 5 minutes. After that, if the refresh fails, no old key authorizes anything. - At most one refresh every 30 seconds. An unknown `kid` within that interval is refused: when you rotate the signing key, publish it with a new `kid`. - The JWKS fetch connects only to approved IPs, with no proxy or redirect, and a 5 s timeout. ## Separation from the console Console SSO and inference JWT have independent issuers, audiences, JWKS and caches. A console session does not become an inference token, and an access token does not open the console. `route:*` covers only inference routes: it grants no access to MCP or administration. The token is never sent to the provider. ## Limits - A token can be replayed while it is valid: there is no replay protection by `jti`, no proof of possession (DPoP) and no revocation of an individual token. To cut off access, disable the binding or revoke the key. - Removing a signing key from the JWKS can take up to 5 minutes to take effect; revocation in the database is immediate. - It is not an OAuth authorization server: no issuance, no introspection and no full RFC 9068 conformance. - Turning the flag off stops JWT authentication; ordinary keys keep working and the bindings are kept. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `GET /api/v1/admin/jwt-bindings` | Lists the subject-to-key bindings (`bindings`) with the trust fingerprint writes must name | | `PUT /api/v1/admin/jwt-bindings` | Binds one subject to an existing managed key, or changes that binding | ## See also - [Access control](/docs/features/access-control/). - [Console SSO](/docs/features/oidc/). - References: [RFC 8725](https://www.rfc-editor.org/rfc/rfc8725.html), [RFC 9068](https://www.rfc-editor.org/rfc/rfc9068.html), [RFC 7519](https://www.rfc-editor.org/rfc/rfc7519.html), [RFC 7517](https://www.rfc-editor.org/rfc/rfc7517.html). ## Boot policy constraints `max_ttl_seconds` is required when a JWT trust block is present and accepts 60–3,600 seconds; zero is invalid. `clock_skew_seconds` accepts 0–60 seconds, with omitted or explicit zero allowing no clock skew. These constraints share the typed backend policy and still validate a present block when inference JWT is disabled. They are not new public scalar catalog entries or console trust controls. Binding management retains its own authorization and versioning; changing boot trust requires rollout. # Usage tags **Last updated:** 2026-11-21T08:59:43-03:00 (UTC-3) Tag each request with an environment, application, or cost center, and then filter and group usage and cost by those tags. The client sends the tags in a header; you define the accepted values, and each team can have default tags. Flag: `usage_tags`. Tags are for attribution and reporting. They do not change authorization, price, or limits, and they do not prove origin: they are declared by the key. (To reserve targets by tag, see [tag-based routing](/docs/features/routing-strategies/#by-tags).) ## How to turn it on ```yaml features: usage_analytics: true usage_tags: true # requires usage_analytics and a database usage_tag_defaults: true # optional: default tags per team usage_tag_scoped_defaults: true # optional: also per model alias and per key; requires usage_tag_defaults usage_tag_management: true # optional: edit in the console; requires ui and PostgreSQL usage_tags: allowed_values: environment: [production, staging] application: [support, batch] defaults_by_team: team_example_id: # the team ID, not its name environment: production application: support defaults_by_model: # with usage_tag_scoped_defaults embeddings-default: # the alias ID application: batch defaults_by_key: # with usage_tag_scoped_defaults key_example_id: # the key ID (YAML or managed) environment: staging ``` | Key | What it does | | --- | --- | | `usage_tags.allowed_values` | The taxonomy: each tag name with its closed list of allowed values; any other name or value is refused | | `usage_tags.defaults_by_team` | Map of a team ID to the tags its keys' requests get when the client does not send them (`usage_tag_defaults`) | | `usage_tags.defaults_by_model` | The same, per canonical model alias (`usage_tag_scoped_defaults`) | | `usage_tags.defaults_by_key` | The same, per key ID (`usage_tag_scoped_defaults`); precedence, lowest first: team, model, key, then the client header | | Rule | Limit | | --- | --- | | Tag names | up to 16 | | Values per name | 1 to 32, unique | | Name and value format | `[A-Za-z0-9][A-Za-z0-9_.-]{0,63}`, case-sensitive | | Teams with defaults | up to 128, each with 1 to 8 pairs | | Model aliases with defaults | up to 128, each with 1 to 8 pairs | | Keys with defaults | up to 256, each with 1 to 8 pairs | | Alias and key IDs | `[A-Za-z0-9][A-Za-z0-9_.:/@-]{0,127}` | | Whole policy | 16 KiB | The closed list of values is deliberate: it keeps free text (and personal data or secrets) from becoming a tag by mistake. ## How to use it ```bash curl http://localhost:8080/v1/embeddings \ -H "Authorization: Bearer $GATEWAY_API_KEY" \ -H 'Content-Type: application/json' \ -H 'X-Gateway-Tags: {"environment":"production","application":"batch"}' \ -d '{"model": "embeddings-default", "input": "test text"}' ``` - A single `X-Gateway-Tags`, up to 2 KiB and eight pairs, as a flat JSON object of strings. - The name and value must be on the allowed list. Outside it, `400`; with the flag off, `404`. - **Team defaults:** with `usage_tag_defaults`, the gateway applies the default tags of the key's team. The client can swap a default value for another allowed one, but cannot remove it. The total is still limited to eight pairs. - **Model and key defaults:** with `usage_tag_scoped_defaults` as well, the defaults of the alias that serves the request (for an [automatic router](/docs/features/auto-routing/), the alias it chose) and of the authenticated key are layered on top, before any [conditional routing](/docs/features/conditional-routing/) reads the tags. Each layer replaces a name an earlier one set, lowest first: **team, model alias, key**, then the header. In the example above a request with `key_example_id` to `embeddings-default` records `environment: staging` (key) and `application: batch` (alias) unless the header names them. An alias or key ID that does not exist (yet) stays latent and is not an error, so deleting a key or alias never invalidates the policy. - With the flag off, `defaults_by_model` and `defaults_by_key` from YAML stay validated but unused, and the API refuses to save them (`403 feature_disabled`). The batch check of [required attribution](/docs/features/budgets-and-tpm/#require-the-end-user-and-tags) counts team and key defaults only, because a batch is checked before its lines name their models; each line is admitted again with its own alias. - The team, key and alias always come from authentication and admission, never from the header or the body. This applies to Chat, the other inference routes, and native Gemini. It does not apply to MCP, `/v1/models`, or administrative routes. The header is not sent to the provider, and tags do not go into structured logs, spans, or Prometheus metrics. ## Filtering and grouping Analytics, Request logs, the CSVs, valuation, and receipts accept `tags`: a JSON object with up to four pairs, combined with AND. ```bash curl -b "$COOKIE_FILE" --get \ --data-urlencode 'tags={"environment":"production"}' \ --data-urlencode 'tag_dimension=application' \ http://localhost:8080/api/v1/admin/analytics ``` - `tag_dimension` groups by one tag in analytics, CSV, and valuation: up to 20 values, with one group for events without the tag. - The filter accepts values that have since left the allowed list, so you can investigate the past. - Team roles still see only their own events. In the console, Analytics, Request logs, and Durability have the tag filter; the drill-down from Analytics to Request logs preserves the filters. ## Editing the policy With `usage_tag_management`, **Usage tags** in the console edits the list and the per-team defaults in a JSON editor, for the global admin only. The API is `/api/v1/admin/usage-tags`: | Method | What it does | | --- | --- | | `GET` | `{version, source, effective, base_fingerprint}` | | `PUT` | Replaces the whole policy: `{version, expected_base_fingerprint, policy}` | | `DELETE` | Reverts to the YAML | Writes require a session, same origin, and CSRF, and they go into the audit log (without the policy values). Viewer, operator, and team roles do not see the global policy. ## How tags are stored - Each request records its tags once, in the usage event and in the durable receipt. Changing the list or the defaults later does not alter the past. - Requests served by the same [cache](/docs/features/exact-cache/) each keep their own tags. - Without `durable_usage`, recording is best effort and can be missing if the database fails. - Turning `usage_tags` off preserves the history, but hides the tags and makes the filters respond `404` instead of ignoring them. Turning it back on shows everything again. ## Limits - Defaults per key and per alias need `usage_tag_scoped_defaults`. - No free text and no tags read from the body (`metadata`, `tags`). - Budgets and TPM are not enforced per tag. To budget an application, harness or repository, use [attribution groups](/docs/features/attribution-groups/), which the server decides from the authenticated key and model. ## Which layer set a tag With `usage_tag_provenance` (off by default; requires `usage_tags`), each new usage event also records, per tag, the layer whose value won: `team`, `model` or `key` (a default) or `header` (`X-Gateway-Tags`). The [request journey](/docs/features/observability/#request-journey) shows it as **Tag sources** (`app=team, env=header`) and in `event.tag_sources`, only while `usage_tags` and the flag are on. Earlier records, and records written with the flag off, have no sources; the policy of that time is in the audit log. Migration 170 adds the nullable column; nothing is written until the flag is on. The sources also travel with the event to configured [log destinations](/docs/features/observability/), as layer names only. ```yaml features: usage_tags: true usage_tag_defaults: true usage_tag_provenance: true ``` ## See also - [Required attribution](/docs/features/budgets-and-tpm/#require-the-end-user-and-tags): a team or key that refuses requests without given tag names (`attribution_requirements`). - [Analytics experience](/docs/features/analytics-experience/). - [Valuation](/docs/features/usage-valuation/). ## Typed policy constraints Tag allowlists and defaults remain typed, bounded domain maps. Names and values use the existing ASCII slug grammar; team defaults refer to authenticated team identity and explicitly allowed values. Shared [parameter definitions](/docs/reference/parameter-registry/) cannot expose configured tag names/team IDs in a safe scalar catalog or grant permission. Existing parser, merged-map bounds, versioned management and team-scoped analytics remain authoritative. # Attribution groups **Last updated:** 2026-11-22T07:30:00-03:00 (UTC-3) An attribution group is a financial grouping of one team's traffic: an **application**, a **harness** (a coding agent or batch runner), a **repository** or any **custom** grouping. Rules attribute each request to at most one group of its team, from facts the gateway owns: the authenticated team, the authenticated key and the canonical model alias. Budgets and TPM can then target a group, and a report shows spend per group with its coverage. Flag: `attribution_groups` (default `false`). Groups are not [usage tags](/docs/features/usage-tags/). A tag is a label the client declares; a group is decided by the server and cannot be chosen or avoided by a header, the body, the end user or a session ID. That is why a group can carry a hard budget and a tag cannot. Both can be used together: the report groups by attribution, the analytics pages still filter by tag. Groups are financial ownership only. They do not change routing, authorization, tenancy or plan rights, and a team role sees nothing new. ## Enable it ```yaml features: usage_analytics: true # required attribution_groups: true attribution_groups: groups: - id: support-bot # unique; ^[a-z][a-z0-9_-]{1,63}$ kind: application # application, harness, repository or custom team_id: acme # the owning team (its ID, not its name) name: Support assistant # optional, up to 120 printable bytes - id: ci-monorepo kind: repository team_id: acme - id: acme-other kind: custom team_id: acme rules: - id: support-keys # unique; same grammar as group ids group: support-bot precedence: 10 # 1-100000, unique within the team; lowest wins key_ids: [key_support_prod, key_support_eval] - id: ci-cheap-model group: ci-monorepo precedence: 20 key_ids: [key_ci] models: [fast-chat] # canonical model aliases teams: - team_id: acme unmatched: default_group # unattributed, default_group or deny default_group: acme-other ``` The flag is an operator control, changes at runtime and applies on the next request. It needs PostgreSQL: migration 147 creates the rule set history, adds the captured attribution to usage events and durable receipts, and widens a reservation's charge bound to 140 so a group subject fits next to every other one. The new columns have no default and their shape checks are `NOT VALID` (existing rows hold no attribution), so the migration neither rewrites nor scans the usage tables; new rows are checked. Without storage the inference request answers `503 attribution_unavailable` and the API answers `503`. ### Fields and bounds | Field | Default | Bounds and meaning | | --- | --- | --- | | `groups[]` | none | Up to 256. `id`, `kind` and `team_id` are required. | | `groups[].name` | empty | Optional display name of the group in reports and the console, up to 120 printable bytes | | `groups[].kind` | required | `application`, `harness`, `repository`, `custom`. Informational: every kind behaves the same. | | `rules[]` | none | Up to 512. Each names an existing `group` and needs `key_ids`, `models` or both. | | `rules[].precedence` | required | 1-100000, unique per team. The lowest matching precedence wins; there are no ties. | | `rules[].key_ids` | any key | Up to 64 key IDs (YAML or managed). A rule naming a removed key simply never matches. | | `rules[].models` | any model | Up to 32 canonical model aliases, matched exactly. | | `teams[].team_id` | required | The team these settings apply to, by its ID; one entry per team. | | `teams[].default_group` | none | The group of that team an unmatched request is attributed to; required with `unmatched: default_group`. | | `teams[].unmatched` | `unattributed` | What a request of that team that matches no rule gets: `unattributed` (recorded as unmatched), `default_group` (attributed to `default_group`, a group of the same team) or `deny`. | | whole policy | | 256 KiB of canonical JSON. | A rule only ever sees requests of its group's team. A rule of team `acme` that names a key of team `beta` never matches, so one team cannot charge another team's group or move its own traffic there. ## How a request is attributed Once per inference request, after authentication, team and model admission and before the durable receipt, the quota reservation or any provider call: 1. The gateway reads the effective rule set version (one indexed read; the parsed body is cached by version). 2. It takes the matching rule with the lowest precedence among the rules of the request's team. A rule matches when the key is in `key_ids` (if set) and the canonical model is in `models` (if set). 3. Without a match it applies the team's `unmatched` setting. With `deny` the request is refused with `422 attribution_group_required` and the provider is not called; its own usage event records it as `unmatched` under that version. 4. The result is captured once: the group (empty when unmatched), the rule (empty for a team default), the source (`rule`, `team_default` or `unmatched`) and the rule set version. The durable receipt, the quota reservation and the usage event carry the same values; the final event cannot move a receipt to another group. Chat and the other inference routes, native Messages and Gemini, passthrough, video and each Realtime response are attributed. Administrative routes, MCP and `/v1/models` are not. A call the gateway makes while serving a client request of the same team (a moderation guardrail, an auto-routing helper, embeddings for a vector search) inherits that request's attribution; it never resolves rules for its own model. A moderation guardrail call without such a parent records no attribution rather than being refused. Every other internal call (batch lines, evaluations) is attributed like a direct request of its key and model, so a group budget or `deny` cannot be avoided through `/v1/batches`. Auto-routing helpers (the embedding or classifier call that chooses the target) run before the request is attributed and are resolved like requests of the same key: a team with `deny` and model-only rules must also cover those helper models, or use key rules. ## Budgets and TPM per group A quota policy with `subject: group` and the group ID as `subject_id` limits that group's traffic, with everything a policy offers: TPM, TPD, USD per day, month, week, quarter, year or lifetime, `soft_budget`, alert thresholds and temporary increases. ```yaml quotas: policies: - id: support-monthly subject: group subject_id: support-bot budget_usd: "250" budget_period: month alert_thresholds: [80, 100] ``` - The group ceiling is cumulative over every key and model that the rules attribute to the group, reserved in the same PostgreSQL transaction as every other applicable policy: concurrent requests never pass it together. - An unknown outcome (timeout, crash, missing usage) keeps its hold until [reconciliation](/docs/features/quota-finance/) substantiates it; it never becomes zero. - A group policy needs `attribution_groups`. In YAML it must name a group of the YAML rules. In the console it must name a group of the effective rule set (`422 unknown_quota_subject` otherwise, checked in the same transaction as the write), and a rule set version cannot drop a group that an enabled policy targets (`409 group_in_use`). - **Flag off with a group budget.** If `attribution_groups` is turned off while an enabled group policy exists, requests of the team that owns that group are refused with `503 quota_unavailable` instead of running without the group ceiling. Other teams are unaffected. Disable or remove the group policies first. - **Orphaned budgets.** A group policy that came from a YAML quota base for a group the effective (console) rule set does not define matches no request. `GET /api/v1/admin/attribution-groups` lists such policies in `orphaned_group_policies` (with `orphaned_group_policies_unknown: true` when the quota catalog could not be read), and the console warns about them. - Status: group items appear from `GET /api/v1/admin/quota-policies/status?status_version=5`; earlier status versions leave them out. ## Rule versions Every effective rule set is an immutable, numbered version; the database refuses to update or delete one. - **YAML base.** The YAML block is adopted as version 1 the first time it is needed. When the effective version came from YAML and a restarted process has a different YAML, that process adopts it once, as the next version. A body that some version already held is never adopted again, so replicas still running the earlier YAML during a rolling change do not alternate versions; to return to an earlier body, use revert. A YAML base that would drop a group an enabled quota policy targets is not adopted: the current version stays, the gateway logs `attribution_base_not_adopted` and the API reports `base_differs: true`. - **Console.** Publishing creates the next version (`source: console`). A later YAML change never replaces it; the API reports `base_differs: true` until an administrator reverts. - **Revert** publishes the YAML body again as a new version (`source: yaml`). Nothing is deleted. - Recorded requests keep the version they were attributed under, so a rule change never reinterprets history. ## API All responses are `private, no-store`. Reads need a global role with `quotas:read`; writes need a live global administrator, `quotas:manage`, same origin and CSRF, and are audited (`attribution_groups.publish`, `attribution_groups.revert`). Team roles are refused. | Method and path | What it does | | --- | --- | | `GET /api/v1/admin/attribution-groups` | The effective version: `version`, `source`, `fingerprint`, `policy`, `created_at`, `base_fingerprint`, `base_differs`, `group_kinds`, `orphaned_group_policies` | | `PUT /api/v1/admin/attribution-groups` | `{version, policy}`: publish the next version under compare-and-set (`409 version_conflict` if another version was published) | | `DELETE /api/v1/admin/attribution-groups` | `{version}`: publish the YAML base again | | `GET /api/v1/admin/attribution-groups/versions?limit=50` | History, newest first (1-200) | | `GET /api/v1/admin/attribution-groups/versions?version=N` | One version with its body | | `GET /api/v1/admin/attribution-groups/report` | Spend per group with coverage; `from`, `to` (RFC 3339, at most 366 days, default the last 30), `team`, `format=csv` | ```bash curl -b "$COOKIE_FILE" -H "X-CSRF-Token: $CSRF" -X PUT \ -H 'Content-Type: application/json' \ -d '{"version":1,"policy":{"groups":[{"id":"support-bot","kind":"application","team_id":"acme"}],"rules":[{"id":"support-keys","group":"support-bot","precedence":10,"key_ids":["key_support_prod"]}],"teams":[{"team_id":"acme","unmatched":"deny"}]}}' \ http://localhost:8080/api/v1/admin/attribution-groups ``` ### Report and coverage ```json { "from": "2026-10-15T00:00:00Z", "to": "2026-11-14T00:00:00Z", "coverage": {"events": 1200, "by_rule": 1000, "team_default": 150, "unmatched": 20, "not_evaluated": 30, "versions": [1, 2]}, "groups": [ {"team": "acme", "group": "support-bot", "source": "rule", "requests": 1000, "input_tokens": 900000, "output_tokens": 90000, "estimated_usd": "1.26", "valued_known": 990, "valued_partial": 0, "valued_unknown": 6, "not_valued": 4, "tokens_unknown": 3, "rule_versions": 2} ], "truncated": false } ``` - `coverage` counts every selected event: attributed by a rule, by a team default, unmatched, or **not evaluated** (recorded before the feature, with the flag off, or on a route that is not attributed). A group total is only as complete as its coverage. - `team` filters before aggregation. - Token sums leave out requests without a reported count; `tokens_unknown` says how many. - `estimated_usd` sums only known [valuations](/docs/features/usage-valuation/), priced from the price book with discounts and margins frozen in each event. It is an estimate, not a provider charge; with `budget_charge_reports` each group also carries `budget_charge`, what its budgets took at the approved rates ([budget charge beside the estimate](/docs/features/usage-valuation/#budget-charge-beside-the-estimate)); partial, unknown and not valued requests are counted, never treated as zero. Provider charges are compared in [financial reconciliation](/docs/features/quota-finance/). - Up to 500 rows (largest first); `truncated` says more exist. The CSV has the same columns plus a final `#coverage` line, with spreadsheet formulas neutralized. ## Console **Access control → Attribution groups** shows the coverage, the spend table (with a CSV download), the rules in force (precedence, group, `key_ids`, `models`) and the team defaults (`unmatched`, `default_group`) as tables beside the rule set JSON editor, with its version and base state, and the version history. Global viewers read; only a global administrator publishes or reverts. Group budgets are edited in **Budget & TPM** like any policy, with subject **group**. ## Limits and upgrade notes - Matching uses the authenticated team, key and canonical model only. There is no matching by user, project, end user, tag or header. - Rule sets and captured attribution live in PostgreSQL; group budgets are qualified with the PostgreSQL quota store only. - **Upgrade.** Migrate every replica (migration 147), upgrade them all, then turn the flag on, and only then add group policies. An older replica does not know `subject: group`: it neither attributes requests nor enforces group ceilings. To roll back, remove group policies, turn the flag off, then downgrade. # Customer portal **Last updated:** 2026-11-26T23:07:44-03:00 (UTC-3) The customer portal is for an operator that sells AI usage to its own customers. The operator registers **customer organizations**, their **customer teams** and **members** under one of its gateway teams, gives them budgets, and its backend calls the gateway with one of that team's keys plus headers that name the customer. The gateway charges the organization, the customer team and the member in the same quota reservation as every other budget, refuses a request that would pass any of their hard ceilings before the provider is called, raises a `customer_budget_crossed` alert and reports usage per customer. Flag: `customer_portal` (default `false`). Customers are not console users, gateway teams or end users: they never sign in, own no keys and get no access to anything. They are financial subjects that the operator's backend names on each request. ## Enable it ```yaml features: budget_limits: true # required (a restart flag) durable_usage: true # required by budget_limits usage_analytics: true # required customer_portal: true customer_portal_credentials: true # optional: scoped backend credentials customer_self_service: true # optional: read-only customer view links customer_budget_windows: true # optional: several budgets per level (a day and a month) customer_portal: trusted_keys: - key_id: backend-prod # a YAML or managed key ID require_identity: true # optional; default false require_override_approval: false # optional; see override approval requests override_request_ttl_hours: 168 # optional auto_register_members: false # optional; see auto-registration view_token_max_minutes: 1440 # optional; see the self-service view auto_register_organizations: false # optional; see auto-registration max_auto_organizations: 100 # optional; per operator team auto_organization_profile: # required with auto_register_organizations id: default budget_usd: "5" # each member's ceiling budget_period: month organization_budget_usd: "200" # the organization's own ceiling organization_budget_period: month ``` The flag is an operator control, changes at runtime and applies on the next request. It needs PostgreSQL for both the store and the quota ledger: migration 160 creates the customer tables and adds the captured customer to usage events and durable receipts. Without PostgreSQL an inference request that would resolve a customer answers `503 customer_unavailable` and the API answers `503`. Customer traffic is budgeted traffic: every request that names a customer reserves USD, so its model needs an approved quota rate ([budgets and TPM](/docs/features/budgets-and-tpm/#how-to-turn-it-on)), exactly as for a team budget. A request without one is refused with `422 quota_profile_unsupported`. ## Trusted keys Only a **trusted key** may name a customer, and only a customer of the key's own team. A key is trusted when it is listed in `customer_portal.trusted_keys` (read-only in the console) or when an administrator trusts it through the API or the console. The team is always the key's own: it is never taken from the request or from the administrator's input, and a stored trust entry never moves to another team. | Field | Default | Meaning | | --- | --- | --- | | `customer_portal.trusted_keys[]` | none | Up to 256 entries, unique `key_id`. | | `customer_portal.trusted_keys[].key_id` | required | A YAML or managed key ID, 1-128 characters. | | `customer_portal.trusted_keys[].require_identity` | `false` | Refuse that key's inference requests that name no customer organization (`422 customer_identity_required`). | Revoking trust takes effect on the next request: a request of that key that names a customer is refused. Trust is checked live in PostgreSQL on every request when the key is not trusted in the YAML. ## What a request sends | Header | Required | Meaning | | --- | --- | --- | | `X-Gateway-Customer-Org` | yes, to name a customer | The organization ID. | | `X-Gateway-Customer-Team` | no | A customer team of that organization. | | `X-Gateway-Customer-Member` | no | A member of that organization. A member registered in a customer team charges that team too; a different team header is refused. | ```bash curl https://gateway.example/v1/chat/completions \ -H "Authorization: Bearer $BACKEND_KEY" \ -H "X-Gateway-Customer-Org: acme-co" \ -H "X-Gateway-Customer-Member: alice@acme.example" \ -H "Content-Type: application/json" \ -d '{"model":"fast-chat","messages":[{"role":"user","content":"hi"}],"max_completion_tokens":256}' ``` The headers are resolved once per request, after authentication and before the durable receipt, the quota reservation or any provider call. Every refusal below happens before the provider is called: | Answer | When | | --- | --- | | `422 customer_portal_disabled` | A customer header is present while the flag is off. The headers are never silently ignored. | | `403 customer_identity_not_trusted` | The key is not trusted to assert customer identity. | | `422 customer_identity_required` | The key requires identity and the request names no organization. | | `422 customer_org_required` | A team or member header without an organization header. | | `422 customer_unknown` | The organization, team or member is not registered under the key's team (also when it is deleted while the request is admitted). | | `422 customer_team_mismatch` | The team header differs from the member's registered team. | | `403 customer_disabled` | A named level is disabled. | | `429 quota_exceeded` | A hard ceiling would be passed. `X-Gateway-Quota-Policy` is `customer:org`, `customer:team` or `customer:member`, and `X-Gateway-Quota-Dimension` is the period of the window that ran out. A level with [several budget windows](#several-budget-windows) names the window in the policy too: `customer:member:day`, `customer:org:month`. | | `422 customer_budget_windows_disabled` | A named level holds several budget windows and `customer_budget_windows` is off. The stored windows are never reduced to one. | Chat and the other inference routes, native Messages and Gemini, passthrough, video and each Realtime response are resolved. A call the gateway makes while serving a client request of the same team (a moderation guardrail) inherits that request's customer, and the embeddings of a vector store upload or search carry the client's customer headers, so they are resolved and charged like the client's own request. An auto-routing helper (the embedding or classifier call that picks the target) runs after the customer is checked but is not charged to it. **Batches.** `POST /v1/batches` from a trusted key may carry the customer headers, resolved exactly like a client request's: every line is charged to that customer and recorded with it (the batch stores `customer_org`, `customer_team`, `customer_member`). Each line is admitted on its own, so a line is refused (and reported in the error file) when the customer's ceiling is reached, when the customer is deleted or disabled, or when the key loses its trust while the batch runs. A key with `require_identity` must name a customer to create a batch (`422 customer_identity_required`). **Evaluations.** `POST /api/v1/admin/evals/runs` takes an optional `customer` (`{"org": "acme-co", "member": "alice"}`; `team` optional): the run's model calls and its evaluators' judge calls are charged to that registered, enabled customer of the dataset's team, reserved and settled on the same ledger; a call that would pass a ceiling is refused (a refused judge call is not retried, and the item keeps no score). Because customer traffic is budgeted, the run's model calls are sent with `max_completion_tokens: 4096`. The session needs `customers:manage` for that team (`403 team_forbidden`); an unknown customer is `422 customer_unknown`. ## Records Every record is keyed by IDs the operator chooses: 1-64 characters of `A-Z a-z 0-9 . _ @ : -`, starting with a letter or digit, so an email or a UUID fits. They live under the operator's gateway team, so two teams may use the same customer IDs without sharing anything. | Kind | Fields | | --- | --- | | Organization | `name`, budget, `profile_id` (the default profile of its new members), limits, `disabled` | | Customer team | `name`, budget, `profile_id` (the default profile of its new members, before the organization's), limits, `disabled` | | Member | `name`, `customer_team`, `profile_id`, budget, limits, override, `disabled` | | Budget profile | `name`, budget (required), limits | Limits are the [token ceilings and per-model allowances](#per-model-allowances-and-token-ceilings) of a level. The budget fields are shared: | Field | Default | Bounds and meaning | | --- | --- | --- | | `budget_usd` | none | Positive decimal string, up to six decimal places, up to 1,000,000. Omitted: no ceiling, but spend is still counted, so a budget set later starts from the real spend. | | `budget_period` | `month` | `day` or `month` (UTC); `week`, `quarter` and `year` need `calendar_budget_periods`; `lifetime` needs `lifetime_budget_limits`. | | `soft_budget` | `false` | `true` alerts without refusing. | | `alert_thresholds` | `[80, 100]` | Up to five unique percentages 1-100; `[]` disables alerts. | | `budgets[]` | none | Up to four budget windows with distinct periods; see [several budget windows](#several-budget-windows). More than one needs `customer_budget_windows`. | | `budgets[].budget_usd` | required | As `budget_usd`. | | `budgets[].budget_period` | `month` | As `budget_period`, unique within the level. | A member's ceiling is, in order: an unexpired **override**, its own budget, then its **profile**. A new member that names neither a profile nor a budget gets its customer team's default profile, else its organization's, once, at creation. A member follows its profile live: raising the profile raises every member that uses it. Up to 10,000 teams, members and profiles fit in one organization. An **override** replaces a member's ceiling (higher or lower) until `expires_at`, at most 366 days ahead. On a member with several budget windows it replaces the window its `budget_period` names, or the first (shortest) window when it names none; the other windows stay enforced. An override (or an override request) that names a period none of the member's windows has is refused with `422 invalid_customer`; when the window is removed afterwards, the override changes nothing. On a member without a budget the override is its one hard ceiling, counted in the period it names (default: the member's `budget_period`). Each reservation decides it after locking its counters, by the database clock, and the captured ceiling is the one its settlement and alerts use. An override never resets spend: when it expires, the member's own or profile ceiling applies to what was already spent in the window. ### Several budget windows A level may hold up to four budgets with distinct periods, for example 1 USD a day and 5 USD a month, so that a customer neither spends its month in one day nor passes its month. Flag: `customer_budget_windows` (default `false`, an operator control that needs `customer_portal` and applies on the next request). ```bash curl -X PUT "$API/organizations/acme/acme-co/members/alice@acme.example" -d '{ "budgets": [ {"budget_usd": "1", "budget_period": "day"}, {"budget_usd": "5", "budget_period": "month"} ]}' ... ``` - **All together.** Every window is reserved in the same transaction as the level's other budgets: the request fits all of them or none, concurrent requests on any number of replicas never pass any of them, and settlement moves all of them by the same measured amount. - **The refusal names the window.** `429 quota_exceeded` carries `X-Gateway-Quota-Policy: customer:member:day` (the level and the period) and `X-Gateway-Quota-Dimension: day`, and `Retry-After` is when that window resets. A level with one window keeps the policy ID `customer:member`. Budget alerts are deduplicated by policy ID, so a level that goes from one window to several (or back) may alert once more for a threshold it already crossed in the current window. - **One budget is one window.** `budget_usd` with `budget_period` is the same as a `budgets` list of one entry, with or without the flag, and existing records and clients are unchanged. A record is returned with both: `budgets` lists its windows, shortest period first, and `budget_usd` and `budget_period` are the first one. - **Writing.** Send one spelling: `budgets`, or `budget_usd` with `budget_period`. A client that reads a record and writes it back sends both, so the gateway settles them: - several `budgets` entries are the whole list, and a `budget_usd` beside them must be the shortest window's, exactly as a read returns it; - one `budgets` entry beside the same `budget_usd` and `budget_period` is one window; - one `budgets` entry beside a different `budget_usd`: the side that still equals the stored record is what the client read, and the other side is the change. So changing `budget_usd` of a record with one budget works as it always did, and so does reducing several windows to one by sending the one entry; - anything else (two budgets that are both new, also on a create, or a `budget_usd` that disagrees with several entries) is refused with `422 invalid_customer`: a ceiling is never dropped by guessing. - **Profiles.** A profile's windows apply to every member that follows it, live. - **Soft budgets and alerts.** `soft_budget` and `alert_thresholds` belong to the level and apply to each of its windows: each window alerts on its own thresholds, and the `customer_budget_crossed` event names the window in `budget_period`. - **Status.** `effective.windows[]` lists every effective window with its `budget_usd`, `budget_period`, `committed_usd`, `window_start` and `source` (`override`, `own` or `profile`). | Answer | When | | --- | --- | | `422 feature_disabled` | A write with more than one window while `customer_budget_windows` is off, or with a period whose flag is off. | | `422 invalid_customer` | More than four windows, two windows of one period, an amount that is not a positive decimal, or a `budget_usd` and `budgets` that name different budgets (see Writing). | | `422 customer_budget_windows_disabled` | A request that names a level with several stored windows while the flag is off. Turn the flag on again, or give those levels one budget, before turning it off. | ### API Every write needs `customers:manage` for the record's operator team and is audited (`customer..put`, `.delete`, `customer.member.override`, `customer.trusted_key.put`); a cookie session also sends its CSRF token from the same origin. Reads need `customers:read`. See [who manages customers](#who-manages-customers) for which sessions hold them. A create omits `version` and is refused with `409 customer_exists` when the record exists; a replace sends the current `version` and is refused with `409 version_conflict` when it changed. ```bash API=https://gateway.example/api/v1/admin/customer-portal # Organization with a monthly 100 USD ceiling and a default member profile. curl -X PUT "$API/organizations/acme/acme-co/profiles/starter" -d '{"budget_usd":"5","budget_period":"month"}' ... curl -X PUT "$API/organizations/acme/acme-co" -d '{"name":"Acme","budget_usd":"100","profile_id":"starter"}' ... # Customer team and member (the member gets the starter profile). curl -X PUT "$API/organizations/acme/acme-co/teams/eng" -d '{"name":"Engineering"}' ... curl -X PUT "$API/organizations/acme/acme-co/members/alice@acme.example" -d '{"customer_team":"eng"}' ... # Temporary override for one week, at the member's version. curl -X PUT "$API/organizations/acme/acme-co/members/alice@acme.example/override" \ -d '{"version":1,"budget_usd":"20","expires_at":"2026-11-22T00:00:00Z","reason":"launch week"}' ... # Trust a managed key; its team is the key's. curl -X PUT "$API/trusted-keys/key_backend" -d '{"require_identity":true}' ... ``` | Route | Purpose | | --- | --- | | `GET /customer-portal` | Trusted keys (YAML and stored), header names, default thresholds, periods | | `PUT`, `DELETE /customer-portal/trusted-keys/{key_id}` | Trust or revoke a key | | `GET /customer-portal/organizations?team=` | Organizations with their effective ceiling and committed spend | | `GET`, `PUT`, `DELETE /customer-portal/organizations/{team}/{org}` | One organization; delete removes its teams, members and profiles. The read takes `member_q`, `member_sort` and `member_order` ([search and sort](#member-search-and-sort)) | | `PUT`, `DELETE /customer-portal/organizations/{team}/{org}/{teams\|members\|profiles}/{id}` | Customer teams, members and profiles | | `PUT`, `DELETE /customer-portal/organizations/{team}/{org}/members/{id}/override` | Set or clear an override | | `GET`, `POST /customer-portal/credentials`, `POST /customer-portal/credentials/{id}/revoke` | Backend credentials (people only) | | `GET /customer-portal/override-requests`, `POST .../organizations/{team}/{org}/members/{id}/override-requests` | List and file override requests | | `POST /customer-portal/override-requests/{id}/approve`, `.../deny` | Decide a request (people only, never the requester) | | `GET /customer-portal/usage?team=&org=&from=&to=&by=&format=` | Usage per customer and date range | | `GET /customer-portal/organizations/{team}/{org}/export`, `POST /customer-portal/organizations/{team}/import` | Export and import an organization | | `POST /customer-portal/organizations/{team}/{org}/view-tokens`, `POST /customer-portal/view-tokens/{team}/{id}/revoke` | Mint and revoke a self-service view link | A customer team with members, or a profile that a member, team or the organization still names, cannot be deleted (`409 customer_in_use`). Deleting a record keeps its counters and its usage events; deleting a member or an organization also deletes its view links and override requests. ## Import and export `GET /customer-portal/organizations/{team}/{org}/export` returns one organization as a portable `customer-portal/v1` document: the organization, its profiles, customer teams and members with their budgets, limits and allowances, without versions, timestamps, spend or overrides. `POST /customer-portal/organizations/{team}/import?mode=merge|create` writes such a document into that operator team (the document's own `team` is ignored), so an export of one team or gateway imports into another unchanged. ```bash curl "$API/organizations/acme/acme-co/export" ... > acme-co.json curl -X POST "$API/organizations/acme-staging/import?mode=create" --data-binary @acme-co.json ... # {"team":"acme-staging","org":"acme-co","mode":"create","created":42,"replaced":0} ``` | Field | Default | Meaning | | --- | --- | --- | | `mode` | `merge` | `merge` creates missing records and replaces existing ones at their current version; `create` refuses the import (`409 customer_exists`) when any record exists. | A level's budget windows travel in `budgets`, so an export of an organization with several windows imports with all of them. The import is one transaction, written in order (organization, profiles, customer teams, members) and validated as a whole first: any invalid record, missing reference, period, limit or number of budget windows whose flag is off, or more than 10,000 records refuses it and writes nothing. The body is at most 8 MiB. Overrides are never imported: they follow their own [approval flow](#override-approval-requests). Import needs `customers:manage` for the team (a team administrator only into its own teams), export `customers:read`; an import is audited as `customer.import.` with its record count. ## Auto-registration Both kinds are off by default, apply only to requests of a trusted key and only inside that key's own team. ### Members With `customer_portal.auto_register_members: true` (default `false`), a trusted key's request that names an unknown member of a registered, enabled organization registers that member before it is admitted: in the named customer team when the request names one, with the default profile of that customer team, else of the organization. Without a default profile, or with a disabled organization or team, the member stays unknown (`422 customer_unknown`). Concurrent first requests of one member register it once; each registration is audited as `customer.member.auto_register` by `system:customer-auto-register`, and counts toward the organization's 10,000 records. ### Organizations With `customer_portal.auto_register_organizations: true` (default `false`), a trusted key's request that names an unknown organization registers that organization before it is admitted, with a default member profile, so an operator whose backend already knows its tenants does not have to register each one first. The organization is always created in the key's own team; only a trusted key can do it, and a request from any other key is refused as before. | Field | Default | Bounds and meaning | | --- | --- | --- | | `customer_portal.auto_register_organizations` | `false` | Register an unknown organization named by a trusted key. | | `customer_portal.max_auto_organizations` | `100` | 1-10000. The most auto-registered organizations one operator team may hold. Organizations registered through the API, the console or an import do not count. | | `customer_portal.auto_organization_profile.id` | `default` | The ID of the default member profile created in each such organization (a customer ID). | | `customer_portal.auto_organization_profile.budget_usd` | required | The profile's ceiling: a positive decimal, up to six places. There is no default, because a ceiling is your decision; the gateway refuses to start with auto-registration on and no amount. | | `customer_portal.auto_organization_profile.budget_period` | `month` | As `budget_period`; calendar and lifetime periods need their flags. | | `customer_portal.auto_organization_profile.organization_budget_usd` | required | The organization's own hard ceiling, over all of its members together: a positive decimal, up to six places. Required whether or not members auto-register: the gateway refuses to start, and refuses a configuration change, with auto-registration on and no organization ceiling, so a request never creates an organization that can spend without limit. | | `customer_portal.auto_organization_profile.organization_budget_period` | `month` | As `budget_period`. | The settings are read at startup, like the rest of `customer_portal`. What a registration does: 1. The organization is registered with `organization_budget_usd` as its own hard ceiling and marked `auto_registered: true`. 2. The default profile is created in it and set as the organization's default profile, so its new members get that ceiling. Change the organization's budget or the profile through the API or the console afterwards. 3. The registration is audited as `customer.org.auto_register` by `system:customer-auto-register`. A request registers an organization only when it would then be admitted: it names no customer team (a new organization has none), and it names a member only when `auto_register_members` is on too (the member is then registered with the default profile in the same request). Otherwise the answer is `422 customer_unknown` and nothing is registered. Past `max_auto_organizations` the organization stays unknown (`422 customer_unknown`, logged as `customer_auto_register_capped`): raise the cap, or delete organizations you no longer serve. A registration that could not be written (storage trouble, or a timeout behind many first requests of one team) also answers `422 customer_unknown` and is logged as `customer_auto_register_failed`; the next request tries again. Concurrent first requests of one organization register it once, and the cap holds under any load. ## Erasing a member A member is erased through the [end-user deletion](/docs/features/data-governance/) API, by naming `customer_org` and `customer_member` instead of `end_user` (needs `end_user_deletion` and `customer_portal`; a live global administrator with `retention:manage`, refused while a legal hold is active): ```bash curl -X POST https://gateway.example/api/v1/admin/end-user-deletions \ -d '{"team":"acme","customer_org":"acme-co","customer_member":"alice@acme.example","dry_run":true}' ... curl -X POST https://gateway.example/api/v1/admin/end-user-deletions \ -d '{"team":"acme","customer_org":"acme-co","customer_member":"alice@acme.example","confirm":true}' ... ``` The request deletes the member record, its override requests and its view links at once and removes the member from batches and evaluation runs that name it, so no new request can charge it, and creates a durable job (subject `customer_member`) that the end-user deletion worker runs exactly like an end-user job: usage events and finalized receipts keep their tokens, costs and fingerprints with `customer_member` cleared (the organization and customer team stay); captured content, evaluation captures and annotations and client addresses of those requests are deleted; the member is redacted (`"erased"`) from the details of customer alert events. Budget counters, reservations and budget alerts keyed by the member are financial evidence and stay until their windows age out; the dry run reports them. Jobs never return the member ID. With auto-registration on, a later request that names the member registers it again: stop sending it first. ## Override approval requests Anyone who manages a team's customers (a global administrator, a team administrator of the team, a managing backend credential) may **request** a member override instead of setting it. A person other than the requester (and, for a request filed with a backend credential, other than the person who issued that credential) who administers the team (a global administrator or another team administrator of the team) **approves** or **denies** it; a backend credential never decides. Approval writes the override on the member at its current version in the same transaction, so the decision and the ceiling never diverge. | Field | Default | Meaning | | --- | --- | --- | | `customer_portal.require_override_approval` | `false` | `true`: team administrators and backend credentials cannot set or clear an override directly (`403 approval_required`); global administrators keep the direct write. | | `customer_portal.override_request_ttl_hours` | `168` | 1-8784. How long a pending request may be decided, captured when it is filed; after that it is `expired`. | ```bash # The backend (or a team administrator) files the request. curl -X POST "$API/organizations/acme/acme-co/members/alice@acme.example/override-requests" \ -H "Authorization: Bearer $CUSTOMER_CREDENTIAL" \ -d '{"budget_usd":"20","expires_at":"2026-11-30T00:00:00Z","reason":"launch week"}' # {"id":"cor_5b1e...","state":"pending","requested_by":"cpc_3f9a...","decide_by":"2026-11-23T...",...} # Another administrator of the team decides. curl -X POST "$API/override-requests/cor_5b1e.../approve" -d '{"note":"approved for the launch"}' ... curl -X POST "$API/override-requests/cor_5b1e.../deny" -d '{"note":"not this month"}' ... ``` | Answer | When | | --- | --- | | `409 request_pending` | The member already has a pending request (one per member; up to 1,000 pending per team). | | `403 self_approval` | The requester tries to decide its own request. | | `403 team_forbidden` | The decider does not administer the request's team. | | `409 request_closed` | The request was already decided, has lapsed (`expired`), or the requested override expiry has passed. | Filing, approving and denying are audited (`customer.override_request.create`, `.approve`, `.deny`, plus `customer.member.override` for the applied override) and write the alert events `customer_override_requested` and `customer_override_decided`: subscribe an [alert channel](/docs/features/alerting/) to be notified. Their `operational.detail` carries `team`, `org`, `member`, `request`, `budget_usd`, `expires_at`, `state`, `requested_by`, `decided_by` (decisions) and `request_id`. `GET /customer-portal/override-requests?team=&org=&state=` lists the requests of the session's teams, newest first. ## Per-model allowances and token ceilings Every level (organization, customer team, member, profile) may also carry: | Field | Default | Bounds and meaning | | --- | --- | --- | | `tpm` | `0` (none) | Tokens per minute of the level, up to 10^12; needs `tpm_limits`. | | `tpd` | `0` (none) | Tokens per UTC day of the level; needs `tpd_limits` and `tpm_limits`. | | `model_allowances[]` | none | Up to 16 allowances, one per model alias. | | `model_allowances[].model` | required | A configured model (not an `alias_of` name); requests for it under any of its client names count. | | `model_allowances[].budget_usd` | required | Positive decimal, up to six places: a hard ceiling. | | `model_allowances[].budget_period` | `month` | As `budget_period`; calendar and lifetime periods need their flags. | | `model_allowances[].fallback_model` | none | A cheaper configured alias used when the allowance is exhausted. | A member without its own `tpm`/`tpd`, or without its own allowances, follows its profile's, live. An organization or team allowance is shared by every member of that level; a member allowance is the member's own. Token ceilings and allowances are part of the same quota reservation as the budgets: the request fits all of them or none, concurrent requests never pass them, and they settle with the measured amount. A write naming an alias that is not configured, or a limit whose flag is off, is refused with `422`, so a stored limit is never silently unenforced. ```bash curl -X PUT "$API/organizations/acme/acme-co/members/alice@acme.example" -d '{ "tpm": 20000, "model_allowances": [ {"model": "smart-chat", "budget_usd": "10", "budget_period": "month", "fallback_model": "fast-chat"} ]}' ... ``` When an allowance is exhausted: - **With `fallback_model`**, a request of the chat pipeline (Chat Completions, and Messages or Responses requests translated through it to another provider's protocol) is answered through the fallback alias once, in the client's own dialect, with the same machinery as the [semantic fallbacks](/docs/features/routing-strategies/#semantic-fallbacks): the destination is admitted like a client request of the same key (its allowed models, team policy, flags, rate limits and the same customer's budgets and its own allowance), the client's attribution headers are carried, and the answer carries `X-Gateway-Fallback: allowance:`. The answer is recorded under the request ID `.fallback`, charged to the same organization, team and member; the relayed outer request names no customer, so customer usage counts it once. When the destination refuses before a provider answers (the key may not use it, its own allowance or budget is exhausted), the client gets the original `429` with `X-Gateway-Fallback-Refused: allowance:`. - **Without it**, or on a native route (native Messages, Responses or GenerateContent to a provider of the same protocol, embeddings, media), which have no fallback machinery, the request is refused with `429 quota_exceeded` and `X-Gateway-Quota-Policy: customer:model:` before any provider call. The fallback is one hop: the fallback alias's own allowance or budget is checked, but an exhausted fallback never falls back again, so a chain or a loop of allowances can never multiply sends or hide where a request was answered; the client gets the original refusal instead. The allowance is counted in its own counter (`customer_model`), so changing it never resets the level's budget, and raising it to what was already spent keeps it exhausted. Allowances raise no threshold alert; the level budgets do. ## Self-service customer view With `customer_self_service` (default `false`, an operator control that needs `customer_portal`), the operator's backend mints a short-lived, read-only **view link** for one customer organization or one member and hands it to that customer. The link opens `/customer-view`, which shows only that scope: its ceiling and committed spend in the current window and its usage by UTC day over the last 30 days. It never shows the operator team, keys, other members or any record. ```bash curl -X POST "$API/organizations/acme/acme-co/view-tokens" \ -H "Authorization: Bearer $CUSTOMER_CREDENTIAL" -d '{"member":"alice@acme.example","ttl_minutes":30}' # {"view_token":{"id":"cvt_9c2d...","expires_at":"..."},"token":"gwcv_...","path":"/customer-view#token=gwcv_..."} curl -X POST "$API/view-tokens/acme/cvt_9c2d.../revoke" ... # The page reads the same data with the token: curl https://gateway.example/v1/customer-view -H "Authorization: Bearer gwcv_..." ``` | Field | Default | Meaning | | --- | --- | --- | | `member` | none | Omitted: the whole organization's view. Otherwise a registered member. | | `ttl_minutes` | `60` | 1 to `customer_portal.view_token_max_minutes`. | | `customer_portal.view_token_max_minutes` | `1440` | 1-10080 (YAML/API), the longest a link may live. | The token travels in the link's fragment, so it is never sent to the server in a URL; the page removes it from the address bar and keeps it only in memory. Only its SHA-256 is stored; it expires by the database clock, can be revoked, and stops working when its organization or member is deleted. Minting needs `customers:manage` for the team (a managing backend credential, a team administrator or a global administrator); each mint and revocation is audited. Up to 1,000 live links per organization. Invalid links share the administrative Bearer failure limit. ## Who manages customers | Session | Reads | Writes | | --- | --- | --- | | Global administrator | every team | every team: records, overrides, trusted keys, credentials | | Viewer | every team | nothing | | Team administrator (`team_admin_console`) | the teams it administers | records, overrides (or override requests), trusted keys of its own team's keys, credentials, and decisions on other people's override requests, all of those teams | | Customer credential, `access: read` | its own team | nothing | | Customer credential, `access: manage` | its own team | records, overrides (or override requests) of its own team; never decisions | A team administrator sees and changes only the customers of the teams it administers (with `membership_roles`, the memberships where it is an administrator). Another team's organization, usage or credentials answer `403 team_forbidden`, and the organization list is filtered before its page bound. Every write is checked again inside its database transaction against the live actor: a team administrator removed from the team, a disabled user or a revoked credential is refused on its next write even when the request was already admitted. ### Backend credentials With `customer_portal_credentials` (default `false`, an operator control that needs `customer_portal`), a global administrator or a team administrator issues a **customer credential** for the operator's backend. It is a server-side secret bound to one operator team and to customer management: | Field | Default | Meaning | | --- | --- | --- | | `team` | required | The operator team; a team administrator only its own. | | `name` | required | 1-120 characters, one line. | | `access` | `manage` | `read`: the customer read routes of that team. `manage`: also its record, override and approval writes. | | `expires_at` | none | Optional; in the future and at most 1095 days away. | ```bash API=https://gateway.example/api/v1/admin/customer-portal # Issued from a console session; the secret is shown once (no-store). curl -X POST "$API/credentials" -d '{"team":"acme","name":"billing-backend","access":"manage"}' ... # {"credential":{"id":"cpc_3f9a...","team_id":"acme","access":"manage","state":"active",...},"secret":"gwcp_..."} # The backend then calls the customer routes with it; no cookie or CSRF token. curl -X PUT "$API/organizations/acme/acme-co/members/alice@acme.example" \ -H "Authorization: Bearer $CUSTOMER_CREDENTIAL" -d '{"customer_team":"eng"}' curl -X POST "$API/credentials/cpc_3f9a.../revoke" ... ``` The credential reaches only the customer record, usage and approval routes of its own team. It never opens the console, never changes trusted keys, never issues or revokes credentials and is no session on any other route (`401`). It is checked live on every call: revocation and expiry (by the database clock) apply to the next call, and a write already holding the credential finishes first. A credential also lives only as long as its issuer administers its team: when the person who issued it is disabled or deleted, loses the team administrator (or global administrator) role, or leaves the team (with `membership_roles`, stops being its administrator), or when the team is deleted, its next call answers `401` and the credential is revoked at once (`revoked_by: system:issuer-lost`, audited as `customer.credential.revoke_issuer_lost`); a sweep once a minute revokes the ones nobody presents. Writes are audited under the credential's ID (`cpc_...`); issuance and revocation are audited as `customer.credential.create` and `customer.credential.revoke`. Only the SHA-256 of the secret is stored, a team holds at most 100 active credentials, and a revoked credential stays listed as a tombstone. Failed attempts share the administrative Bearer limit (10 per client address per minute). Turning the flag off refuses every credential at once. ## How it is accounted Each named level becomes one budget of the request, next to the quota policies that already apply to it: - **One transaction.** The organization, customer team and member counters are reserved in the same PostgreSQL transaction as every other policy, after the customer records are read in that transaction: the request fits all of them or none. Concurrent requests of many members serialize on the counters, so no member passes its own ceiling and the members together never pass their team's or organization's. The ceiling is checked against reservations, not after the fact. - **Exact settlement.** Settlement moves every customer counter by the same measured amount as the other budgets; an unknown outcome keeps the hold. - **Windows.** Each level is counted in every money window (UTC day, month, calendar periods, lifetime), so changing a period never resets spend. - **Committed spend** shown by the API and the console is the counter of the current window: settled spend plus open holds. ## Alerts A level crossing one of its `alert_thresholds` writes a `quota_budget_threshold` alert and, in the same transaction, a `customer_budget_crossed` event, once per level, window and threshold, so a retried or concurrent request never repeats it. Subscribe an [alert channel](/docs/features/alerting/) to `customer_budget_crossed`; the webhook's `operational.detail` carries `team`, `org`, `level` (`org`, `team` or `member`), `customer_id` (team or member), `threshold`, `budget_usd`, `committed_usd`, `budget_period`, `window_start`, `soft_budget`, `basis` (`reservation` or `settlement`), `quota_alert_id`, `request_id` and `trace_id`. It holds no prompt, response or credential. A hard ceiling refuses a request that would pass it, so with hard budgets choose thresholds below 100 for an early warning. ## Usage per customer `GET /api/v1/admin/customer-portal/usage` reads the usage events of one operator team's customers over at most 366 days (default the last 30), optionally of one organization, grouped by `org` (default), `team`, `member`, UTC `day`, `model` or `day,model`. Each row has requests, input and output tokens, `estimated_usd` (known valuations priced from the price book with discounts and margins, an estimate, never a provider charge; with `budget_charge_reports`, `budget_charge` beside it is what the customer budgets took at the approved rates, the number the budget state counts, see [budget charge beside the estimate](/docs/features/usage-valuation/#budget-charge-beside-the-estimate)), the counts of partial, unknown and not valued events, and `tokens_unknown`. Up to 1,000 rows; `truncated` says more exist. `format=csv` exports the same rows for billing. **By model.** `by=model` gives one row per organization and served model alias, and `by=day,model` one row per organization, UTC day and model, newest day first (so a report cut at 1,000 rows keeps the recent days): what each customer used of each model, day by day. Add `org=` for one organization. The rows carry `model` (and `day`), and their CSV has a `model` column after `day`; the other groupings keep their columns. The numbers are the same as the structured usage query below grouped by `customer_org` and `model` (its `calls`, `input_tokens` and `output_tokens`). ```bash curl "$API/usage?team=acme&org=acme-co&by=day,model" ... # {"by":"day,model","rows":[{"org":"acme-co","day":"2026-11-25T00:00:00Z","model":"fast-chat","requests":412,"input_tokens":188000,"output_tokens":51200,"estimated_usd":"0.42",...}],"truncated":false} ``` **By any grouping.** The [structured usage query](/docs/features/ask-ai/#the-structured-usage-query) takes `customer_org`, `customer_team` (`org/team`) and `customer_member` (`org/member`) as dimensions and filters with this flag on, across every team the reader sees: spend, requests, tokens, the cost of one request and, with [evaluation metrics](/docs/features/evaluation-metrics/), pass rates by customer (`group_by=customer_org&metrics=cost_usd,p95_cost_usd`). **Usage → Cost estimates** shows the spend by customer organization, and **Usage → Quality** the results of an evaluation by the judged request's customer organization. ## Member search and sort `GET /customer-portal/organizations/{team}/{org}` takes three optional parameters that apply to its `members` (customer teams and profiles are returned as always): | Parameter | Default | Meaning | | --- | --- | --- | | `member_q` | none | Up to 120 characters. Keeps the members whose ID or name contains the text, ignoring case. | | `member_sort` | `id` | `id`, `name`, `budget` (the ceiling of the member's first effective window), `committed` (the committed spend of that window) or `utilization` (the largest committed share among the member's windows). | | `member_order` | `asc` | `asc` or `desc`. | Members without the sorted value (no budget, no name) come last in either order, and ties keep the ID order. An invalid value answers `400 invalid_member_query`. `?member_sort=utilization&member_order=desc` lists the members closest to a ceiling first. ## Console **Access control → Customer portal** (also shown to team administrators, scoped to their teams) lists the trusted keys (YAML entries without a revoke action), the organizations with their committed spend against the effective ceiling, and, for an opened organization, its customer teams, members and profiles with the ceiling source (override, own, profile or none) and overrides. Administrators create organizations and records, set overrides and trust keys; team administrators do the same for their teams; viewers read. **Backend credentials** issues a credential (the secret is shown once) and revokes it. **Import organization** takes a document (pasted or from a file) and a mode; the organization detail has **Export** and, for global administrators with end-user deletion on, **Erase member** with a dry run and an explicit confirmation. The organization detail also creates a **view link** for the organization or one member (shown once). **Override requests** lists the requests with **Approve** and **Deny**; the organization detail files a request (**Request override**) and, when direct overrides are allowed for the session, sets one (**Set override**). The usage panel groups by organization, team, member, day, model or day and model. The organization detail has **Search members** (by ID or name) with **Sort members by** ID, name, budget, committed spend or utilization, and **Daily usage by model**, the organization's last 30 days per UTC day and model. With `customer_budget_windows`, the organization and record forms take **Budget windows** (`1/day, 5/month`), each level shows every window with its committed spend, and the override form chooses the **Window** it replaces. **Portal settings** shows whether unknown organizations are registered automatically, the cap and the default profile. ## Upgrade Migration 300 adds the `budgets`, `override_period` and `auto_registered` columns of `gateway_customer_records` (constant defaults, no rewrite), the `budget_period` column of `gateway_customer_override_requests`, and widens a reservation's captured policies to 143 (`NOT VALID`, nothing is scanned). **Upgrade step for budget windows:** migrate and upgrade every replica, and only then turn `customer_budget_windows` on. An older replica knows one budget per level: it would enforce only the first window of a level that has several. To roll back, give those levels one budget first; with the flag off their requests are refused (`422 customer_budget_windows_disabled`), not admitted on one window. Migration 165 adds the customer columns of `gateway_batches` and `gateway_eval_runs` (no default, `NOT VALID` shape checks: nothing is rewritten or scanned) and `gateway_customer_view_tokens`. Migration 164 adds the member erasure columns of `gateway_end_user_deletions` and two partial expression indexes on the usage events and durable receipts that name a member (built in the migration: on a large usage table, run it in a maintenance window). Migration 163 adds `gateway_customer_override_requests`. Migration 162 adds the `tpm_limit`, `tpd_limit` and `model_allowances` columns (constant defaults, no rewrite) and widens a reservation's bounds to 182 charges and 134 captured policies (`NOT VALID`, nothing is scanned). Migration 161 adds `gateway_customer_credentials` (hashes only). Migration 160 adds `gateway_customer_records`, `gateway_customer_trusted_keys`, the `customer_org`, `customer_team` and `customer_member` columns of `gateway_usage_events` and `gateway_durable_usage` (no default and `NOT VALID` shape checks, so nothing is rewritten or scanned) and widens a reservation's bounds to 158 charges and 131 captured policies. **Upgrade step:** migrate and upgrade every replica, then turn the flag on, and only then trust keys. An older replica does not know the headers: it would admit a trusted key's request without the customer ceilings. To roll back, turn the flag off first (requests that still name a customer are then refused, not ignored). **Before migration 164 (operators):** it builds two indexes on `gateway_usage_events` and `gateway_durable_usage` inside the migration transaction, which blocks writes to those tables while they build. On a large usage table, run `gateway migrate` in a maintenance window before upgrading the replicas. ## Validation evidence Recorded 2026-11-16 against a running gateway (T158.007), separate from the in-process tests: the binary built with `go build ./cmd/gateway`, a `postgres:16-alpine` container, a mock OpenAI-compatible provider (10 input and 5 output tokens per answer, 50 ms latency) and a webhook receiver, all owned by the run and bound to 127.0.0.1. Synthetic customers only; **no real provider was called** (0 calls, 0 USD). The gateway ran with `customer_portal`, `customer_portal_credentials`, `customer_self_service`, `end_user_deletion`, `alert_channels`, team-scoped console users and `customer_portal.require_override_approval: true`, one YAML backend key trusted with `require_identity`, and a webhook channel subscribed to the three customer events (`allow_loopback_http`). | Step | Result | | --- | --- | | A team administrator (named user) issues a `manage` backend credential; the credential calls `GET /api/v1/admin/config` | `201`; `401` (no session outside customer routes) | | The credential imports an organization (1 profile, 1 customer team, 6 members) with `mode=create`; into another team | `200`, 9 records created; `403` | | Export from the team, import into a second team, export again | identical documents (9 records) | | Organization hard cap set to 5.5 reservations above its spend; 30 concurrent requests from 6 members | 5 admitted, 25 refused with `429`, 5 provider calls; committed with open holds 0.005308 USD and after settlement 0.000090 USD, both under the 0.028796 USD cap; member counters sum to the organization's | | Member at its own ceiling; the team administrator sets an override directly | `429 customer:member`; `403 approval_required` | | The credential files an override request (25 s); the credential approves; the team administrator approves | `201 pending`; `401`; `200 approved` | | The member's request under the override; again after it expires | `200`; `429 customer:member` (database clock) | | Member allowance for `public` exhausted, fallback `cheap` | `200` with `X-Gateway-Fallback: allowance:cheap`, one call to the cheap model, usage recorded on `.fallback` for the same member | | Webhook receiver | `customer_budget_crossed` ×2 (50 % and 80 % of the cap, reservation basis), `customer_override_requested` ×1, `customer_override_decided` ×1 | | View token for one member; the view; after revocation | `201`; only that member (6 requests), no operator team or other member; `401` | | Member erasure (dry run, confirm) through `POST /api/v1/admin/end-user-deletions`; the member's next request | 5 usage rows found and cleared, record deleted, job `waiting_receipts` (receipt quiet period); `422 customer_unknown` | | Backend credential revoked; its next call | `401` | The gateway logged no error during the run. The run's processes, database and secrets were removed afterwards. ## Limits of this release - Auto-routing helper calls are not charged to the customer. - An erased member's ID stays in budget counters and budget alerts (financial evidence) until their windows age out. Prefer opaque IDs when that matters. - Override approval gates overrides only: a team administrator or backend credential can still change a member's own `budget_usd` or import over it. Restrict who manages customers accordingly. - An allowance fallback answers chat-pipeline requests only, once (no chain); native routes keep the `429`. - Usage is reported from usage events. - `soft_budget` and `alert_thresholds` are per level, not per budget window. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `GET /api/v1/admin/customer-portal` | The portal settings: trusted keys, request header names, default alert thresholds and budget periods, and the effective `customer_portal` object (`require_override_approval`, `override_request_ttl_hours`, `auto_register_members`, `view_token_max_minutes`, `auto_register_organizations`, `max_auto_organizations`, `auto_organization_profile`), which the console shows read-only under **Portal settings**, and `max_budget_windows` | | `GET /api/v1/admin/customer-portal/credentials` | Lists the server-side credentials issued for operator backends | | `POST /api/v1/admin/customer-portal/credentials` | Issues a credential for an operator backend, bound to one team and to customer management | | `POST /api/v1/admin/customer-portal/credentials/{id}/revoke` | Revokes a credential at once | | `GET /api/v1/admin/customer-portal/organizations` | Lists the customer organizations of the caller's teams | | `POST /api/v1/admin/customer-portal/organizations/{team}/import` | Writes one `customer-portal/v1` document (organization, profiles, teams, members) into the team in one transaction; `mode=create` refuses existing records | | `GET /api/v1/admin/customer-portal/organizations/{team}/{org}` | Reads one customer organization with its teams, members and profiles; `member_q`, `member_sort` and `member_order` search and sort the members | | `PUT /api/v1/admin/customer-portal/organizations/{team}/{org}` | Creates or replaces a customer organization | | `DELETE /api/v1/admin/customer-portal/organizations/{team}/{org}` | Deletes an organization with all its teams, members and profiles | | `GET /api/v1/admin/customer-portal/organizations/{team}/{org}/export` | Exports one organization in the import format | | `PUT /api/v1/admin/customer-portal/organizations/{team}/{org}/members/{id}/override` | Sets a member's temporary budget ceiling | | `DELETE /api/v1/admin/customer-portal/organizations/{team}/{org}/members/{id}/override` | Clears a member's override at its current version | | `POST /api/v1/admin/customer-portal/organizations/{team}/{org}/members/{id}/override-requests` | Asks for a member override, for at most 366 days, to be approved by someone else | | `POST /api/v1/admin/customer-portal/organizations/{team}/{org}/view-tokens` | Mints a read-only view token for the organization or one member, returned once | | `PUT /api/v1/admin/customer-portal/organizations/{team}/{org}/{kind}/{id}` | Creates or replaces a customer team, member or budget profile of an organization | | `DELETE /api/v1/admin/customer-portal/organizations/{team}/{org}/{kind}/{id}` | Deletes a customer team, member or profile | | `GET /api/v1/admin/customer-portal/override-requests` | Lists the override requests of the caller's teams | | `POST /api/v1/admin/customer-portal/override-requests/{id}/approve` | Approves a pending request; never by its requester or the issuer of the credential that filed it | | `POST /api/v1/admin/customer-portal/override-requests/{id}/deny` | Denies a pending request, with the same rights as approving | | `PUT /api/v1/admin/customer-portal/trusted-keys/{key_id}` | Trusts a key to assert the identity of its team's customers, or changes `require_identity` | | `DELETE /api/v1/admin/customer-portal/trusted-keys/{key_id}` | Revokes a stored trust entry | | `POST /api/v1/admin/customer-portal/view-tokens/{team}/{id}/revoke` | Revokes a view token at once | # Content capture **Last updated:** 2026-11-26T02:16:00-03:00 (UTC-3) [Data inventory](/docs/security/data-inventory/) · [Cryptography](/docs/security/cryptography/) · [Access control](/docs/features/access-control/) By default the gateway keeps no prompt and no answer: logs, traces, request events and the request log carry metadata only. Some operators must keep what their users sent and received, for example for a regulatory audit. Content capture is that option. It stores the request and response bodies of a team's inference requests in PostgreSQL, encrypted, for a bounded time. What each person reads of it follows the content permissions of their role, from the whole record at the top down to metadata only, and every read is recorded. > **Turning this on changes your data profile.** Captured prompts and answers can contain personal data, secrets and anything else your users type. The gateway then holds that data for the retention you choose, in your database and in its backups. Decide with whoever is accountable for privacy and audit: which teams, which side (request, response or both), for how long, and who may read it. Prefer short retentions and few readers. ## How it works 1. The operator turns on the flag `content_capture` and configures the content key. 2. A team gets a **capture policy** (YAML or console). Without a policy nothing is captured, even with the flag on. 3. For each chat, Messages, Responses or generateContent request of that team the policy selects, the gateway copies what the client sent and what the client received, bounded, and after the answer is complete writes one encrypted record. 4. People read according to their role ([who can read](#who-can-read)): an administrator reads the whole record, a team administrator the request after guardrail masking and the answer, a viewer the record's metadata only. A global administrator can **grant** `content:read` to a named console user, for some teams or all of them, to give that user the whole record of those teams. 5. A reader opens a request in **Logs → Requests**, clicks **Show captured content**, and the gateway records the read in the audit log before returning the content. 6. Records are deleted when their retention ends, or earlier by hand. Three optional parts, each behind its own flag and off by default, add to what a record keeps: [captured images and audio](#captured-images-and-audio-content_capture_media), [the model's reasoning](#the-models-reasoning-content_capture_reasoning) and, for teams that keep no content at all, [the shape of the conversation on the span](#structural-items-on-the-span-span_structural_items). ## Enable it ```yaml features: console_users: true # required: every read is attributed to a named user content_capture: true # default false (operator control) storage: content_encryption_key_env: GATEWAY_CONTENT_ENCRYPTION_KEY content_encryption_previous_key_env: "" # only during a key rotation content_capture: policies: - team: support capture: both # request | response | both sample_rate: 1 # (0, 1] retention_days: 30 # 1 to 3650 max_bytes: 65536 # per side, 1024 to 1048576 keys: [] # optional: only these key IDs models: [] # optional: only these model aliases ``` Generate the key once and keep it in your secret store, next to the database backup procedure: ```sh openssl rand -hex 32 ``` The gateway refuses to start (or a console change to the flag is refused) when `content_capture` is on and the key is missing or is not 32 bytes in hex, when `console_users` is off, or when there is no database. The key is read like every other secret: environment variable, `_FILE` with `secret_files`, or a [secret manager](/docs/operate/secret-managers/). | Setting | Default | Accepted | Applied | | --- | --- | --- | --- | | `features.content_capture` | `false` | boolean; operator control | Runtime (feature API or console) | | `storage.content_encryption_key_env` | `GATEWAY_CONTENT_ENCRYPTION_KEY` in the shipped YAML | variable name; its value 64 hex characters | At write and read time | | `storage.content_encryption_previous_key_env` | empty | variable name, value 64 hex characters, different from the current key | Reads only | ### Policy fields The same fields apply in the YAML (`content_capture.policies[]`), the API and the console. | Field | Default | Bounds | Meaning | | --- | --- | --- | --- | | `content_capture.policies[].team` | required | team ID; one policy per team | The team whose keys are captured | | `content_capture.policies[].capture` | `both` | `request`, `response`, `both` | Which side is stored | | `content_capture.policies[].sample_rate` | `1` (also when `null`) | greater than 0 and at most 1; `0` is refused | Share of the team's requests captured, drawn at random per request | | `content_capture.policies[].retention_days` | `30` | 1 to 3650 | Days a record is kept; fixed when it is written | | `content_capture.policies[].max_bytes` | `65536` | 1024 to 1048576 | Bytes kept per side; a longer body is cut and marked `truncated` | | `content_capture.policies[].keys` | empty (every key) | up to 50 key IDs | Only requests made with these keys | | `content_capture.policies[].models` | empty (every model) | up to 50 aliases | Only requests that named these aliases (the name the client sent) | | `content_capture.policies[].disabled` | `false` | boolean | Keeps the policy but captures nothing; use it to switch a YAML policy off from the console | | `content_capture.policies[].identifiers` | `plain` | `plain`, `hashed` | How the team's organization, team and key IDs leave the gateway in [provider request labels](/docs/features/provider-request-labels/#plain-or-hashed-values): as they are, or as keyed digests. It applies whenever the team has a policy, also a `disabled` one and with `content_capture` off; it captures nothing | | `content_capture.policies[].request_view` | follows `purposes` | `received`, `sent`, `both` | Which copies of the request a record keeps; applies with `content_capture_evaluation` ([one policy for audit and evaluation](#one-policy-for-audit-and-evaluation-content_capture_evaluation)) | | `content_capture.policies[].purposes` | `[audit]` | `audit`, `evaluation`, `app_spans`, each at most once | Who may use a record; applies with `content_capture_evaluation` | | `content_capture.policies[].operations` | all four | `chat`, `messages`, `responses`, `generate_content` | The operations the policy captures; applies with `content_capture_evaluation` | | `content_capture.policies[].media` | defaults below | object | The bounds of the team's captured images and audio; applies with `content_capture_media` ([captured images and audio](#captured-images-and-audio-content_capture_media)) | A console policy replaces the team's YAML entry until it is removed; removing it returns to the YAML entry or to no capture. A change applies at once on the replica that saved it and within 30 seconds on the others. Records already written keep their retention. ## One policy for audit and evaluation (`content_capture_evaluation`) Audit and evaluation want different copies of the same request. An auditor needs what the user really submitted. A judge model, and the person reviewing its verdicts, must not see a secret that an input [guardrail](/docs/features/guardrails/) masked before the request went to the provider. With the flag `content_capture_evaluation` one team policy says which copies a record keeps and who may use them, and [live evaluation](/docs/features/evals/#evaluating-real-traffic-eval_capture) reads the content store instead of keeping a second one. Turn it on after `content_capture` works for you: ```yaml features: content_capture: true content_capture_evaluation: true # default false (operator control); requires content_capture eval_capture: true # only if rules should judge the captured requests content_capture: policies: - team: support capture: both purposes: [audit, evaluation] # default [audit] request_view: both # default follows the purposes operations: [chat, responses] # default: all four evaluation: # optional limits of the evaluation purpose sample_rate: 0.1 # evaluate a tenth of what is captured retention_days: 14 # evaluation reads a record for 14 days models: [] # default: every captured model operations: [chat] # default: every captured operation ``` | Field | Default | Values | Meaning | | --- | --- | --- | --- | | `request_view` | `received` for `[audit]`, `sent` for `[evaluation]`, `both` for the two | `received`, `sent`, `both` | `received` is the request exactly as the client sent it. `sent` is the request as the gateway holds it after its input stage: after a mandatory system prompt was added and the input guardrails masked it. `both` keeps the two, as two copies | | `purposes` | `[audit]` | `audit`, `evaluation`, `app_spans` | `app_spans` (T186.016): the message content of the team's [OTLP-ingested application spans](/docs/features/otlp-ingest/#content) is stored, normalized to role and content, readable under the same grants as audit; a policy with `app_spans` alone captures no inference request. `audit`: the record is kept for the people whose [permissions](#who-can-read) cover it. `evaluation`: evaluators, review queues, session transcripts and dataset imports also read its sent view and its answer | | `operations` | all four | `chat`, `messages`, `responses`, `generate_content` | The operations the policy captures | ### Limits of the evaluation purpose Audit usually wants everything, for a long time. Evaluation usually wants a sample, for a short time. The `evaluation` block gives the evaluation purpose its own limits inside the same policy. Each one is optional, and none can be wider than the policy: | Field | Default | Bounds | Meaning | | --- | --- | --- | --- | | `content_capture.policies[].evaluation.sample_rate` | all captured requests | greater than 0 and at most 1 | Share of the captured requests that also carry the evaluation purpose. It is decided by the request ID, so the same request always decides the same way on every replica | | `content_capture.policies[].evaluation.retention_days` | the policy's `retention_days` | 1 to the policy's `retention_days` | Days judges and evaluation reviewers may read a record. After that the record stays for audit until it expires | | `content_capture.policies[].evaluation.models` | every captured model | up to 50, each a model the policy captures | Only these models are evaluated | | `content_capture.policies[].evaluation.operations` | every captured operation | among the policy's `operations` | Only these operations are evaluated | A captured request the limits leave out is an audit record and nothing else: its `purposes` say `audit`, no rule is queued on it, no `skipped` result is written, and the evaluation screens do not list or open it. So a team can audit every request for a year while its evaluation reviewers read one request in ten, of one model, for two weeks. The limits need the `evaluation` purpose (400 otherwise). Rules the gateway enforces: - **Evaluation never reads the received view.** A judge prompt, a review queue item, a session transcript and a dataset built from captures get the sent view and the answer, whatever else the record holds. - **The `evaluation` purpose needs `capture: both` and `request_view: sent` or `both`.** A judge reads the masked request and the answer; a policy that keeps neither is refused with `400` instead of producing rules that skip every request. - **A request the input guardrails refused has no sent view**: nothing was sent on. Its record keeps the received view (when the policy asks for it) and the refusal the client got, and it is not an evaluation record: its `purposes` say `audit` only, whatever the policy says. - **The sent view has one shape whether or not a guardrail changed the request.** It is the body the input stage let through, in the Chat Completions shape when the gateway translated a Messages, Responses or generateContent request before its guardrails ran (`dialect: chat`), so a judge reads the same structure for every request. Native generateContent requests are read by no input guardrail: their sent view is the received body, stored once (`same_as_received: true`) when the record keeps both. - **A policy for evaluation alone stores only what a judge can read**: served requests (status 200) with a sent view and an answer. Refused and failed requests of such a team leave no record. With the `audit` purpose every outcome is recorded, as before. - **Streams and every captured operation are judged.** A streamed answer is judged from the text the stream carried. A cache hit is captured as the client received it and judged like any other answer. - **A record kept for audit alone is not a judge's to read.** When a rule matches such a request, its result is `skipped` with the reason `content_not_captured`, so the gap is visible instead of silent. A request or an answer longer than `max_bytes` is `skipped` with `content_truncated`: raise `max_bytes` (up to 1 MiB) for teams with long conversations. - **With the flag off the three fields are stored but not applied, and never widen a policy.** A policy that has the `audit` purpose, keeps the received view and covers all four operations captures the request as received, for audit, as it always did. Any other policy (evaluation alone, the sent view alone, some operations) captures nothing while the flag is off: turning the flag off never starts storing a copy or an operation the policy was written to leave out. Each request span says what happened to its content, never the content itself: the attribute `capture_state` is `not_captured`, `audit_only` or `evaluation`, with `capture_id` naming the record (stored spans on both span engines, and `gateway.capture.state` / `gateway.capture.id` on the exported OTLP server span). **Logs → Requests → Open trace** shows it as *Content*. ### What evaluation readers see The evaluation screens (a capture in **Evals → Live**, a review queue item, a session transcript, a dataset built from captures) show the sent view and the answer of a team's records that carry the `evaluation` purpose. They need `evals:manage` for the team, as before, and they follow the same [ladder](#who-can-read) as every other read: a reader needs `content_sent:read` of the record's team, sees the model's reasoning only with `content_reasoning:read`, and gets image and audio parts only with `content_media:read`; without them those parts are marked as withheld. The built-in team administrator holds all three. The evaluation screens never show the received view, whatever the reader holds: they show what a judge reads. Each such read is written to the audit log (`content_capture.read`, with what was shown in its target, for example `view:sent+reasoning+media`) before the content is decrypted; when the audit row cannot be written the read is refused. Add the `evaluation` purpose only for teams whose masked requests those people may read: unless you set [limits](#limits-of-the-evaluation-purpose), every record the policy captures, for its whole retention, becomes readable by them, not only the requests a rule samples. A judge's own read is not audited row by row: the purpose on the policy is the authorization, and every judge call is a request in the request log. ### Upgrade: the evaluation capture policies move here Before this flag, live evaluation had its own capture policy per team (Evals → Live) and its own store. The first time the gateway runs with `content_capture_evaluation` on, it folds each of those policies into the team's content capture policy, once, and reports it under **Content capture → Moved from evaluation capture** (and in `migrated` of `GET /api/v1/admin/content-capture`). No capture becomes broader than either policy allowed: | The team had | Result | Outcome | | --- | --- | --- | | An evaluation policy and no active content policy | A console policy for evaluation alone: `capture: both`, `request_view: sent`, `purposes: [evaluation]`, `operations: [chat]` (the only operation the evaluation capture covered), the evaluation policy's sampling, models and retention, `max_bytes` 524288; disabled if the evaluation policy was. A disabled console policy it replaces is kept in the report | `created` | | An evaluation policy and a content policy that captures both sides | The content policy keeps its sampling, retention, `max_bytes`, keys and models, and gains `purposes: [audit, evaluation]` with `request_view: both` (a policy that kept only the sent view keeps only it). The evaluation purpose gets the evaluation policy's own [limits](#limits-of-the-evaluation-purpose): its sampling, its models, its retention and `operations: [chat]`. No rule changes | `merged` | | A policy that could not be written (it would not validate) | Nothing changes; the reason is in the report | `skipped` | | An evaluation policy and a content policy that captures one side, that does not capture chat or that shares no model with it, or a disabled evaluation policy beside a content policy | Nothing changes; the team's requests are no longer judged until an administrator adds the `evaluation` purpose | `kept_audit` | | Only a content policy, or no policy | Nothing changes | (not listed) | **The fold is lossless for a team that had both policies.** Audit goes on exactly as the audit policy said. Judges and evaluation reviewers read what the evaluation capture let them read and no more: the same share of requests (chosen by the request ID, as before, among the requests the audit policy captures), the same models, for the evaluation policy's retention. Two things are new for those requests, and they are the point of this feature: a streamed answer and a cache hit are now judged too. To evaluate Messages, Responses or generateContent requests, or more of the traffic, widen the evaluation limits yourself; the console asks you to confirm. A content policy that lives in the YAML cannot be edited by the gateway: the fold copies it into a console policy that adds the purpose. To keep the YAML as the source, add `purposes` and `request_view` to the YAML entry and remove the console policy. The schema change is migration 206: five columns on `gateway_content_captures` with constant defaults and a table that remembers which teams were folded. It rewrites and scans nothing, so it is quick on a large table, and it is applied whether or not the flag is on. After the fold: - `PUT /api/v1/admin/evals/capture-policies/{team}` answers `409 capture_policy_moved`; `GET /api/v1/admin/evals/capture-policies` is a deprecated, read-only view of the content policies that carry the `evaluation` purpose. - Captures the evaluation capture wrote before stay where they are, encrypted under the providers key, and stay readable by rules, review queues and dataset imports until they expire (at most 90 days). They are not copied or re-encrypted. New captures are written only to the content store, under the content key. - Turn the flag on only when every replica runs a version that has it: a replica of an older version keeps writing to the evaluation capture store and accepts its policy API. - Turning the flag off again returns plain audit policies to their audit behaviour and live evaluation to its own capture. The folded policies stay as written (those for evaluation alone idle). A team is folded once: when the flag comes back, only evaluation policies created meanwhile are folded, and a change made to an already folded team through the old API while the flag was off is not carried over. - The first request, or the first read of the Content capture page, after the flag is on starts the fold. Requests do not wait for it: for the moment it takes, capture goes on under the policies as they were. ## What is captured | Route | Operation | | --- | --- | | `POST /v1/chat/completions` | `chat` | | `POST /v1/messages` | `messages` | | `POST /v1/responses` | `responses` (stateless and stored responses; not the Conversations and Containers routes) | | `POST /v1beta/models/{model}:generateContent` and `:streamGenerateContent` | `generate_content` | - **Request:** the body exactly as the client sent it, before any input guardrail masks it. An audit record of a masked prompt would not show what the user submitted. If a team must not keep data that a masking guardrail removes, capture only `response` for it, or, with [`content_capture_evaluation`](#one-policy-for-audit-and-evaluation-content_capture_evaluation), keep only the `sent` view. - **Response:** the body exactly as the client received it. For a stream, the record keeps the **text** the stream carried (the content deltas of Chat Completions, Messages, Responses and generateContent), joined at the end, with `format: stream_text`; the raw events and tool call arguments are not kept, and a stream with no text stores an empty text. Reasoning deltas are never part of that text: they are dropped, or kept as their own part with [`content_capture_reasoning`](#the-models-reasoning-content_capture_reasoning). - **Output guardrails ([T107](/docs/features/guardrails/)):** an answer blocked at output is stored as the refusal the client got, never as the blocked text, and the record has `output_blocked: true`. A masked answer is stored masked. - **Every outcome:** a request refused after authentication (guardrail, budget, provider error) is captured with its status and the error the client got. A request refused before its body was read stores an empty request side. - **Not captured:** requests the gateway makes for itself (batch items, eval runs and judges, m7 ai, auto-routing classification, semantic fallbacks, moderation guardrail calls, vector store embeddings), Realtime sessions, embeddings, media and the other operations. Batch input files are kept by the Files API under its own lifecycle. Playground calls use a client key and are captured like any other request of its team. **The task of an agent run.** With [`agent_recognition`](/docs/features/agent-recognition/#task-capture) and `agent_recognition.task_capture` set to `preview` or `full`, the first 200 or 2,000 characters of the text a user typed to start a coding-agent run are kept with the run, for the teams whose policy here keeps requests (`capture: request` or `both`, not `disabled`), for the runs whose first call the policy covers: its key, model and operation when the policy lists `keys`, `models` or `operations`, and the policy's `sample_rate`. It is content of the sent view: sealed with the content key like a record, bound to its run, expiring after the policy's `retention_days`, read with `content_sent:read` and audited. It is stored in the run's row of `gateway_agent_runs`, not as a capture record, so it is not in the captures list. With `content_capture` turned off, the text already kept is shown to nobody. Each record has metadata in clear: ID, request ID, team, key ID, model, operation, HTTP status, which sides were captured, whether it was a stream, the original size of each side, truncation, `output_blocked`, the reference of the key that wrapped it, when it happened and when it expires; with `content_capture_evaluation` also `request_view` (`received`, `sent`, `both`, or `none` when the record keeps no copy of the request), `purposes`, and the size and truncation of the sent view. The content itself is only in the encrypted envelope. ## Captured images and audio (`content_capture_media`) A request with an image, or an answer with audio, is mostly base64. Without this flag the record keeps those bytes inside the body, up to `max_bytes`, so a multimodal request is usually cut and cannot be judged. With the flag `content_capture_media` the gateway moves each image and audio out of the body into a **media store**: the body keeps a short reference in its place, and the bytes become attachments of the record. ```yaml features: content_capture: true content_capture_media: true # default false (operator control); requires content_capture content_capture: policies: - team: support media: max_items: 4 # attachments kept per record max_item_bytes: 2097152 # one attachment, decoded max_team_bytes: 1073741824 # everything the team's records keep at once disabled: false # true: keep no media for this team ``` | Field | Default | Bounds | Meaning | | --- | --- | --- | --- | | `features.content_capture_media` | `false` | boolean; operator control; requires `content_capture` | Turns the media store on for every team with a policy. Runtime (feature API or console) | | `content_capture.policies[].media.max_items` | `4` | 1 to 16 | Attachments stored per record, request and answer together. Further ones are named in the record (type, size, hash) and not stored | | `content_capture.policies[].media.max_item_bytes` | `2097152` (2 MiB) | 1024 to 10485760 | Size of one attachment, decoded. A larger one is named by its type and size and not stored (nor decoded, so it has no hash); it is never cut, because half an image is no image | | `content_capture.policies[].media.max_team_bytes` | `1073741824` (1 GiB) | 1048576 to 107374182400 | Everything the team's retained records keep in the store. When a new record would pass it, the record is written without media and names each attachment as not stored (`team_limit`), until older records expire | | `content_capture.policies[].media.disabled` | `false` | boolean | Keeps this team's media out of the store with the flag on | The same fields are in the YAML, in `PUT /api/v1/admin/content-capture/policies/{team}` and in the policy form of the **Content capture** page (**Captured images and audio**). With the flag off they are stored and not applied. How it behaves: - **What is taken.** At most 64 attachments per body are looked for, stored or not; anything after that stays in the body as it came. A media type must be a plain `image/…` or `audio/…` type (letters, digits, `.`, `+`, `-`); anything else stays in the body. Inline images and audio in the four captured dialects: `data:` URLs of `image/*` and `audio/*` (Chat Completions `image_url`, Responses `input_image`), `input_audio` data, Messages base64 `image` sources, generateContent `inlineData`, the `audio` of a Chat Completions answer and a generated image of a Responses answer. Images referenced by URL are not fetched: the URL stays in the body. Other files (a PDF, a video) stay in the body. - **The record keeps a reference and a hash.** In the stored body each attachment is replaced by `gateway-media:`. The record's `media` list says, for each one: `id`, `source` (`request` or `response`), `kind` (`image` or `audio`), `content_type`, `bytes`, `sha256` of the bytes, `stored`, and `reason` when it was not stored (`item_too_large`, `record_limit`, `team_limit`, or `store_failed` when the attachments could not be written in time and the record was kept without them). The hash is inside the encrypted record, never in a clear column. - **The record comes first.** If writing the attachments fails, the record is written again without them, so an audit record is never lost to its media. - **Media is never on a span**, in a log line or in OTLP. - **Request media is taken after the input guardrails.** A request the guardrails refused keeps no media. The sent view, no longer swollen by base64, is then usually whole, so a multimodal request can be judged from its text. The received view stays the bytes as the client sent them, within `max_bytes`. - **Answer media** is taken from a buffered answer the gateway could read whole: up to `max_bytes` plus 8 MiB. A larger answer is cut as before and keeps no media. The audio or images of a streamed answer are not captured. - **Encryption.** Each attachment is sealed with AES-256-GCM under its record's own data key, bound to its record, team, request, type and size, so it cannot be moved to another record or relabelled. A [key rotation](#rotating-the-content-key) rewraps one key per record and the media follows; there is nothing more to rewrap. - **Retention and isolation.** An attachment lives exactly as long as its record: the retention purge, a deletion by hand and the end of the evaluation purpose apply to both. Every row carries the request ID, team, organization, key and principal of its request. A reader of another team or organization gets 404 for it, also when the attachment ID is known. - **Judges.** An evaluator with `multimodal: true` gets the record's stored images back in place of their references (up to five, as before). Any other judge reads the text and the references. - **Datasets.** An item built from a capture keeps text and tool traffic only: each image or audio becomes a text part `[media not imported]`, so the item never points at an attachment that will expire. Read an attachment with: ```http POST /api/v1/admin/content-captures/{id}/media/{media_id} X-CSRF-Token: ... ``` It needs `content_media:read` of the record's team ([who can read](#who-can-read)) and answers the bytes with their stored `Content-Type` (`application/octet-stream` for anything that is not a plain image or audio type), `Content-Disposition: attachment`, `X-Content-Type-Options: nosniff`, `Cache-Control: no-store` and `X-Gateway-Media-Kind`. Like a reveal, it is a POST with the CSRF token and writes its audit row (`content_capture.media.read`) in the transaction that reads the attachment. It answers 404 with the flag off, for an unknown attachment and for one outside the reader's teams, and 403 without the permission. `GET /api/v1/admin/content-capture` adds `media` and `reasoning` (the two flags), `media_usage` (attachments and bytes stored per team) and `media_limits` (the bounds above). The schema change is migration 208: four counters on `gateway_content_captures` (`media_count`, `media_bytes`, `reasoning_bytes`, `reasoning_truncated`), the table `gateway_content_media` and one column on the evaluators. It rewrites nothing and is applied whether or not the flags are on. ## The model's reasoning (`content_capture_reasoning`) Models that reason before answering return that reasoning beside the answer. With the flag `content_capture_reasoning` a record keeps it as **its own part**, apart from the answer, for streamed and buffered answers alike: | Client API | Buffered answer | Streamed answer | | --- | --- | --- | | Chat Completions | `message.reasoning_content` (or `reasoning`) | `delta.reasoning_content` (or `delta.reasoning`) | | Messages | `thinking` blocks | `thinking_delta` | | Responses | `reasoning` items (summary and reasoning text) | `response.reasoning_summary_text.delta`, `response.reasoning_text.delta` | | generateContent | parts marked `thought` | parts marked `thought` | Every provider the gateway translates reaches the client in one of these four shapes, so the same capture covers them all. ```yaml features: content_capture: true content_capture_reasoning: true # default false (operator control); requires content_capture ``` | Setting | Default | Accepted | Applied | | --- | --- | --- | --- | | `features.content_capture_reasoning` | `false` | boolean; operator control; requires `content_capture` | Runtime (feature API or console) | - The part is bounded by the policy's `max_bytes`, like each side, and marked `truncated` when cut. It is stored only for policies that capture the response, and not for an answer an output guardrail blocked. - **Only readers with `content_reasoning:read`** get it ([who can read](#who-can-read)): `reasoning` in a reveal and in the evaluation screens. A reader without it gets the answer as text and, in a conversation, a mark where reasoning was. This holds for records written before the flag too: a buffered answer's raw body, which may hold reasoning, is shown only to readers who hold the reasoning permission. - **Judges do not read reasoning unless their evaluator asks.** An evaluator has `include_reasoning`, `false` by default (**Evals → Evaluators → Include the model's reasoning**, or the field in `POST /api/v1/admin/evals/evaluators`). When it is true, a live rule's judge gets the reasoning after its prompt, labelled as not part of the answer. Without it the judge also reads the conversation without the reasoning of earlier turns (thinking blocks, reasoning items, thought parts a client sent back). Code evaluators take no reasoning. - **Datasets never keep reasoning**: an item built from a capture is the conversation and the answer as text. - A reasoning part cut at `max_bytes` is shown to readers as truncated and is not given to a judge. - Reasoning the provider returns encrypted or as a signature is not text and is not captured. ## Structural items on the span (`span_structural_items`) A team that captures no content can still record the **shape** of each conversation, without a word of it. With the flag `span_structural_items` the request span gets one bounded `structure` attribute, and the exported OTLP server span the same as `gateway.structure.*` attributes: | Item | Stored span (`structure`) | OTLP attribute | | --- | --- | --- | | Number of messages | `messages` | `gateway.structure.messages` | | Roles, in order | `roles`: one letter per message (`s` system, `d` developer, `u` user, `a` assistant, `t` tool, `o` other), at most 32, then `+` | `gateway.structure.roles` | | Messages per role | `role_counts` | `gateway.structure.role.` | | Tools declared | `tools_declared`, `tool_names` (at most 16 names, sorted) | `gateway.structure.tools_declared`, `gateway.structure.tool_names` (comma separated) | | Tool calls in the conversation | `tool_calls`, `tool_call_names` (at most 16) | `gateway.structure.tool_calls`, `gateway.structure.tool_call_names` | | Attachments by type | `attachments`: `image`, `audio`, `file`, `video` | `gateway.structure.attachments.` | | File parts that name a slice or a resolution ([file inputs](/docs/features/file-inputs/)) | `file_slices` | `gateway.structure.file_slices` | | Token split | `tokens`: `input`, `output`, `cached_input`, `reasoning`, `cache_write`, as far as the provider reported them | `gateway.structure.tokens.` | ```yaml features: span_structural_items: true # default false (operator control) ``` | Setting | Default | Accepted | Applied | | --- | --- | --- | --- | | `features.span_structural_items` | `false` | boolean; operator control | Runtime (feature API or console) | - **Tool names leave the gateway with the span.** They are names your application chose; with `otlp_traces` they are exported to your OpenTelemetry receiver like the rest of the span. Leave the flag off if tool names are confidential. - **No content.** A tool name is recorded only when it is a short identifier (letters, digits, `_ - . : /`, at most 64 bytes); any other name is counted and not recorded. Role values outside the known ones are counted as `other`. Nothing else of a message is read. - **Bounded.** The attribute stays under 4 KiB whatever the conversation. None of it becomes a metric label. - **Where it is read.** It needs a reader: the [span store](/docs/features/traces/) (`span_store`, on either span engine) or the OTLP trace export (`otlp_traces`). In the console, **Logs → Requests → Open trace** shows *Conversation*, *Tools declared*, *Tool calls in the conversation*, *Attachments* and *Token split* on the request span. - **Who sees it.** Readers with `content_structure:read` of the span's team, the lowest rung of the [ladder](#who-can-read). For anyone else the attribute is left out of the span. - It does not need `content_capture`, and it records the request as the input guardrails let it through; a request refused before them has no structure. - Tool calls counted are the ones in the conversation the client sent (earlier turns). The calls of the answer being produced are not read, since nothing of the answer is kept: they appear on the next turn's span. ## Encryption Each record has its own random 256-bit data key. The content is sealed with AES-256-GCM under that data key, and the data key is sealed with AES-256-GCM under the content key (envelope encryption). Both seals are bound to the record by associated data that covers its ID, request ID, team, key, model, operation, status, sides, sizes, truncation, `output_blocked`, time and expiry (the wrapped data key also binds the key reference; a record written with `content_capture_evaluation` also binds its request view, its purposes, the size of its sent view and the end of its evaluation purpose, so nobody can add the `evaluation` purpose to a stored audit record): moving a ciphertext to another row, or changing any of that metadata in the database, makes decryption fail instead of returning the content under a false label. The record stores only a 16-character reference of the key (an HMAC of a fixed label under the key), never the key. Details in [cryptography](/docs/security/cryptography/). Why a key of its own, and not the providers key: the content key can be rotated or destroyed on its own. Destroying it makes every capture unreadable at once (a cryptographic erase), without touching provider secrets. ### Rotating the content key There are two ways: rewrap the stored records under the new key with `gateway content-rewrap`, or let the old records expire. #### Rewrap with `content_key_rotation` `content_key_rotation` is a boot operator flag, `false` by default. It needs `storage.content_encryption_key_env` and a database, even when `content_capture` itself is off. A rewrap changes only the record's key reference and its 60-byte wrapped data key. The content ciphertext, the metadata and the expiry are never rewritten, so the command is fast and can run while the replicas keep serving. 1. Take and verify a PostgreSQL backup, and keep the old key with it ([backup and recovery](/docs/security/business-continuity/)). A backup without the key that wrapped its records cannot be read. 2. Generate the new key (`openssl rand -hex 32`). **First rollout:** keep the old key as the current key, add the new one as `content_encryption_previous_key_env` and set `content_key_rotation: true`. Every replica can now read both keys and still writes with the old one. 3. **Second rollout:** swap the two references, so the new key is current and the old one is previous. A replica still on the first step writes with the old key, but every replica reads both, so no record becomes unreadable during the rollout. 4. Run `gateway content-rewrap --check` (read-only, exit 3 while records need a rewrap), then `gateway content-rewrap --apply` beside the serving replicas, with the same key configuration as them. Each batch of `storage.reencrypt.page_size` records commits on its own, with one `content_key.rewrap` audit row. An interrupted, cancelled or timed-out run keeps the batches it committed, and running it again resumes. The rewrap never waits on a record that a reveal, a deletion or another run holds: it skips it, and the next run picks it up. Run it again until it exits 0: skipped records and records that a replica on the first step wrote during the run are found by the next run. The same pass rewraps the task texts of [agent runs](/docs/features/agent-recognition/#task-capture), which the content key wraps too: they are counted with the records in every figure of the command and of `key.rotation`, and an unexpired task text blocks the retirement of its key in step 6 like an unexpired record. 5. Check **Content capture** in the console, or `key.rotation` in `GET /api/v1/admin/content-capture`: `current_records`, `previous_records` and `unknown_records` are live counts (expired records awaiting the purge included), and `complete` is true when every record uses the current key. 6. Remove `content_encryption_previous_key_env` and roll out. With the flag on, a replica refuses to start (`content key check failed: content key retirement refused`) while any unexpired record names a key that is not configured. Expired records are never revealed and do not block the start; the purge removes them. Restore the key instead of working around the refusal. If the check itself cannot run, the error says `content key usage could not be checked` instead. 7. Keep the old key as long as a backup taken before step 6 might be restored. **The target key comes from the command's own environment.** `--apply` refuses (`current_key_unused`) when stored records exist but none uses its current key yet, because nothing then shows that the serving replicas hold that key: moving every record to a key they lack would make all of them unreadable. Usually a replica on step 3 has already written a record with the new key. When capture is quiet, or for a rollback, confirm the replicas run that key and pass `--apply --unused-current-key`. **Rollback.** Until the old key is retired, swap the two references back and run `--apply --unused-current-key` again: the records are rewrapped to the old key in the same way. **Startup only.** The retirement check runs when a replica starts. Serving replicas resolve the content keys again on each capture and reveal, so a key removed from a secret file or a secret manager without a restart is not refused: reveals of its records answer `503 encryption_unavailable` until it is restored. Change content keys only through a rollout. | Exit | Meaning | | --- | --- | | `0` | No record left on another key | | `3` | A check found records to rewrap, or an apply finished while records written meanwhile with the previous key remain: run it again | | `1` | Invalid configuration, flag off, no current key, an unused current key without acknowledgement, database or schema unavailable, cancellation or timeout, an uncertain commit, or records left untouched | | `2` | Invalid syntax: only `--check`, `--apply` and `--apply --unused-current-key` are accepted | Each run logs one `content_rewrap_checked` or `content_rewrap_applied` line with counts (`scanned`, `pending`, `rewrapped`, `already_current`, `unknown_key`, `unreadable`, `vanished`, `batches`, `remaining`), or `content_rewrap_failed` with a finite `reason`. It never logs a key, a ciphertext or content. `commit_outcome_unknown` means the connection ended during a batch commit, which may have succeeded: run a check before anything else. The command reads `storage.reencrypt.page_size` and `storage.reencrypt.timeout`, and never applies a schema migration: run `gateway migrate` first (migration 146 adds the key-reference index). **Failing closed.** Before writing, the command authenticates every wrapped data key with the key its record names. A wrong previous key has another reference: the records are counted as `unknown_key` and left untouched, and the boot is refused. A key that claims the right reference but is not that key, or a record altered in the database, is counted as `unreadable` and left exactly as it was. Nothing is deleted to make a run look complete. Each update is a compare-and-swap on the old reference and wrapped key, on a locked record, so a reveal, a deletion or a second run at the same time never sees a mixed record. **Recovery.** Restore the backup with the keys it needs, both of them for a backup taken during a rotation, and run `--check` and `--apply` again: a backup taken mid-rotation resumes like an interrupted run. Starting a restored database with only the new key is refused and changes nothing. #### Rotate by retention 1. Generate a new key. Set it as the current key and the old one as `content_encryption_previous_key_env`, and roll out. New records use the new key; old records stay readable. 2. Wait for the longest `retention_days` of your policies. Every record written with the old key has then expired and been purged. 3. Remove `content_encryption_previous_key_env` and destroy the old key. Because the expiry is bound to the ciphertext, a record's retention cannot be changed in place. A record whose key is no longer configured answers `503 encryption_unavailable` when revealed. ## Who can read What a person reads of captured content follows the permissions of their role. There are five content permissions, and they form a ladder: the top role holds all of them and each role below holds fewer. | Permission | What it lets a person read | | --- | --- | | `content_structure:read` | The metadata of a record (the list) and the [structural items](#structural-items-on-the-span-span_structural_items) of a span. No content | | `content_sent:read` | The sent view (the request after the input guardrails) and the answer, as text | | `content_reasoning:read` | The model's [reasoning](#the-models-reasoning-content_capture_reasoning) | | `content_media:read` | Captured [images and audio](#captured-images-and-audio-content_capture_media) | | `content_received:read` | The received view: the request exactly as the client sent it, before any guardrail masked it | Which built-in role holds which: | Role | Reads | Of which teams | Structure | Sent view | Reasoning | Media | Received view | | --- | --- | --- | --- | --- | --- | --- | --- | | `admin` | Everything | Every team | yes | yes | yes | yes | yes | | `org_admin` | Everything | The teams of its organization | yes | yes | yes | yes | yes | | `team_admin` | The sent view, reasoning and media | The teams it administers | yes | yes | yes | yes | no | | `team_viewer` | Metadata only | Its teams | yes | no | no | no | no | | `user` | Metadata only | Its teams | yes | no | no | no | no | | `operator` | Metadata only | Every team | yes | no | no | no | no | | `viewer` | Metadata only | Every team | yes | no | no | no | no | The rules behind the table: - **A reader of text is shown only what is known to be text.** Without the reasoning or the media permission, a conversation is narrowed to text parts, tool calls and tool results; any other part or field, including one a provider adds later, is replaced by a mark (`{"type": "withheld", "kind": "media" | "reasoning" | "other"}`) or left out. - **One rule for every screen.** The reveal in the request details, the media read, the evaluation screens, the review queue, a session transcript, a dataset built from captures, a judge's reasoning on an evaluation result and the structural items of a span all ask the same function what the session's permissions cover of the record's team. - **Organizations are never crossed.** A role scoped to teams reads only its own teams; an [organization admin](/docs/features/organization-admins/) reads only the teams of its organization. A record of another team or organization answers 404, like a record that does not exist. `admin`, `operator` and `viewer` are the gateway's own roles and read every team. - **With `membership_roles`**, a team a team administrator only belongs to (association `member`) gives the member's share: metadata. - **The operator reads no content.** It changes routing and provider credentials and reads no request log, so of captured content it holds metadata only. An operator who must read content needs a role that does, or a `content:read` grant. - **An evaluator** is, in the built-in roles, the team administrator: it is the role that holds `evals:manage`. To give someone the review screens with less, bind a [custom role ceiling](/docs/features/custom-roles/) on `team_admin` that withholds what they should not read. - **A custom role ceiling can withhold any of the five and never adds one.** The catalog offers each content permission only to the base roles that hold it: `content_structure:read` to all five bases; `content_sent:read`, `content_reasoning:read` and `content_media:read` to `team_admin` alone; `content_received:read` to none. A ceiling that allows only `content_structure:read` reads metadata; one that keeps `content_sent:read` without the other two reads the conversation and the answer as text. A ceiling that lists none of them reads nothing, so add `content_structure:read` to existing ceilings whose users should keep seeing the capture state details. - **The received view names a person.** A session opened with the shared admin token is audited as that token, which names nobody: it reads what the administrator reads except the received view. The shared viewer token reads metadata. ### The `content:read` grant Below the administrator, the received view is not part of any role. A global administrator can give it to one named person for some teams: | Permission | Who has it | What it allows | | --- | --- | --- | | `content_capture:manage` | the global `admin` role | Policies, reader grants, deletion | | `content:read` | **nobody by role**; a named console user with an explicit grant | All five content permissions, so the whole record, for the teams of the grant | - A grant is given by a **named** global administrator to **another** console user: the shared admin and viewer tokens cannot grant, and an administrator cannot grant themselves. The grantor and the reader both appear in the audit log. Review `content_capture.reader.grant` and `user.create` rows together: whoever holds `users:manage` can create console users and sign in as them, so the audit log, not the grant rule, is what shows a misuse. - A grant covers a list of teams or all teams. For a role scoped to teams it applies only to teams the user already belongs to, so it never takes anyone outside their teams or organization. For `viewer` and `operator` it applies to the teams it names. - A grant does not raise a custom role ceiling: a ceiling is a restriction. - A disabled console user loses access at once; the grant is kept and applies again if the user is enabled again. Revoke the grant when someone no longer needs it. `GET /api/v1/admin/content-access` tells any session what it reads: the ladder above (`ladder`), and for the session its level and permissions for every team (`all_teams`, for a gateway-wide role) and per team (`teams`). It grants nothing. ### Upgrade: reading no longer needs a grant at the top Before this version no role read captured content: everyone needed a `content:read` grant. Now the roles hold content permissions, so on upgrade: - A named **administrator** and an **organization admin** read the whole record of their teams without a grant. If your process relied on administrators not reading content, review who holds those roles before upgrading. - A **team administrator** reads the sent view and the answer of the teams it administers, with reasoning and media. - An **operator** lists the metadata of captured records and reads no content, as before. - Every role that reads the request log lists the metadata of captured records, where the list answered 403 without a grant. - Existing grants keep their meaning: the whole record of their teams. A grant held by a user of a team role for a team they do not belong to no longer applies. - **This applies to records already stored**, not only to new ones: content captured while reading needed a grant becomes readable by these roles on upgrade. Delete or shorten what should not be, before upgrading. - Nothing changes for records, policies or keys. Every read is still audited, now with what was shown. ## Read a capture in the console Open **Logs → Requests** and select a request. The request details show the captured records of that request (what was kept, how many media attachments, whether reasoning was kept apart). When your permissions cover more than metadata there is a **Show captured content** button. Nothing is fetched until you click: the click is the audited read, and the content then appears with *This read was recorded in the audit log. You were shown …* and, when the record holds more than you may read, *Not shown with your permissions: …*. A reader of text gets the conversation and the answer as text, with a mark where media or reasoning was. With metadata only there is no button, and without `content_structure:read` the console never asks for captures. The **Content capture** page (Settings) is for the global administrator: the key status, the policies with their source (YAML or console), **Who reads what** (the table above, as the server computes it), the reader grants and the deletion form. With `content_capture_evaluation` the policy form also has **Purposes**, **Request view** and **Operations**, and the page lists the evaluation capture policies it moved. Saving a policy that captures more than the team's current one asks for a second click. The console names what widens (a team that starts being captured, another side or view of the request, the `evaluation` purpose, another operation, a higher sample rate, a longer retention, a larger `max_bytes`, or a key or model filter removed) and saves only after **Confirm and save**. A narrower policy is saved at once. Every save is a `content_capture.policy.set` row in the audit log either way. ## API All under `/api/v1/admin`, with the console session cookie; writes need `X-CSRF-Token`. | Method and path | Permission | What it does | | --- | --- | --- | | `GET /content-capture` | `content_capture:manage` | Policies (effective, with `source` and the YAML entry they replace), grants, key status (`configured`, `current_ref`, `previous_ref`) and bounds | | `PUT /content-capture/policies/{team}` | `content_capture:manage` | Store the console policy of a team (body: the policy fields) | | `DELETE /content-capture/policies/{team}` | `content_capture:manage` | Remove the console policy | | `PUT /content-capture/readers/{user}` | `content_capture:manage`, named session, not oneself | `{"teams": ["support"]}` or `{"all_teams": true}` | | `DELETE /content-capture/readers/{user}` | `content_capture:manage` | Revoke a grant | | `GET /content-captures?request_id=&team=&limit=` | `content_structure:read` | Metadata of the visible records, newest first, 1 to 200 (default 50), and `levels`: for each record ID, what a reveal would show this session (`received`, `sent`, `text` or `structure`) | | `POST /content-captures/{id}/reveal` | a content permission beyond structure, or a grant | The content the session's permissions cover, audited; 403 with structure alone | | `POST /content-captures/{id}/media/{media_id}` | `content_media:read` | One attachment, audited ([captured images and audio](#captured-images-and-audio-content_capture_media)) | | `GET /content-access` | any console session | The ladder, and what this session reads per team | | `DELETE /content-captures/{id}` | `content_capture:manage` | Delete one record | | `POST /content-captures/delete` | `content_capture:manage` | `{"team": "...", "request_id": "...", "before": "RFC 3339"}`; `team` required | A reveal answers, with `Cache-Control: no-store`: ```json { "capture": {"id": "cc_5f0c...", "request_id": "req-42", "team_id": "support", "operation": "chat", "status": 200, "captured": "both", "stream": false, "request_truncated": false, "response_truncated": false, "output_blocked": false, "occurred_at": "2026-11-08T13:37:30Z", "expires_at": "2026-12-08T13:37:32Z"}, "request": {"content_type": "application/json", "format": "body", "encoding": "utf8", "body": "{\"model\":\"chat-default\",\"messages\":[...]}", "truncated": false}, "response": {"content_type": "application/json", "format": "body", "encoding": "utf8", "body": "{\"id\":\"chatcmpl-...\",\"choices\":[...]}", "truncated": false} } ``` A side the policy did not capture is absent. `encoding` is `base64` when the bytes are not valid UTF-8. With `content_capture_evaluation`, `request` is the received view and a third member, `request_sent`, is the sent view. It has the same fields plus `dialect` (`chat`, `messages`, `responses` or `generate_content`: the API shape of the body, which is `chat` when the gateway translated the request before the guardrails ran). For a native generateContent request in a record that keeps both views it is `same_as_received: true` with an empty `body`: ```json { "capture": {"id": "cc_5f0c...", "request_view": "both", "purposes": ["audit", "evaluation"], "sent_bytes": 118, "sent_truncated": false}, "request": {"format": "body", "encoding": "utf8", "body": "{\"messages\":[{\"role\":\"user\",\"content\":\"Reply to ana@example.com\"}]}", "truncated": false}, "request_sent": {"format": "body", "encoding": "utf8", "dialect": "chat", "body": "{\"messages\":[{\"role\":\"user\",\"content\":\"Reply to [EMAIL]\"}]}", "truncated": false}, "response": {"format": "body", "encoding": "utf8", "body": "{\"choices\":[...]}", "truncated": false} } ``` What a reveal answers depends on the reader. `level` names it and `withheld` lists what the record holds that this reader was not shown: | `level` | Reader holds | Members | | --- | --- | --- | | `received` | `content_received:read` (and the rest) | `request`, `request_sent`, `response`, `reasoning`, `media` | | `sent` | sent view, reasoning and media | `request_sent` (with its body, also when it is the same as the received one), `response`, `reasoning`, `media`; `withheld: ["received"]` | | `text` | the sent view, with one or none of reasoning and media | `input` (the conversation as a list of messages, with `{"type": "withheld", "kind": "media"}` or `"reasoning"` in place of the parts not shown), `output` (the answer's text), `output_truncated`, plus `reasoning` or `media` for the one permission held | ```json { "capture": {"id": "cc_5f0c...", "request_view": "both", "media_count": 1, "reasoning_bytes": 212}, "level": "text", "withheld": ["received", "reasoning", "media"], "input": [{"role": "user", "content": [{"type": "text", "text": "What is in this picture, [EMAIL]?"}, {"type": "withheld", "kind": "media"}]}], "output": "A red square.", "output_truncated": false } ``` `reasoning` has the fields of a side (`format: text`). Each entry of `media` is a reference: `{"id": "cm_...", "source": "request", "kind": "image", "content_type": "image/png", "bytes": 48213, "sha256": "...", "stored": true}`. ## Audit Every action is a row of the control audit (the **Admin audit** tab and `GET /api/v1/admin/audit`), never with content: | Action | Target | Actor | | --- | --- | --- | | `content_capture.read` | `capture: request: team: view:`, for example `view:received+sent+reasoning+media` for an administrator, `view:sent+reasoning+media` for a team administrator and `view:sent` for a reader of text; the same through a reveal and through an evaluation screen | The reader | | `content_capture.media.read` | `capture: media: request: team: view:media` | The reader | | `agent_run_task.read` | `run: team: view:sent`: the task text of an [agent run](/docs/features/agent-recognition/#task-capture), one row per run shown | The reader | | `evaluation.reasoning.read` | `team: view:sent`; the number of results whose judge explanation was shown is in `version` | The reader | | `content_capture.policy.fold` | ` ` (the fold of an evaluation capture policy) | `upgrade` | | `content_capture.reader.grant` / `.revoke` | The user ID | The administrator | | `content_capture.policy.set` / `.delete` | The team | The administrator | | `content_capture.delete` | `capture:`, or `team:` with the request and time filters; the count is in `version` | The administrator | | `content_capture.purge` | `expired`; the count is in `version` | `retention` | The read is written in the same transaction that reads the record and is committed before anything is decrypted: no content leaves without its audit row. A read that then fails to decrypt is still recorded. ## Retention and deletion - A record expires `retention_days` after it is written. From then on it is invisible to every read, and a purge, at startup and then every minute on every replica, deletes expired records in batches of 1,000 (up to 200,000 per minute). It runs whether the flag is on or off, and also during the emergency stop. - Deletion by hand works with the flag off too, so turning capture off never prevents erasing what was stored. - The task text of an [agent run](/docs/features/agent-recognition/#task-capture) expires with the `retention_days` of the policy that allowed it and is removed within a minute of that. Deleting a team's captures (`POST /api/v1/admin/content-captures/delete` with the team, also with `before`) removes the task text of that team's runs too, those that began before `before` when it is sent; a deletion narrowed to one request, or of one capture, does not. An [end-user deletion](/docs/features/data-governance/#end-user-deletion) removes it for the runs whose first request it erases. The run and the keyed hash of its task stay. - Shortening a policy's retention does not shorten records already written; delete them by team and time if needed. - Deleting a team does not delete its records; they expire with their retention, or delete them by team. - Backups of the database keep records until those backups expire. Destroying the content key makes every copy unreadable. ## Limits and risks - **Personal data.** This is the only place where the gateway keeps prompts and answers on purpose. Update your records of processing and inform your users as your law requires. The capture never appears in the request log, logs, traces, [request events](/docs/features/request-events/) or exports; only the reveal endpoint returns it. - **Everyone with the database and the key** can decrypt. Keep the key out of the database host and its backups. - **Write latency.** The record is written after the client has the complete answer, on the request's own goroutine, bounded to 3 seconds; a failure is logged (`content_capture_failed`, without content) and the request is not affected. A failed write loses that record. - **Memory.** A captured request holds up to `max_bytes` per side; before its key is known, up to 1 MiB of request body. - **Model filter.** `models` compares the name the client sent; a [model alias](/docs/features/model-aliases/) of a listed model is not covered unless listed too. - **Key wrap volume.** Each record seals a data key under the content key with a random 96-bit nonce. Rotate the content key well before 4 billion records (at 100 records per second, about a year). - **Consistency across replicas.** A policy change reaches other replicas within 30 seconds. - **The sent view is the request after the gateway's input stage**, not the exact bytes on the provider's wire. It includes a mandatory [system prompt](/docs/features/enforced-system-prompt/), which is added before the guardrails; a [context overflow](/docs/features/prompt-compression/#when-the-prompt-exceeds-the-window-context-overflow) summary and the translation to the provider's own protocol happen after it and are not part of it. A record that keeps `both` views holds two copies of the request: keep only `sent` when an audit of the masked request is enough. - **Evaluation needs text or tool calls.** An answer of tool calls only (not streamed) is judged as one `tool call: name(arguments)` line per call; the tools the request offered are `{{tools}}` ([evaluators](/docs/features/evaluators/#variables)). A streamed answer with no text, or an output a guardrail blocked, is not judged; reasoning is read only for an evaluator with `include_reasoning`. - **Media limits.** Only inline images and audio are stored; images by URL are not fetched, and other file types stay in the body. Media of streamed answers, and of buffered answers larger than `max_bytes` plus 8 MiB, is not captured. A native generateContent request keeps its media inline in the received view as well (within `max_bytes`), because no input stage rewrites it. While a team's media is captured, a request holds its decoded attachments in memory until the record is written (at most `max_items` × `max_item_bytes`), and a buffered answer up to `max_bytes` plus 8 MiB. - **Streamed generateContent answers captured by an earlier version** may hold thought text inside the answer's text; this version keeps the two apart for new records only. - **The media bound of a team is checked when a record is written.** Records that expire free their room at the next purge, within a minute. - **A shared token reads without a name.** Its reads are audited as `bootstrap_admin`. Turn `admin.token_login` off, or keep the shared token for recovery only, when every read must name a person. - **Rules are queued on captured requests only.** A request the policy's sampling left out, or of a team with no capture policy, is neither judged nor reported as skipped. In **Evals → Live**, the rule form warns when the chosen team is not captured for evaluation, or when the team's capture policy keeps fewer models than the rule reads. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `PUT /api/v1/admin/content-capture/policies/{team}` | Stores a team's console capture policy, replacing its YAML entry | | `DELETE /api/v1/admin/content-capture/policies/{team}` | Removes the console policy, so the YAML entry applies again | | `PUT /api/v1/admin/content-capture/readers/{user}` | Grants `content:read` to a console user, for every team or for up to 200 listed teams | | `DELETE /api/v1/admin/content-capture/readers/{user}` | Revokes that grant at once | | `GET /api/v1/admin/content-captures` | Lists the metadata of the captures the caller may see, never their content | | `POST /api/v1/admin/content-captures/{id}/reveal` | Decrypts what the reader's permissions cover of one capture, and audits the read | | `POST /api/v1/admin/content-captures/{id}/media/{media}` | Answers one captured image or audio to a reader with `content_media:read`, and audits the read | | `GET /api/v1/admin/content-access` | The content ladder, and what the session reads per team | | `DELETE /api/v1/admin/content-captures/{id}` | Deletes one capture and audits the deletion; it works with the flag off | ## See also - [Agent runs](/docs/features/agent-recognition/): the typed task of a coding-agent run as captured content - [Data inventory](/docs/security/data-inventory/) - [Cryptography](/docs/security/cryptography/) - [Access control](/docs/features/access-control/) - [Guardrails](/docs/features/guardrails/) # Data governance: legal holds, audit retention, tamper evidence and end-user deletion **Last updated:** 2026-11-25T08:23:14-03:00 (UTC-3) Three controls decide how long the gateway keeps evidence, and what it erases on request: - **Legal holds** (flag `legal_holds`) suspend every destructive retention purge while a hold is in force. - **Audit retention** (flag `audit_retention`) keeps the administrative audit log within a contractual minimum and an optional maximum, and deletes older rows in small, audited batches. - **Audit tamper evidence** (flag `audit_tamper_evidence`) seals every committed audit row into a hash chain and verifies it on demand. - **End-user deletion** (flag `end_user_deletion`) erases what is stored for one declared end user of one team, without touching financial records. All four flags are operator controls, off by default, and require PostgreSQL. They are managed only by the global administrator (`retention:manage`; the audit chain needs `audit:read`). In the console they live on **Settings → Data governance**. **Nothing is deleted by default.** With `audit_retention` off or `retain_days: 0`, every audit row is kept forever. ## Legal holds A legal hold is a named, audited switch: while at least one hold is active, the gateway does not run | Destructive path | While a hold is active | | --- | --- | | Audit retention purge (this page) | Skipped; the state shows `last_skip: legal_hold`, and the purge resumes on the first tick after the last hold is released | | [Metadata retention](/docs/features/metadata-retention/) purge | Skipped; the batch reports `legal_hold` and runs on a later tick once released | | [End-user deletion](#end-user-deletion) | Refused (`409 legal_hold_active`); open jobs pause (`held`) | A hold does **not** stop the short, privacy-driven expiries that each record carries from its own policy: captured content ([content capture](/docs/features/content-capture/)), evaluation captures and persisted client addresses ([source IP controls](/docs/security/source-ip-controls/#persisted-client-addresses)) still expire on schedule. If those records matter to a case, export them first or disable their capture. **Holds are enforced even with the flag off.** Turning `legal_holds` off hides the API and console section, but an active hold keeps blocking the purges. To release a hold, turn the flag back on and release it explicitly. **Placing a hold is safe against a batch already running.** A purge batch holds a shared lock for at most five seconds; placing a hold takes the same lock exclusively and waits for that batch to commit. Every batch that starts after the hold sees it. No batch deletes after the hold is stored. Each hold has a reason (1–500 printable characters, required) and an optional reference (up to 128, such as a case or ticket ID). At most 100 holds can be active at once. Releasing requires its own reason. Released holds stay listed as history; nothing about a hold is ever deleted. ### Through the API | Endpoint | What it does | | --- | --- | | `GET /api/v1/admin/legal-holds` | Active holds first, then recent releases (200 rows), with the `active` count | | `POST /api/v1/admin/legal-holds` | `{reason, reference}` → `201` with the hold (`id` is `lh_` + 32 hex) | | `POST /api/v1/admin/legal-holds/{id}/release` | `{reason}` → `204`; `404` when no active hold has that ID | ```http POST /api/v1/admin/legal-holds X-CSRF-Token: {"reason": "Litigation hold for case 42", "reference": "CASE-42"} ``` ```json {"id": "lh_3f2a…", "reason": "Litigation hold for case 42", "reference": "CASE-42", "placed_by": "user:usr_…", "placed_at": "2026-11-14T04:00:00Z", "released_at": null, "active": true} ``` Audit actions: `legal_hold.place` and `legal_hold.release`, with the hold ID as target and the number of holds still active as the version. ## Audit retention The audit tables are the identity audit (teams, keys, users, organizations, workloads) and the control audit (configuration, providers, policies, retention itself). Audit retention removes rows older than `retain_days`, measured by the PostgreSQL clock. ```yaml features: audit_retention: true audit_retention: revision: 1 # increase it on every YAML change retain_days: 400 # 0 preserves; otherwise minimum_days..maximum_days (or 3650) minimum_days: 365 # contractual floor maximum_days: 730 # contractual ceiling; 0 = none batch_size: 500 # rows per audit table per batch interval: 1h # time between batches ``` | Field | Default | Accepted | | --- | --- | --- | | `revision` | `0` | `0`–`2147483647`; a positive `retain_days` in YAML requires a positive revision, raised on every change | | `retain_days` | `0` (preserve) | `0`, or `minimum_days`..`maximum_days` (`3650` without a ceiling). `0` is refused when `maximum_days` is set | | `minimum_days` | `365` (also when `0`) | `30`–`3650`. Any shorter `retain_days` is refused | | `maximum_days` | `0` (no ceiling) | `0`, or `minimum_days`..`3650`. When set, audit rows cannot be preserved forever | | `batch_size` | `500` (also when `0`) | `1`–`5000` rows per table per batch | | `interval` | `1h` (also when empty) | Go duration, `1m`–`24h` | **The contract only tightens.** The console and API may store an override, but it may never loosen the YAML contract: `minimum_days` cannot go below the YAML value, and a YAML `maximum_days` cannot be raised or removed. If a later YAML revision raises the floor or lowers the ceiling past an existing override, the override is dropped (audited as `audit_retention.override_dropped`) and the YAML policy applies. **How the purge runs.** Every replica runs a worker each minute; PostgreSQL serializes them, so only one batch runs at a time across replicas. A batch: 1. checks the shared flag override (a runtime disable stops it before replicas reload) and the YAML revision (an older replica is fenced, exactly as in metadata retention); 2. waits for the interval since the last batch; 3. stops if a legal hold is active; 4. re-checks the floor and ceiling on the stored policy; 5. deletes at most `batch_size` of the oldest expired rows from each audit table and writes a new `audit_retention.purge` audit row (version = rows deleted) in the same transaction. A full batch schedules the next one at the next worker tick, so a backlog drains at about `batch_size` rows per table per minute instead of one batch per interval. Statements are bounded to five seconds with a 200 ms lock timeout. The first batch runs one interval after the policy is set: there is no "delete now". Before turning it on, export what you must keep beyond the period with the [audit CSV export](/docs/features/analytics-export/) (filters by time range). **In the console:** the **Audit retention** section shows the policy in effect, its source, the contract, the last batch (or "Skipped: legal hold"), the total purged and the newest purged timestamp. **Preview audit purge** counts, without deleting, up to 10,000 eligible rows per table. Saving any positive period asks you to check **I authorize irreversible deletion of administrative audit rows older than the retention period**, unchecked on every edit. ### Through the API | Endpoint | What it does | | --- | --- | | `GET /api/v1/admin/audit-retention` | Base, effective policy, source, version, last batch, `active_legal_holds`; the YAML `revision` in force is `audit_retention.revision` | | `PUT /api/v1/admin/audit-retention` | `{base_fingerprint, version, policy, confirm_delete_expired_audit}` | | `DELETE /api/v1/admin/audit-retention` | Reverts to the YAML (same confirmation when the YAML has a positive period) | | `GET /api/v1/admin/audit-retention/preview` | Bounded counts, cutoff, oldest row, `blocked` by a hold | ```http PUT /api/v1/admin/audit-retention X-CSRF-Token: {"base_fingerprint": "", "version": 3, "policy": {"retain_days": 400, "minimum_days": 400, "maximum_days": 700, "batch_size": 500, "interval": "1h"}, "confirm_delete_expired_audit": true} ``` | Status | Code | Meaning | | --- | --- | --- | | `204` | | Override stored (`audit_retention.set`) | | `400` | `retention_contract` | The policy would loosen the YAML floor or ceiling | | `400` | `invalid_retention` | Out of bounds (for example `retain_days` under `minimum_days`) | | `400` | `confirmation_required` | Positive period without `confirm_delete_expired_audit` | | `409` | `version_conflict` | Someone else changed the policy; reload | | `409` | `retention_base_changed` | Replicas disagree on the YAML revision; publish one higher revision | ## Audit tamper evidence Flag `audit_tamper_evidence` (operator, off by default, PostgreSQL). It makes the administrative audit log **tamper-evident**: every committed row of the identity and control audit tables is sealed into one SHA-256 hash chain, and a verification recomputes the chain and names the first row that was edited, deleted, inserted out of place or reordered. How a row is sealed: ```text row_hash = SHA-256("aigw.audit.row.v1" || every stored field, each length-prefixed: source table, id, occurred_at (microseconds), action, target_id, actor, request_id, version) chain_hash = SHA-256("aigw.audit.chain.v1" || previous chain_hash || seq || row_hash) ``` - **Sealing runs after the write**, in the retention worker (about once a minute, up to 1,000 rows per batch and 20 seconds per tick). Audit writers never wait on a global lock; the chain order is the seal order. A row committed but not sealed yet is reported as **unsealed** (pending), never as verified. - **One sealer at a time** across replicas (advisory lock plus the chain head row), so parallel writers never produce a gap or a duplicate position, and a rolled-back write never takes one. - **The first seal is the genesis**: turning the flag on seals the existing history first (oldest first), then new rows as they arrive. Turning it off stops sealing; rows written meanwhile are sealed when it is turned on again. - **Every seal logs the new head** as `audit_chain_sealed` (`head_seq`, `head_hash`), and every purge checkpoint as `audit_chain_checkpoint`. Those log lines, collected outside the database, are your external copy. **The seals carry no secret key**: someone with write access to the database can compute valid seals, so they could rebuild the whole chain, or delete history and append a correctly sealed checkpoint row for a new anchor. Only values kept elsewhere reveal that: check the newest logged head with `--expect :` and the newest logged checkpoint with `--expect-anchor :` (a forged anchor never appears in your logs). Keep these log lines for at least as long as the audit retention period. - **A row forged before it is sealed is sealed as genuine**: nothing ties `occurred_at` to the time of sealing. The chain proves that sealed rows were not changed afterwards, not that every row was written by the gateway. ### Retention and checkpoints Audit retention removes sealed rows only as a **prefix of the chain**: in each batch it takes the oldest sealed positions after the current anchor, stops at the first row newer than the cutoff, **verifies** that prefix (and the first row it keeps), deletes it and records a `purge` checkpoint (`through_seq`, `chain_hash`, `purged`) that becomes the new anchor. The same batch appends the checkpoint to the chain as a sealed `audit_chain.checkpoint` control audit row (target `:`), so the remaining chain itself attests its anchor: moving the anchor or re-inserting history below it with plain SQL is reported as `anchor_unattested` or `below_anchor`; a forger who also seals a checkpoint row is caught by `--expect-anchor`. The batch logs it as `audit_chain_checkpoint` with the new head. Sealed rows count against `batch_size`: no table loses more than `batch_size` rows in one batch. - A prefix that does not verify is **never purged**: the batch reports `chain_broken` (shown on the audit retention card and logged once as `audit_retention_chain_broken`) and keeps the rows that prove the tampering. The whole audit purge stops, so rows may outlive `maximum_days` until it is resolved. To resolve it, run a verification, investigate the reported position and restore that row from a backup; the purge resumes on the next tick once the chain verifies. There is deliberately no command that re-anchors a broken chain. - An old row sealed after a younger one (a late commit) waits until the younger one expires too, so it can outlive the cutoff by the gap between them. - Rows that were never sealed keep the previous purge behavior (oldest first). - Once a chain exists, purges keep it consistent even with `audit_tamper_evidence` off. ### Verifying In the console, **Settings → Data governance → Audit tamper evidence** shows the stored result of the last verification (*Verified*, *Tampering detected* with the position and kind, or *Not verified yet*), the sealed and unsealed counts, the anchor and the head hash. **Verify now** runs a full verification. | Endpoint | What it does | | --- | --- | | `GET /api/v1/admin/audit-chain` | Head (`head_seq`, `head_hash`), anchor, `unsealed`, last verification and the 20 newest checkpoints. Reads never seal or verify | | `POST /api/v1/admin/audit-chain/verify` | Recomputes every seal after the anchor in one snapshot (60 s budget), stores the result and writes `audit_chain.verify` or `audit_chain.tampered`. Optional body `{"expect": {"seq": 42, "hash": "<64 hex>"}}` also checks a pair kept outside the database; the report then carries `expected.result`: `match`, `mismatch` or `purged` (below the anchor, no longer checkable). `{"expect_anchor": {"seq": 120, "hash": "<64 hex>"}}` requires the current anchor to equal a logged checkpoint (`expected_anchor.result`). A failure that only concerns these caller-supplied values is audited as `audit_chain.expect_mismatch` and does not change the stored indicator | Both need a global administrator with `audit:read`; the verification is a write and needs the CSRF token. A tampered chain is a `200` with `status: "tampered"`: ```json {"status": "tampered", "verified_rows": 6, "head_seq": 42, "head_hash": "ab12…", "anchor_seq": 0, "anchor_hash": "0000…", "unsealed": 3, "failure": {"kind": "altered", "seq": 7, "source": "control", "row_id": 19, "detail": "the row content or its position no longer matches its seal"}, "verified_at": "2026-11-14T08:05:00Z"} ``` | `failure.kind` | Meaning | | --- | --- | | `altered` | The row at `seq` no longer matches its seal: edited content or timestamp, a forged seal, swapped or renumbered positions | | `missing` | No row at `seq`: deleted, also at the end of the chain | | `duplicate` | Two rows carry the same position | | `beyond_head` | A sealed row is newer than the recorded head | | `head_mismatch` | The recorded head differs from the recomputed chain | | `head_missing` | Sealed rows exist but the chain head is gone | | `anchor_mismatch` | The anchor differs from the newest recorded checkpoint | | `anchor_unattested` | No sealed `audit_chain.checkpoint` row names the current anchor: history below it was removed outside a purge | | `below_anchor` | A sealed row sits at or below the anchor, where every row was purged | | `expected_mismatch` | The externally kept hash differs from the chain at that position | | `expected_beyond_head` | The externally kept position is newer than the head: the chain was truncated or rebuilt (also when you verify a backup taken before that pair was logged) | | `anchor_unexpected` | The current anchor is not the checkpoint passed in `expect_anchor` / `--expect-anchor` | For a chain too long for the 60-second request, or against a replica or a restored backup, run the read-only command with the same configuration and database URL as the server: ```sh gateway audit-verify gateway audit-verify --expect 1842:9f2c…e1 --expect-anchor 1200:4b7a…09 # pairs from your logs ``` It prints the same report as one JSON line and never migrates, seals or records anything. It works whatever the flag says, without the pool's statement timeout (one hour at most). Exit status: `0` verified (or nothing sealed yet), `3` tampered or the expected pair does not match, `1` could not verify (for example a schema behind the binary), `2` usage. ## End-user deletion Flag `end_user_deletion` (operator, off by default, PostgreSQL). It erases what the gateway stored for one **declared end user of one team**: the value a client sent in `X-Gateway-End-User` or the OpenAI `user` field, recorded with [`end_user_tracking`](/docs/features/observability/). The value is untrusted client metadata, so the gateway cannot prove who the person is: the administrator who runs the deletion is responsible for matching the request to the right team and value. **Scope is exact.** The team is the exact team ID and the end user is the exact recorded value (case-sensitive, 1–128 printable characters). The same value in another team is a different person and is never touched. | Stored data | Outcome | | --- | --- | | Request-log rows (usage events) of the team with that end user | **Attribution cleared** (`end_user` set to empty); tokens, status, timings, cost proof and fingerprints stay, so totals, analytics, budgets and invoices do not change | | Finalized durable receipts | **Attribution cleared**, once finalized for 15 minutes (a retried finalization still has to match). Receipts never finalized wait, and the job shows `waiting_receipts`, until they are finalized or abandoned: no lease or update for 24 hours | | Captured prompts and answers ([content capture](/docs/features/content-capture/)) of those requests | **Deleted** | | Evaluation captures of those requests | **Deleted** | | The task text of [agent runs](/docs/features/agent-recognition/#task-capture) whose first request is one of those requests | **Deleted**; the run, its counters and the keyed hash of the task stay | | Evaluation scores and review comments attached to those requests (judge rationales and notes can quote content) | **Deleted**. A live evaluation already running for one of those requests can still write its score after the final sweep; evaluation queue items and jobs keep only the request ID | | Persisted client addresses ([source IP controls](/docs/security/source-ip-controls/#persisted-client-addresses)) of those requests | **Deleted** | | Budget counters, reservations, the ledger archive and budget alerts keyed `team/end user` (`end_user_budgets`) | **Kept**: they are financial evidence and follow their own windows and [ledger archiving](/docs/features/quota-finance/#archiving-the-ledger). The dry run counts the counters and alerts | | Valuations, rollups, audit | Unchanged (they never held the value) | A request ID can be sent by the client and reused. A capture is only deleted when no **other** declared end user of the same team used the same request ID. **What the deletion cannot reach:** copies outside the gateway database (structured logs or OTLP exports you collect, request-event destinations, backups) and short-lived rate-limit windows. Usage fingerprints are SHA-256 hashes over the whole original event, kept as financial proof; they do not contain the value in readable form. ### How it runs 1. **Dry run** (`dry_run: true`): counts what would change, and whether a legal hold blocks it. Nothing is written. 2. **Request** (`confirm: true`): creates a durable job with the database time as its cutoff (later requests are out of scope) and audits `end_user.delete.request`. Repeating the request while the job is open returns the same job; after it completes, a new request creates a new job that finds nothing. 3. **Batches**: each batch is one transaction over at most 500 request-log rows (and their captures, annotations and addresses) plus 500 receipts. A failing batch rolls back completely and is retried; the job shows that the last batch failed. The request runs batches inline for up to 5 seconds, and every replica's worker resumes open jobs each minute — also if the flag is later turned off, because an accepted erasure is finished. 4. **Settling**: a request already running at the cutoff writes its usage row when it ends. Once everything found is erased, the job shows `settling` and sweeps once more after the longest request the configuration allows: the longest stream `max_duration` (network default or any model override) or Realtime `max_session`, plus one minute, and never less than 15 minutes (with the defaults, 31 minutes after the cutoff). With `durable_usage` on, a request in flight also holds the job in `waiting_receipts` until its receipt is finalized. 5. **Completion**: the job clears the stored end-user value (and its digest), records the counts and audits `end_user.delete.complete` with the total. Audit rows name the job ID, never the value. The dry run is audited too (`end_user.delete.dry_run`, with the team and the matching count only). An active [legal hold](#legal-holds) refuses new requests (`409 legal_hold_active`) and pauses open jobs (`held`) until it is released. **In the console:** **Settings → Data governance → End-user deletion** asks for the team ID and the end user, shows the dry-run counts and requires checking **I authorize irreversible erasure of this end user's stored data** before **Delete end-user data**. The job list shows state and counts, never the value. ### Through the API | Endpoint | What it does | | --- | --- | | `POST /api/v1/admin/end-user-deletions` | `{team, end_user, dry_run}` or `{team, end_user, confirm: true}` | | `GET /api/v1/admin/end-user-deletions` | The 100 most recent jobs | | `GET /api/v1/admin/end-user-deletions/{id}` | One job | ```http POST /api/v1/admin/end-user-deletions X-CSRF-Token: {"team": "support", "end_user": "customer-8841", "dry_run": true} ``` ```json {"dry_run": true, "team": "support", "blocked_by_legal_hold": false, "counts": {"usage_events": 42, "durable_receipts": 42, "content_captures": 5, "eval_captures": 0, "eval_annotations": 0, "client_sources": 12, "retained_quota_counters": 2, "retained_budget_alerts": 1}} ``` ```http POST /api/v1/admin/end-user-deletions {"team": "support", "end_user": "customer-8841", "confirm": true} ``` ```json {"id": "eud_9c1f…", "team": "support", "state": "settling", "requested_by": "user:usr_…", "cutoff": "2026-11-14T04:10:00Z", "completed_at": null, "counts": {"usage_events": 42, "durable_receipts": 42, "content_captures": 5, "eval_captures": 0, "eval_annotations": 0, "client_sources": 12, "retained_quota_counters": 0, "retained_budget_alerts": 0}, "deferred_receipts": 0, "attempts": 2} ``` | Status | Code | Meaning | | --- | --- | --- | | `201` | | New job (`200` returns the job already open for the same team and end user) | | `400` | `invalid_team`, `invalid_end_user` | Not an exact team ID or recorded value | | `400` | `confirmation_required` | Neither `dry_run` nor `confirm: true` | | `409` | `legal_hold_active` | A legal hold is in force | ## Provider error redaction The page also shows, read-only, which JSON key names have their string values redacted before a provider's error answer reaches a client: `security.provider_errors.credential_field_names`, the effective list after normalization (lowercase letters and digits), and whether it is the default or set in the YAML. An empty list reads as off. Changing it takes a restart. What the redaction does and does not cover is in [Security](/docs/security/security/) ("Provider errors never relay a credential-named field or a URL signature"). ```yaml security: provider_errors: credential_field_names: [password, secret, apikey, connectionstring, x_vendor_token] ``` ## What is never removed - The money path: usage events, receipts, valuations and the budgets ledger are outside audit retention ([metadata retention](/docs/features/metadata-retention/) and [financial reconciliation](/docs/features/quota-finance/) own them). - Legal holds themselves and their history. - Audit rows newer than the cutoff, including the purge's own `audit_retention.purge` row. ## Upgrade Migration 132 adds `gateway_audit_retention`, `gateway_legal_holds` and an age index on each audit table; migration 133 adds `gateway_end_user_deletions` and an end-user index on durable receipts; migration 144 adds the `chain_seq`/`chain_hash` columns and their indexes to both audit tables, `gateway_audit_chain` and `gateway_audit_chain_checkpoints` (the new columns are nullable and their check is added `NOT VALID`, so existing rows are not rewritten or scanned for it; the four indexes are built in the migration transaction, which blocks writes to the audit tables, and so every audited change, while they build: plan the upgrade for a large audit log). Run them with this release and upgrade every replica before turning any of the flags on: an older replica does not know about holds and would keep running metadata retention while a hold is active, and it does not resume end-user deletion jobs. An older replica also purges audit rows without verifying or checkpointing the chain, which a later verification reports as `missing`: upgrade every replica before turning `audit_tamper_evidence` on. ## Limits - Tamper evidence detects changes; it does not prevent them. The seals are not keyed (no secret outside the database), so a writer with database access who recomputes seals is caught only against the logged head and checkpoint pairs (`--expect`, `--expect-anchor`). Rows are covered once sealed, about a minute after they are written. - The chain covers the two administrative audit tables only, not usage events, receipts or request logs. - Backups are outside the gateway: a hold does not reach copies you keep elsewhere, and purged rows survive in backups until those expire. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `GET /api/v1/admin/audit/export` | Exports up to 10,000 administrative changes as CSV, with the same filters as the audit explorer | | `GET /api/v1/admin/end-user-deletions/{id}` | The state and counts of one end-user deletion job | | `PUT /api/v1/admin/audit-retention` | Stores a console override of the audit retention that may only tighten the YAML bounds | # Guardrails **Last updated:** 2026-11-08T04:58:34-03:00 (UTC-3) A prompt with a customer's CPF, an API key pasted by mistake or a toxic response should not go out, or come back, unchecked. Guardrails inspect text before it goes to the provider and, if you want, the response before it goes back to the app. They mask what is sensitive or block the request. ## What is available | Feature | What it does | Flag | Learn more | |---|---|---|---| | **Local detectors** | Email, CPF, CNPJ, card (with Luhn), phone, IPv4, API keys and your own RE2 patterns, with no external call | `guardrails` | [Guardrails](/docs/features/guardrails/) | | **Mask or block** | `mask` replaces the match with a placeholder; `block` refuses the request | `guardrails` | [Guardrails](/docs/features/guardrails/) | | **Input and output** | On input for Chat, Messages, Responses and Conversations; on output for non-stream answers, where a blocked answer becomes a refusal in the route's own shape | `guardrails` | [Guardrails](/docs/features/guardrails/) | | **Per-team policies** | Sets of guardrails applied per team or model, with ready-made templates | `guardrail_policies` | [Guardrails](/docs/features/guardrails/) | | **Simulator** | Tests a policy against a text before you turn it on | `guardrail_management` | [Guardrails](/docs/features/guardrails/) | | **Integrations** | Azure AI Content Safety, Presidio, Lakera Guard, Bedrock Guardrails, model-based moderation and any service that speaks the generic guardrail API, on the request, the answer or both | `guardrails` | [Guardrails](/docs/features/guardrails/) | | **Catalog with metrics** | Precision and recall of each detector, measured against datasets | `guardrail_management` | [Guardrails](/docs/features/guardrails/) | | **Compliance** | Runs the guardrail stack against a dataset with the expected result and shows where it fails | `guardrail_compliance` | [Guardrails](/docs/features/guardrails/) | ## Limits - The output of **streams** does not go through the guardrails. While an external service checks an alias's answers, its streamed requests are refused instead of passing unchecked. - The evaluated text never goes to logs or telemetry; only the counts of findings do. # Guardrails **Last updated:** 2026-11-26T03:21:52-03:00 (UTC-3) Guardrails inspect text before it goes to the provider and, if you want, the answer before it goes back to the app. They **mask** what is sensitive (a CPF becomes a placeholder) or **block** the request (an API key pasted by mistake). Detection can be local, with no external call, or delegated to services such as Azure AI Content Safety, Presidio, Lakera, Bedrock Guardrails or a moderation model. | Flag | What it turns on | | --- | --- | | `guardrails` | Guardrails on input and output | | `guardrail_management` | Editing in the console, the simulator and the catalog with metrics | | `guardrail_policies` | Policies per team, key or model | | `guardrail_compliance` | Compliance testing in the Playground | | `guardrail_streaming` | Output guardrails inspect streamed answers in bounded windows (needs `guardrails` and `stream_usage`) | | `judge_guardrails` | Provider type `judge`: one of your evaluators decides, at input or output ([judge guardrails](/docs/features/judge-guardrails/)) | ## How to turn it on Available local detectors: `email`, `cpf`, `cnpj`, `credit_card` (with Luhn), `phone`, `ipv4`, `secret_key`, `private_key` and `prompt_injection`, plus your own patterns in `patterns` (RE2). ```yaml features: guardrails: true guardrail_management: true guardrails: - id: pii-mask name: PII mask mode: mask # mask | block | monitor detectors: [email, cpf, cnpj, credit_card, phone, ipv4, secret_key] - id: injection name: Prompt injection mode: block detectors: [prompt_injection, private_key] patterns: - {name: ticket, regex: 'TCK-\d{6}'} models: [] # empty = all aliases - id: secrets name: Block secrets mode: block detectors: [secret_key] ``` | Key | Default | What it does | | --- | --- | --- | | `guardrails[].id` | required | Unique identifier, used by policies, the request header and the response counts | | `guardrails[].name` | required | Display name | | `guardrails[].mode` | required | `mask` replaces findings, `block` refuses the request, `monitor` only reports what it would do | | `guardrails[].detectors` | `[]` | Built-in local detectors to run, from the list above | | `guardrails[].patterns` | `[]` | Your own detectors: each has a `name` and a `regex` | | `guardrails[].patterns[].regex` | required | An RE2 expression (linear time, no backtracking), so a pattern cannot slow a request down | | `guardrails[].models` | `[]` | Aliases the guardrail applies to; empty means every alias | | `guardrails[].stages` | `[input]` | `input` (request text) and/or `output` (the answer) | | `guardrails[].disabled` | `false` | Keeps the guardrail declared without running it | - **Coverage:** text in Chat Completions, Anthropic Messages, OpenAI Responses and Conversations. - **Order:** as declared. A `block` with a finding ends the request with `400 guardrail_blocked`, before the provider is called. - **Models:** `models` limits the guardrail to certain aliases; empty applies to all. - **Privacy:** the response and the logs carry only counts (`X-Gateway-Guardrails: pii-mask=2`), never the text that was found. - **Console:** **Guardrails**, with detectors, `name=regex` patterns, models and **Simulate** (nothing is sent, saved or recorded). - **API:** `GET /api/v1/admin/guardrails` (with the boot `guardrail_streaming` settings under that key), `PUT|DELETE /api/v1/admin/guardrails/{id}`, `POST /api/v1/admin/guardrails/simulate`. ## Monitor mode (try a guardrail before enforcing it) `mode: monitor` runs a guardrail on real traffic without acting on it. It evaluates the request text and, with the output stage, the non-streaming answer exactly as its `monitor_action` would, but the provider receives the request as the client sent it and the client receives the answer as the provider generated it. What it would have done is recorded, so you can measure false positives and coverage before switching the guardrail to enforcement. ```yaml guardrails: - id: pii-watch name: PII (watch) mode: monitor monitor_action: mask # block (default) | mask: what it would do sample_percent: 25 # 0-100, default 100 detectors: [email, cpf, phone] stages: [input, output] - id: moderation-watch name: Moderation (watch) mode: monitor # a provider monitor would block sample_percent: 10 stages: [input, output] provider: {type: moderation, model: safety-moderation} ``` | Field | Default | Contract | | --- | --- | --- | | `mode: monitor` | — | Evaluate and record; never rewrite, block, refuse or add a client header | | `monitor_action` | `block` | `block` or `mask`: the outcome recorded for a finding (`would_block` or `would_mask`). A provider guardrail only blocks, so it accepts only `block`. Only with `mode: monitor` | | `sample_percent` | `100` | Integer 0–100: the share of requests evaluated at each stage, drawn independently for the input and the output of each request with `crypto/rand`, so a client cannot predict or steer which requests are evaluated. `0` evaluates nothing (no provider call). Only with `mode: monitor`: an enforcing guardrail always runs, since sampling a block would make the policy optional | What is recorded for each evaluated stage, never with the matched text: - the [request event](/docs/features/request-events/) (`logging.request_events`) gets a `guardrails[]` entry with `outcome` `would_block` or `would_mask` and the finding count, or `passed`; `error_allowed` when a provider monitor's service failed (whatever `on_error` says) or the answer could not be parsed; `incomplete` when an enforcing guardrail stopped the request or the answer before the monitor saw it. A request that was not sampled has no entry for that guardrail; - `gateway_guardrail_findings_total{guardrail,outcome="would_block"|"would_mask"}` counts the findings ([observability](/docs/features/observability/#metrics-prometheus)); - an Info log line `guardrail_monitor` with the request ID, guardrail ID, stage, outcome and finding count. What stays exactly as without the monitor: - the request and the answer, their status, body and headers: `X-Gateway-Guardrails` and `X-Gateway-Guardrails-Output` count only enforcing guardrails, and no alert fires; - streams: a monitor never refuses a stream, a background response or a conversation the way a provider guardrail on the output stage does; without `guardrail_streaming`, streamed answers are not evaluated at output (with it, a monitor evaluates the whole stream, see [inspecting streamed answers](#inspecting-streamed-answers)); - an answer the monitor cannot inspect (not JSON, above 8 MiB): it goes out unchanged and the monitor records `error_allowed`; - the [semantic cache](/docs/features/semantic-cache/): monitors are not part of its key, so adding one keeps the cached answers, and a cached answer is served without evaluation; - an enforcing guardrail next to a monitor keeps enforcing; guardrails run in declared order, so a monitor after a `mask` sees the masked text, as the real one would. - the request checks that only enforcing input guardrails need (the refusal of a body that repeats a member name) and the way the answer is relayed: with monitors alone on the output stage, the answer streams to the client as it arrives, live evaluation capture and the semantic cache see it as usual, and the monitors evaluate a copy afterwards. The cost is the evaluation itself: local detectors take microseconds, but a provider monitor makes the same call to its service as an enforcing one, synchronously: on a sampled request the input check delays the provider call, and the output check runs after the answer is sent but before the response ends, so the client sees the end of the body that much later (up to the service's timeout when it hangs). The service's price applies too; `sample_percent` bounds both. Policies (`default_on`, `guardrail_policies`) and `models` select monitors like any guardrail. The **Simulate** button reports *Monitor: would block* or *would mask* and returns the sample unchanged, and the Playground compliance test lists `would_block`/`would_mask` without letting a monitor decide the verdict. A `refusal` is kept on a monitor that would block, unused, so turning it into an enforcing guardrail is one change: `mode: block` (or `mode: mask`). The released parameter catalogs (V10, V11) still list `mask` and `block` for `guardrails[].mode`; the gateway and the console accept `monitor` beyond them. Tested on 2026-11-08 with the native binary, PostgreSQL 16.15 and the real OpenAI moderation endpoint (`omni-moderation-latest`) behind a monitor on both stages, with a local stand-in for the chat model: a threatening prompt got its normal answer (200, unchanged, no `X-Gateway-Guardrails` header) and its request event recorded input `would_block` (1 finding) and output `passed`; a benign prompt whose answer was the threat got that answer unchanged and recorded input `passed` and output `would_block`. `gateway_guardrail_findings_total{guardrail="moderation-watch",outcome="would_block"}` read 2, two `guardrail_monitor` lines were logged at Info, and neither the texts nor the key appeared in the output. ## Policies per team, key or model With `guardrail_policies`, a policy groups guardrails and is attached to teams, keys or models (`*` for all), with inheritance and removal; a guardrail with `default_on: false` runs only where a policy adds it. Ready-made templates (LGPD, injection and secrets, content safety, regulated) and a simulator are on the **Policies** tab. ```yaml features: guardrail_policies: true guardrail_policies: - id: regulated name: Regulated teams guardrails: [pii-mask, injection] teams: [payments, support] - id: payments-batch name: Batch key without masking inherit: regulated remove: [pii-mask] keys: [batch-key] ``` | Key | Default | What it does | | --- | --- | --- | | `guardrail_policies[].id` | required | Unique lower-case identifier, up to 64 characters (at most 100 policies) | | `guardrail_policies[].name` | required | Display name, 1–80 characters | | `guardrail_policies[].description` | empty | Up to 500 characters, shown on the **Policies** tab | | `guardrail_policies[].inherit` | empty | Another policy whose guardrails this one starts from; chains go at most 5 deep and never loop | | `guardrail_policies[].guardrails` | `[]` | Up to 50 existing guardrail IDs the policy adds | | `guardrail_policies[].remove` | `[]` | Up to 50 guardrail IDs taken out of what the policy inherits | | `guardrail_policies[].teams` | `[]` | Up to 100 team IDs the policy applies to, or `*` | | `guardrail_policies[].keys` | `[]` | Up to 100 key IDs the policy applies to, or `*` | | `guardrail_policies[].models` | `[]` | Up to 100 model aliases the policy applies to, or `*` | ## Guardrails a request adds With the operator flag `request_guardrails` (off by default, requires `guardrails`), a client adds guardrails to one Chat Completions, Messages or Responses request with a header: ```http X-Gateway-Add-Guardrails: pii-opt-in,injection-block ``` - 1 to 8 distinct guardrail IDs, comma separated, in one header (up to 600 characters). - Each one must exist, apply to the request's alias (its `models`, or all) and list the key's team, or `*`, in `selectable_teams`. Otherwise the request is refused with `403 guardrail_not_selectable` before any guardrail or provider call; a malformed header is `400 invalid_request_guardrails`. A key without a team can add none. - The header only adds checks. The guardrails that already apply (default on, or through a policy) keep running, and run first: an added guardrail sees the text after them, so an added mask can never hide text from a configured block. Nothing can be removed or relaxed per request. An added guardrail runs at its own stages, input and output, streams included, as configured. - A [semantic fallback](/docs/features/routing-strategies/#semantic-fallbacks) or a customer allowance fallback carries the header to its destination, which admits the guardrails again for its own alias: one that does not apply there refuses the fallback. - With the flag off, the header is refused with `400 request_guardrails_disabled`, never ignored, so a client never believes a check ran when it did not. - Other routes do not read the header. `selectable_teams` is set per guardrail in YAML, in the API (`PUT /api/v1/admin/guardrails/{id}`) and in the console (**Selectable by teams**, shown while the flag is on): ```yaml features: request_guardrails: true guardrails: - id: pii-opt-in name: PII mask on demand mode: mask detectors: [email, cpf] default_on: false # runs only where a policy or a request adds it selectable_teams: [team-a, team-b] # or ["*"] for any team ``` Up to 64 entries, each a team ID or `*`, without repetition. Empty or absent means no key may add the guardrail. A guardrail with `default_on: false` is the usual choice: it runs only for the requests that ask for it. The Playground lists the selectable guardrails of the console session's teams under **Request options** (`playground_request_options`). ## Catalog with metrics In **Guardrails › Catalog**, each built-in detector appears with precision, recall and F1 measured against 55 labeled cases, and each configured guardrail, including provider ones, can be evaluated with **Evaluate**; the round is saved. `prompt_injection` and `private_key` are built-in detectors. API: `GET /api/v1/admin/guardrails/catalog`, `GET …/datasets`, `POST /api/v1/admin/guardrails/{id}/evaluate`. ## Compliance testing With `guardrail_compliance`, the Playground has a **Compliance** tab that runs the configured guardrails (including provider ones) against datasets with an expected result and counts false positives and false negatives. The API is `POST /api/v1/admin/guardrails/test`. ## Inspecting the answer (output stage) `stages` says where a guardrail runs: `[input]` (the default) checks the request, `[output]` checks the answer, `[input, output]` checks both. The Gemini Interactions API is covered on both stages too, with its own rules for stored and streamed answers; see [file inputs](/docs/features/file-inputs/#guardrails). The output stage covers the non-streaming answers of Chat Completions, Anthropic Messages and Responses, whether the alias serves the route natively or through translation, and their streamed answers with `guardrail_streaming` (see [Inspecting streamed answers](#inspecting-streamed-answers)). The gateway reads the whole answer (up to 8 MiB), records its usage, and only then decides what the app receives. - **`mask`** rewrites the answer text, as on input, unless the original would stay readable (see [Held rewrites](#held-rewrites)). - **`block` with a refusal** replaces the answer with the refusal, in the route's own shape. The client gets `200`, the provider's `usage`, and the same finish signal the provider would send for a content filter, so SDKs need no new error handling: | Route | Refused answer | | --- | --- | | Chat Completions | `choices[].message.content` is the refusal, `finish_reason: content_filter` | | Anthropic Messages | one `text` block with the refusal, `stop_reason: refusal` | | Responses | one `message` item with the refusal, `status: incomplete`, `incomplete_details.reason: content_filter`, and a new `id` | | GenerateContent (translated) | one candidate with the refusal, `finishReason: SAFETY` | - **`block` without a refusal** (local detectors only) keeps the earlier answer: `502 guardrail_blocked_output`. - **Counts** come out in `X-Gateway-Guardrails-Output` (`mod-out=1`), never the text. Only the envelope of the provider's answer survives a refusal: `id`, `model`, `created`, `usage` and similar fields. Anything that could carry generated text (other choices, tool calls, reasoning, citations) is dropped. A refused Responses answer gets a fresh, unsigned `id`. The provider's stored response can then be neither fetched through `GET /v1/responses/{id}` nor continued with `previous_response_id`. ```yaml guardrails: - id: answer-moderation name: Answer moderation mode: block stages: [output] # or [input, output] refusal: "I can't share that answer." # optional provider: {type: moderation, model: mod, on_error: block} ``` ### Held rewrites A rewritten answer must not keep the original elsewhere. Every rewrite of a non-streamed answer follows one rule: a local `mask`, an applied generic redaction (`apply_redactions`) and an extension `redact` verdict (which on output never rewrites and always withholds). When the original would stay readable, the answer is **held** instead of rewritten, as a block labelled `redaction_not_applicable`: | Where the original stays | When | | --- | --- | | Token `logprobs` | A Chat Completions choice (or a legacy completion) whose `logprobs` carry tokens, or a Responses `output_text` part with non-empty `logprobs`: they spell the generated tokens out again. Empty shapes (`{"content": null}`, `{"content": []}`) do not count | | A text the mask does not rewrite | A local mask rewrites only the visible text. When one of the local guardrails still finds something in the masked answer's other generated text (reasoning, an audio transcript, tool-call arguments, a block read whole), the answer is held | | The provider's stored answer | A Responses answer that is stored: its `store` is not `false`, or the provider left `store` out and the request did not send `store: false`. The stored original is readable through `GET /v1/responses/{id}` and is continued with `previous_response_id`. `store: null` counts as stored, and so does an answer that names a `conversation` | A Chat Completions alias on an openai target sends `store: false` whenever an enforcing output guardrail covers the alias and the client or the target's request policy set `store` (an absent `store` stays absent). On a Responses-API target (`api: responses`, or `auto` when it picks Responses) the chat answer carries the provider's raw `resp_` id, and a stored original could be read or continued through it; on Chat Completions OpenAI would keep a stored completion of the original. The override is not reported in a header. Without such a guardrail (monitors only, or none) the client's `store` goes through. A held answer is answered like a block: a provider guardrail with its refusal (`200`), a local mask with `502 guardrail_blocked_output` (a mask has no refusal). The finding still counts in `X-Gateway-Guardrails-Output` and the request event shows the guardrail as `blocked`. Messages answers carry neither, so they are always rewritten. To keep masking instead of holding, send `logprobs: false` and, on Responses, `store: false`. Answers with no finding are never held. Every guardrail whose mask fired is counted `blocked` in the metrics when the answer is held. A Responses request with `background: true` or a `conversation` is refused before dispatch (`400 guardrail_output_unsupported`) when any enforcing output guardrail covers the alias, local ones included: the answer is read later, outside the guardrails. ### `refusal` | Field | Default | Bounds | | --- | --- | --- | | `refusal` | empty. A provider guardrail then answers `This answer was withheld by a content policy.`; a local one answers `502` | 1 to 500 characters, no surrounding spaces; line breaks allowed, but no other control, line-separator or bidirectional-override characters, which could disguise the text in a log or a chat window. Only with `mode: block` and the `output` stage. | Provider guardrails always answer with a refusal, because the answer was generated and paid for: a `200` with the provider's usage lets the reservation settle and the cost be valued from that usage. A local guardrail keeps its `502` unless you set a refusal, so existing configurations behave as before. The console shows the field as **Refusal (replaces a blocked answer)** once the guardrail is `block` and **Answer (output)** is checked. ### Usage, logs and audit - **Billing:** the provider's usage is read from its own answer before the check. A refused answer is recorded as a `200` with those tokens, so budgets, TPM and cost see what the provider charged. A `502` or `503` withholding still records the tokens, but, like any failed request, its cost stays unknown and its reservation stays held until reconciliation. - **Log:** one `guardrail_blocked_output` line with `request_id`, `guardrail_id`, `stage: output`, the `categories` the service named (for example `violence`) and `action` (`refusal` or `error`). The answer itself is never logged. - **Alert event:** `guardrail_blocked` with `model`, `stage: output` and `categories`, for channels subscribed to that event. - **Metrics:** `gateway_guardrail_findings_total{guardrail,outcome="blocked"}`. ### Streams, background responses and conversations Without the `guardrail_streaming` flag the gateway does not inspect a stream. While a **provider** guardrail checks the answers of an alias, a request whose answer would escape the check is refused before anything is sent or billed, with `400 guardrail_output_unsupported`: - `stream: true` on Chat Completions, Messages, Responses or GenerateContent (with `guardrail_streaming` on, see [Inspecting streamed answers](#inspecting-streamed-answers)); - a Responses request with `background: true`, whose answer is fetched later; - a Responses request with a `conversation`, whose answer is stored where its items can be listed; - any GenerateContent call (`:generateContent` or `:streamGenerateContent`) on an alias served natively by Gemini, which the gateway relays without inspection. Such an alias cannot be used on `/v1beta` while a provider guardrail covers its answers; an alias that reaches another provider through translation is inspected; - a `/v1/realtime` session. Without this refusal, any client could skip the moderation by setting one field. To let an alias stream without inspection, scope the guardrail to other aliases with `models`. Without the flag, local output guardrails keep their earlier behavior: streams go through without inspection. ### Inspecting streamed answers With `features.guardrail_streaming: true` (it needs `guardrails` and `stream_usage`), the output guardrails inspect streamed answers instead of refusing them. This covers: | Stream | Inspected as | | --- | --- | | Chat Completions, native or translated to any provider | OpenAI chat chunks | | Anthropic Messages, native | Messages events | | Anthropic Messages, Responses and GenerateContent translated through the chat format | OpenAI chat chunks, before the gateway turns them into the client's dialect | | Responses, native | Responses events; the request needs `store: false`, read on the body every target of the alias would be sent after its request policy, before any guardrail call, reservation or send (a target whose policy sets `store: true` refuses the stream with `400 guardrail_output_unsupported`, whatever the order the targets are tried in; a policy `store: false` satisfies it) | | GenerateContent on an alias served natively by Gemini, `/v1/realtime` | not inspected: still refused while a provider output guardrail covers the alias | How a stream is held: 1. The gateway reads the provider's stream into complete SSE events. A character or an event split across network reads is put back together before anything is decided. 2. It takes the generated text out of each event: the visible text, and also reasoning, refusals, tool-call arguments, transcripts and fields it does not know. An event without generated text (the role chunk, `message_start`, `response.created`) goes out at once when nothing is waiting. 3. Events with text are held until `window_bytes` of new text has arrived. With `boundary: sentence`, the gateway then waits for a sentence end, but never past twice the window. The end of the answer (`[DONE]`, `message_stop`, `response.completed`) triggers the check at once. 4. The held text is checked together with the last bytes already sent. Local guardrails check each output channel (a choice, a content block), and provider guardrails check everything generated, after masking. 5. Events that passed go out in order. The last `holdback_bytes` of text stay held and are checked again with the next window, so a value that straddles two windows is caught before any part of it is sent. What ends a stream: a finding of a `block` guardrail, a required check that failed (`on_error: block`), a text larger than the service checks, or an event larger than `max_held_bytes`. When that happens, nothing that was held is sent, and the gateway keeps reading the provider's stream to its end without forwarding it. That way the usage the provider reports is recorded exactly and billed as for any answer. The client then gets one error event in its own dialect, and nothing after it: ```text data: {"error":{"code":"guardrail_blocked_output","message":"I can't share that answer.","param":null,"type":"content_filter"}} ``` | Dialect | Error event | | --- | --- | | Chat Completions | `data: {"error":{"code":...,"message":...,"param":null,"type":...}}`, without `[DONE]` | | Messages | `event: error` with `{"type":"error","error":{"type":"api_error","message":...}}` (`overloaded_error` when a check failed) | | Responses | `event: error` with `{"type":"error","code":...,"message":...,"param":null}` | | Code | When | Message | | --- | --- | --- | | `guardrail_blocked_output` | a block guardrail found something | the guardrail's `refusal`, or the default refusal for a provider guardrail, or `The answer was blocked by guardrail ` | | `guardrail_unavailable` | a required check failed | `A required guardrail could not check the answer` | | `guardrail_output_unavailable` | an event above `max_held_bytes`, or a text above what the service checks | `The answer could not be inspected by output guardrails` | **Masking** rewrites the held text before it is sent. The masked text of each channel goes into the window's first event of that channel, and the channel's later events in the window carry an empty string. Every other field stays as the provider sent it. Some text cannot be rewritten in place: a finding there ends the stream as a block would. That covers: - a finding that starts in text already sent; - any finding in a native Responses stream, whose done events and final response repeat the text, unless `guardrail_stream_responses_mask` is on (below); - a chat stream, or a native Responses stream, that returns token `logprobs`; - text outside a text delta, such as content parts, non-JSON data or a done event that differs from its deltas. **Native Responses streams masked in place** (operator flag `guardrail_stream_responses_mask`, off by default, requires `guardrail_streaming`). A Responses stream says its text twice: in `response.output_text.delta` events, then whole in `response.output_text.done`, `response.content_part.done`, `response.output_item.done` and the terminal `response.completed` (or `response.incomplete`, `response.failed`). With the flag on, a mask finding rewrites the deltas like a chat stream, and each later event that repeats a masked channel's text carries exactly the masked text the client already received for it. No event is added, removed or reordered: the event names and every `sequence_number` stay as the provider sent them, and every other field (reasoning items with their `encrypted_content`, `usage`, `obfuscation`, item IDs) is unchanged. These still end the stream: a block finding, a finding in text already released, deltas with non-empty token `logprobs`, and a done event whose text differs from its deltas (it is scanned on its own and cannot be rewritten consistently). The guardrail list (`GET /api/v1/admin/guardrails`, `streaming.responses_mask`) and the console's streamed-answers note say whether the flag is on. Limit: `annotations` offsets (`start_index`, `end_index` of a citation) in a masked part are not shifted; the native Responses route still needs `store: false`, so no unmasked original is kept by the provider. ```yaml features: guardrails: true stream_usage: true guardrail_streaming: true guardrail_stream_responses_mask: true ``` **Monitors** (`mode: monitor`) never hold a stream. The answer goes out unchanged, and the monitors check the whole text once the stream ended (up to 8 MiB), recording `would_block` or `would_mask` as for a JSON answer. **Client gone:** when the client disconnects, nothing more is written, not even the error event, and the guardrails that had text still waiting record `incomplete`. **A provider that fails mid-stream:** the text it sent before failing is checked and released, then the usual interruption event follows. An event the provider never finished is dropped. ```yaml features: guardrails: true stream_usage: true guardrail_streaming: true guardrail_streaming: window_bytes: 1024 # new text checked at once holdback_bytes: 256 # checked text kept back and checked again with the next window boundary: sentence # or bytes max_held_bytes: 1048576 guardrails: - id: answer-moderation name: Answer moderation mode: block stages: [output] stream: inspect # default; refuse keeps answering streams with 400 provider: {type: moderation, model: mod, on_error: block} ``` | Field | Default | Bounds | | --- | --- | --- | | `guardrail_streaming.window_bytes` | `1024` | 64 to 65536 | | `guardrail_streaming.holdback_bytes` | `256`, or half of a smaller window | 0 to 4096, smaller than `window_bytes`. The last 256 bytes sent (or `holdback_bytes`, if larger) are always rechecked as context. | | `guardrail_streaming.boundary` | `sentence` | `sentence` (a window waits for `.`, `!`, `?`, `;`, `:`, a line break or their CJK forms) or `bytes` | | `guardrail_streaming.max_held_bytes` | `1048576` | 65536 to 16777216, and at least four times `window_bytes` plus `holdback_bytes`. Reaching it with many events checks and releases early. A single larger event ends the stream. | | `guardrails[].stream` | `inspect` | `inspect` or `refuse`; only with the `output` stage. `refuse` answers stream requests on the aliases it covers with `400 guardrail_output_unsupported` before dispatch. It has no effect while the flag is off. | The `guardrail_streaming` block is read at boot (restart to apply). The console shows it, read-only, under **Streamed answers** in the guardrail editor, where `stream` is set. Costs and trade-offs: - Every window is a call to each provider guardrail. Their request IDs are `.w.guardrail-output`, so each call has its own record. A larger window means fewer calls, and a longer wait before the first text. - The client sees text in bursts, one window at a time. - A blocked stream's error event arrives only after the provider finished generating, because the usage must be measured. A client with a short read timeout may give up first. If it does, it is recorded as a client cut. - A streamed answer is never written to the semantic cache while an output guardrail applies. ### Cache An answer that was refused, blocked, or passed only because a guardrail service failed open is never written to the semantic cache. An answer that passed is cached as the client saw it, and a later hit is served without a new check. The cache key includes the output guardrails that applied, with their settings, so the hit already passed the same checks. Changing a guardrail changes the key. The exact cache does not serve Chat Completions, Messages or Responses. ## External services External services run **after** the local detectors, on the already masked text. A guardrail with `provider` needs `mode: block`, has no detectors or patterns of its own and runs on input, on output or both (`stages`). If the service fails, the response is `503 guardrail_unavailable`, unless the guardrail declares `on_error: allow`. On the output stage the service receives the generated text of the answer: its content, refusals, audio transcripts, the reasoning the provider returned and tool calls. A harmful answer can be written into a tool call or a reasoning summary that an app displays, so they are checked too. A block, item or message field the gateway does not know (hosted tool results, provider extensions) goes as its JSON, without base64 images, encrypted content and signatures: something unknown is never treated as nothing to check. Search results and code output in an answer are checked as well, so they can also be flagged. Each service is told it is reading an answer: | Service | What changes on output | | --- | --- | | Moderation model | internal call with the derived ID `.guardrail-output` (input uses `.guardrail`) | | Azure AI Content Safety | harm categories only; Prompt Shields rates prompts, so an output guardrail needs `categories` | | Presidio | the same analysis on the answer text | | Amazon Bedrock Guardrails | `source: OUTPUT` | | Generic guardrail API | `input_type: response` | | Lakera Guard | the answer goes as `assistant` messages | | Judge (an evaluator) | `{{output}}` is the answer; internal call `.guardrail-judge-output.0` (input uses `.guardrail-judge.0`) | **Service failure on output** follows `on_error`, as on input. With `block` (the default) the answer is withheld with `503 guardrail_unavailable`: the provider generated it, but the required check did not run. With `allow` the answer goes out, a Warn `guardrail_provider_failed` line with `stage: output` is logged, and the answer is not cached. **An answer longer than the service checks** is withheld with `502 guardrail_output_unavailable` even with `on_error: allow`. The client decides how long the answer is, so a size limit that let the answer through would be a way around the check. The limits are 200,000 characters for a moderation model (ten parts of 20,000), 100,000 for Presidio, Bedrock, Lakera and the generic API, and ten parts of 10,000 for Azure AI Content Safety. On input the earlier behavior stays: an oversized request is a service failure, and `on_error` decides. **The Compliance tab** tests a guardrail that runs only on answers the way it reads answers: no Prompt Shields, Bedrock `OUTPUT`, Lakera `assistant`, generic `input_type: response`. ### Judge (one of your evaluators) Type `judge` runs one of your [evaluators](/docs/features/evaluators/) on the text, with its judge model: a `fail` assessment blocks (or, in monitor mode, would block). Settings: `evaluator` (required), `max_tokens` (16-600, default 64), `max_input_chars` (100-100000, default 8000), `timeout` and `on_error`. The evaluator must belong to the request's team or to a team of the same organization; streams are refused. Everything about it, cost and latency included, is in [Judge guardrails](/docs/features/judge-guardrails/). ### Azure AI Content Safety A guardrail can delegate detection to Azure AI Content Safety: ```yaml guardrails: - id: safety name: Content safety mode: block # required with provider provider: type: azure_content_safety endpoint: https://.cognitiveservices.azure.com api_key_env: CONTENT_SAFETY_KEY # optional; without it, uses Entra ID categories: [Hate, SelfHarm, Sexual, Violence] severity_threshold: 4 # 0-7 prompt_shields: true # jailbreak on_error: block # or allow ``` | Key | Default | What it does | | --- | --- | --- | | `provider.endpoint` | required | The resource's https URL, `https://.cognitiveservices.azure.com`, with no path | | `provider.categories` | `[]` | Azure categories that block: `Hate`, `SelfHarm`, `Sexual`, `Violence`; the guardrail needs categories, `prompt_shields` or both | | `provider.severity_threshold` | `4` | Severity, 0–7, at or above which a category blocks | | `provider.prompt_shields` | `false` | Also runs Azure Prompt Shields, which blocks jailbreak attempts | - **Order:** runs after the local guardrails, on the already masked text. - **Blocking:** responds 400 `guardrail_blocked`, with a count in `X-Gateway-Guardrails`. - **Service failure:** 503 `guardrail_unavailable`, unless `on_error: allow` is set. - **Console:** in the guardrail editor, check **Check with an external service (blocks)** and choose the service; check **Answer (output)** to also check answers. ### Presidio (PII by an external analyzer) `provider.type: presidio` queries the open source [Presidio](https://microsoft.github.io/presidio/) Analyzer, running alongside the gateway: ```yaml guardrails: - id: pii-presidio name: PII (Presidio) mode: block provider: type: presidio endpoint: http://presidio-analyzer:3000 entities: [CREDIT_CARD, US_SSN, IBAN_CODE, PERSON] language: en score_threshold: 0.7 on_error: block ``` - **When it runs:** after the local detectors, on the already masked text. | Key | Default | What it does | | --- | --- | --- | | `provider.endpoint` | required | The analyzer's http(s) URL; the gateway calls its `/analyze` | | `provider.entities` | required | 1–50 Presidio entity types that block (`PERSON`, `CREDIT_CARD`, `US_SSN`, `IBAN_CODE`, ...) | | `provider.language` | `en` | Two-letter lower-case language code the analyzer reads the text in (`en`, `pt`) | | `provider.score_threshold` | `0.5` | Minimum recognizer score, 0–1, for an entity to block | - **What it blocks:** each entity of a listed type with a score at or above the threshold blocks with 400 `guardrail_blocked`. Types the analyzer returns that are not on the list do not block. - **Service failure:** with `on_error: block` (the default), it responds 503; with `allow`, it lets the request through. - **Tested** with the official `mcr.microsoft.com/presidio-analyzer` image and the real OpenAI: an ordinary question passed; a card number and a person's name were blocked before the provider; the email, masked locally, went through. ### Moderation model `provider.type: moderation` uses any moderations alias of the gateway itself: ```yaml models: - id: mod capabilities: [moderations] targets: [{provider: openai, model: omni-moderation-latest}] guardrails: - id: moderation name: Moderation mode: block models: [gpt] # empty = all aliases provider: type: moderation model: mod categories: [violence, self-harm/intent] # empty = whatever the provider flags score_threshold: 0.4 # optional: blocks by category_scores on_error: block ``` - **As the caller:** moderation runs as the key that made the request, restricted to the `mod` alias. It appears in the request log and the usage ledger under that key and its team, and the key does not need its own access to the alias. - **Budgets and token ceilings do not apply to the check:** the moderation call is the gateway's own check, chosen by the operator, so it takes no [budget or TPM](/docs/features/budgets-and-tpm/) reservation and is never refused for quota, whatever policy applies to the caller (its key, team, user, project, organization, end user, or the moderation alias itself). A policy whose subject is the moderation alias therefore refuses every direct call to it (`422`) and never applies to guardrail checks. The guarded request is reserved and settled as usual. Moderation has no quota profile, so without this exemption a covering policy would refuse every check. Nothing of the check is charged to the caller's budget, TPM or TPD. A client calling `/v1/moderations` directly is still refused under a covering policy (`422 quota_profile_unsupported`, see [moderation](/docs/features/moderations/#with-other-features)); the exemption is attached only to the gateway's own in-process call and cannot be requested by a header or a body field. - **Where the check is visible:** each check is its own entry in the request log and the usage ledger, with `operation: moderations`, the caller's key and team, the derived request ID `.guardrail` (`.guardrail-output` on the answer) and, in [request audit events](/docs/features/request-events/), `"internal": true`. Its tokens and cost are recorded as unknown, like any moderation call. With [evaluation tracing](/docs/features/evaluation-tracing/#helper-calls) on, every check is a `helper` call of kind `guardrail`, so the guardrails' spend is its own line in Cost estimates (**Spend by origin**, `by_helper_kind` on `GET /api/v1/admin/valuation`), apart from the application's. A moderation call has no price model, so today that line counts the checks as unknown rather than zero; a helper call valued through a priced model shows its known amount in the same line. A provider that bills moderation (by tokens, for example) charges the connection's account; that cost is not in the caller's budget, so read it from the provider's billing. - **RPM does not count the check either:** for the same reason, the check is not a request of the caller's key, team or end user for [RPM](/docs/features/access-control/#request-limits-rpm). The guarded request is counted once, as before, and over its limit it answers `429 rate_limit_exceeded` before any guardrail runs, so no check is made for it. A check is therefore never refused for RPM: `rpm: 1` lets one guarded request a minute through with all of its checks (input and output), `on_error: block` never turns the caller's RPM into `503 guardrail_unavailable`, and `on_error: allow` never lets a request out unchecked because of it. Monitor guardrails' checks spend no RPM either. The check also takes no concurrency slot and is not checked for [required attribution](/docs/features/budgets-and-tpm/#where-it-is-checked). Only that in-process call is exempt: a client calling `/v1/moderations` directly, and the gateway's other in-process calls, count as before, and no header or body field claims the exemption. - **A request already over its quota does not pay for a check:** input guardrails run before the guarded request's [quota reservation](/docs/features/budgets-and-tpm/#where-it-is-checked), because the reservation is estimated from the request as they leave it, and a mask can make the text longer or shorter. Right before the first moderation check of the request (enforcing or monitor), with `budget_limits` or `tpm_limits` on, the gateway asks the quota store, without reserving or changing anything, whether that admission is certain to refuse the request whatever the guardrails do to its text: what settled requests already spent on a daily or monthly budget or TPD counter of a policy that applies leaves no room for the smallest reservation the request could take, or a budget, TPM or TPD ceiling is below that smallest reservation by itself. The smallest reservation is the request's output limit plus the fixed 4,096-token allowance every input estimate carries, with the request's images and shape as they are (a mask replaces text, never parts or items). If so, the request answers `429 quota_exceeded` for that policy, with the `Retry-After`, `X-Gateway-Quota-Policy` and `X-Gateway-Quota-Dimension` the admission uses, and the moderation provider and the model's provider are not called. It exists because a provider that bills moderation would otherwise charge a check for a request already bound to be refused. - **It never refuses what the admission would admit:** it applies the admission's own comparison to that lower bound, so where it refuses, any larger reservation is refused too, and it counts only what cannot free before the admission runs. Reservations of requests still in flight are left out, since they may settle lower or be released. A TPM counter never refuses by its content, since its minute may end first; a daily or monthly counter does only while its window lasts longer than the guardrails and the admission can take (7 seconds per provider check of the stage, plus 5). A counter a billing reconciliation lowered below what its open reservations hold counts as empty. Only an operator action in those seconds (a billing import, a policy edit) can still change the outcome. When several policies would refuse, the admission might have named another one of them. - **When it is not certain, nothing changes:** with room smaller than this request's estimate but not smaller than the lower bound, room taken only by requests in flight, a full TPM minute, a profile or settings refusal (`422 quota_profile_unsupported`), storage trouble, or a quota store other than PostgreSQL, the check runs and the admission answers after it, as before; such a request still makes one moderation call per input guardrail before its `429`. - **Order:** local detectors still run first and keep their `400 guardrail_blocked`. A request the moderation check would have blocked, but that is certainly over its quota, gets the `429`. A provider guardrail listed before the first moderation guardrail still runs before the precheck. - **Cost:** with `budget_limits` or `tpm_limits` on, each request that reaches a moderation guardrail reads the quota state once more (one short read transaction, no locks on counters; open reservations are found through their own index) before its check. - **What it blocks:** without `categories` and without `score_threshold`, it blocks whatever comes back `flagged`. With categories, only the listed ones. With `score_threshold`, the score of each category applies. - **When it runs and failures:** order and failure handling are the same as Presidio: after the local detectors, 400 `guardrail_blocked`, and 503 with `on_error: block`. - **OpenAI project:** if the project restricts models, allow `omni-moderation-latest` in it. Without that, OpenAI responds 403 and the guardrail fails closed. - **Other providers:** any `/v1/moderations` provider works, and it was validated with OpenAI and Mistral. When the response has no `flagged` field (Mistral), any flagged category counts. - **On answers:** with `stages: [output]` the same alias checks the answer, as a second moderation call per request (`.guardrail-output`), also billed to the caller's team. A flagged answer becomes the refusal; see [Inspecting the answer](#inspecting-the-answer-output-stage). - **Calibration:** OpenAI's `flagged` is sensitive; a question about a fight scene in a movie gets violence 0.43 and is flagged. To block threats (0.9+) without stopping that kind of question, use `categories: [violence]` with a `score_threshold` around 0.6. ### Amazon Bedrock Guardrails `provider.type: bedrock_guardrail` applies an AWS guardrail (`ApplyGuardrail`) to the request text, signed by one of the gateway's own Bedrock connections: ```yaml providers: - id: aws protocol: bedrock base_url: https://bedrock-runtime.us-east-1.amazonaws.com auth: {type: aws_sigv4, region: us-east-1} guardrails: - id: bedrock name: Bedrock guardrail mode: block provider: type: bedrock_guardrail connection: aws # bedrock provider: region and identity guardrail_id: abc123def456 guardrail_version: "3" # default DRAFT on_error: block ``` | Key | Default | What it does | | --- | --- | --- | | `provider.connection` | required | ID of one of the gateway's `bedrock` providers; its region and SigV4 identity sign `ApplyGuardrail` | | `provider.guardrail_id` | required | The AWS guardrail identifier | | `provider.guardrail_version` | `DRAFT` | The guardrail version to apply, as a string (`"3"`) | - **Policies:** configured in AWS: filters, prompt attack, topics, words, PII, regex. - **What it blocks:** each `BLOCKED` action counts as a finding and blocks with 400 `guardrail_blocked`. - **Anonymized PII:** PII with `ANONYMIZE` does not block and goes through unmasked. To mask, use the local detectors or Presidio. - **When it runs and failures:** same order and same `on_error` as the other external services. - **Permission:** the connection's identity needs `bedrock:ApplyGuardrail` on the guardrail. ### Generic guardrail (your own API) `provider.type: generic_api` calls a service of yours: the gateway sends the request texts and the service responds whether to block. Use it for your company's own rules: ```yaml guardrails: - id: company-policy name: Company policy mode: block provider: type: generic_api endpoint: http://guardrail-service:8080/check # the service's full URL api_key_env: GUARD_KEY # sent as x-api-key params: {policy: strict} # additional_provider_specific_params apply_redactions: false # true applies GUARDRAIL_INTERVENED texts timeout: 5s # 100ms-30s, default 5s on_error: block ``` - **What the service receives:** - `texts`, already masked by the local detectors; - `model` and `input_type: request`; - `call_id` and `trace_id`, with the request ID and the trace ID; - `request_data`: the key's alias, team and end user. - **What is not sent:** client headers and the structured conversation. - **Decision:** - `BLOCKED` blocks with 400; - `NONE` lets the request through; - `GUARDRAIL_INTERVENED` lets it through unchanged by default: its `texts` are advice. With `apply_redactions: true` they are applied (below); - any other action or a status other than 200 counts as a failure (`on_error`). - **Applying redactions** (`apply_redactions: true`): - **Validation:** the answer must carry `texts` with one JSON string per text sent, in the same order, each at most twice the original plus 4,096 bytes. A missing list, another count, a `null` or a number is a failure, and `on_error` decides: `block` answers 503, `allow` sends the original text and logs the failure. - **Input:** each text replaces the one sent, in place. Roles, tool calls, images and the message structure stay as the client sent them; the next guardrails and the provider see the redacted text. - **Output** (a non-streaming answer, with the `output` stage): the texts replace the visible answer text and refusals. A change the answer cannot carry rewritten (reasoning, an audio transcript, tool-call arguments, a block checked as raw JSON) withholds the answer with the guardrail's refusal, so neither the original nor a half-redacted answer goes out. So does a redaction of an answer with token `logprobs` or a stored Responses answer ([Held rewrites](#held-rewrites)). - **Streams:** a streamed window joins already released text, every output channel and the non-visible text in one check, so it cannot be rewritten. A redaction ends the stream like a block (error event `guardrail_blocked_output`). Use `stream: refuse` if clients should send `stream: false` instead. - **Monitors** (`mode: monitor`) never rewrite; a redaction counts as a finding they would act on. - **Audit:** an applied redaction is counted as `masked` in `X-Gateway-Guardrails` (or `-Output`), in the metrics and in the request event, and logged as `guardrail_redaction_applied` with the guardrail ID and the number of texts changed and checked. Never the text. - **Failure policy:** pair it with `on_error: block`. With `allow`, a check the service cannot finish (a long request that outlasts `timeout`, for example) lets the original text through. - **Timeout:** `timeout` is the deadline of one check, from `100ms` to `30s` (default `5s`); every provider type takes it except `extension`, whose deadline is the plugin manifest's `timeout_ms`. The guardrail editor offers **Extension plugin** as an external service while `extension_guardrails` and `extensions` are on: it asks for the plugin ID only, with no endpoint, key or timeout. The deadline cancels the call, and a check cut by it is a failure (`on_error`). - **Example service:** a Python implementation of this contract, with a pinned Containerfile, a health check and timeout guidance, is in `extensions/examples/python-guardrail`; see [Out-of-process plugins (Python and ML)](/docs/features/extensions/#out-of-process-plugins-python-and-ml). ### Lakera Guard `provider.type: lakera_guard` calls Lakera Guard v2. The policy (prompt attack, PII, moderated content) lives in a Lakera project: ```yaml guardrails: - id: lakera name: Lakera Guard mode: block provider: type: lakera_guard api_key_env: LAKERA_API_KEY project_id: project-1234 # optional: that project's policy # endpoint: https://lakera.internal # only for self-hosted Lakera on_error: block ``` | Key | Default | What it does | | --- | --- | --- | | `provider.endpoint` | Lakera's SaaS | The https base URL of a self-hosted Lakera; the key goes to it as a bearer token | | `provider.project_id` | empty | Lakera project whose policy decides; without it the account's default policy applies | | `provider.api_key_env` | required | Variable holding the Lakera API key | - **Blocking:** `flagged` blocks with 400, and each triggered detector counts in `X-Gateway-Guardrails`. A response without a verdict is a failure (`on_error`). - **Tested with the real Lakera:** a prompt attack in English and in Portuguese and an insult were blocked, and an ordinary question passed. ## Limits - The output of **streams** is inspected only with `guardrail_streaming`, in windows. Without it, a provider guardrail on the output stage refuses streams for the aliases it covers. Responses background requests and conversation turns are always refused, and so are stored (`store` not `false`) native Responses streams while the flag is on. - A streamed value longer than `holdback_bytes` that straddles two windows can have its first part sent before the stream ends. Raise `holdback_bytes` above the longest value you mask or block. - On output, the local detectors mask only the visible answer text; the external services also read refusals, reasoning and tool-call arguments. - A semantic fallback (`content_policy_fallback`, `context_window_fallback`) answers through the other alias, whose own output guardrails apply, not those of the alias the client named. - The local detectors are heuristic: check precision and recall in the **Catalog** before you trust a block. - The evaluated text never goes to logs or telemetry; only the counts do. - External services receive the already masked text; check each service's terms before sending data. On output they also receive reasoning, transcripts and tool calls, which the local detectors do not mask. - A refusal replaces what the client receives, not what the provider did. The provider may still keep the response it stored (Responses `store`), and a code-interpreter container it created is still claimed for the caller's team. A refused Responses answer cannot be continued with `previous_response_id`; an agent that chains responses starts over. - Bedrock `ANONYMIZED` does not block and does not rewrite the answer, as on input; nor does a generic API `GUARDRAIL_INTERVENED` without `apply_redactions`. - A moderation guardrail on answers is a second call made as the caller. Like the input check it takes no budget or TPM reservation and spends no RPM (see above); if it fails for any reason, `on_error` decides, and with `block` the answer is withheld. The quota precheck applies only before input checks: the answer's check runs after the request was admitted. - The native Gemini GenerateContent relay runs neither input nor output guardrails; see the refusal above for output provider guardrails. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `GET /api/v1/admin/guardrail-policies` | Lists the guardrail policies (`GuardrailPolicy`, with their source) and the ready-made templates | | `PUT /api/v1/admin/guardrail-policies/{id}` | Creates or replaces a console policy | | `DELETE /api/v1/admin/guardrail-policies/{id}` | Removes a console policy, or reverts a YAML one | | `POST /api/v1/admin/guardrail-policies/simulate` | Shows which guardrails a request of a given team, key and model meets, and why | | `POST /api/v1/admin/guardrail-policies/templates/{id}/apply` | Creates a template's guardrails and a policy attached to the given teams, keys or models, in one change | | `GET /api/v1/admin/guardrails/datasets` | The labeled cases the catalog and the compliance test use | | `POST /api/v1/admin/guardrails/simulate` | Runs a draft guardrail on up to 8 KiB of sample text; nothing is sent or stored | ## See also - [Guardrails](/docs/features/feature-guardrails/): overview. - [Playground](/docs/features/playground/): the Compliance tab. - [Access control](/docs/features/access-control/): the `guardrails:read` and `guardrails:manage` permissions. ## Policy schema boundaries Guardrail definitions and inheritance remain typed domain configuration. Pattern content, external endpoint and credential references are not published through the safe parameter catalog. Shared [parameter definitions](/docs/reference/parameter-registry/) must preserve existing stages, detector/provider validation, default-on behavior, inheritance and removal precedence. A schema or enabled flag never grants access to a provider, model or managed writer. Presidio and moderation `score_threshold` values must be finite and within `0`–`1`. Their zero semantics remain different: Presidio selects its `0.5` fallback, while moderation keeps its existing provider-flag/category decision behavior. YAML `NaN` and infinities do not bypass these bounds. Guardrail display names follow the server limit of eighty Unicode runes; identifiers retain their separate ASCII grammar. The score controls accept continuous values without rounding to a fixed increment, while the server remains authoritative for bounds and provider-specific validation. On observed loss of management access or accepted configuration metadata, the console discards guardrail drafts and simulation results. A response started under the previous authority cannot restore them afterward. This adds no polling or permission grant. # Judge guardrails **Last updated:** 2026-11-26T03:21:52-03:00 (UTC-3) A judge guardrail uses one of your [evaluators](/docs/features/evaluators/) as a guardrail: before the request reaches the provider (input) or before the answer reaches the app (output), the gateway asks the evaluator's judge model about the text and acts on its verdict. Use it for rules that a pattern or a classifier cannot express ("does this answer promise a refund?", "is this question about another customer?"). A judge adds a model call to every request it checks, so it adds latency and cost by design. Use a small, fast judge model, keep `max_tokens` low, and try it in monitor mode first. | Flag | What it turns on | | --- | --- | | `judge_guardrails` | Guardrail provider type `judge`, the guardrails backed by a judge in an alias's **Used by**, and the dataset of guardrail cases. Off by default. A tenant flag: with plan entitlements a team's plan must include it. Needs `guardrails` and `evaluators` | ## How to turn it on 1. Create an evaluator of the team whose traffic it will check (Evals → Evaluators). It must be an **LLM judge** or a **rule** evaluator with **pass criteria** (or boolean output): a `fail` assessment is what blocks. A decision model or a JavaScript evaluator is refused. `{{output}}` is the text being checked at either stage; `{{input}}` is the request text at input and empty at output. 2. Publish it. The guardrail always runs the **published version**; publishing a new version changes the guardrail within 15 seconds. 3. Measure it first (optional, recommended): **Evaluate on guardrail cases** below. 4. Add the guardrail, in monitor mode: ```yaml features: guardrails: true evaluators: true judge_guardrails: true guardrails: - id: no-refund-promises name: No refund promises mode: monitor # monitor first; block when you trust it models: [support-chat] stages: [output] provider: type: judge evaluator: ev_6a1f0c2b9d3e4f5a6b7c8d9e # the evaluator's ID max_tokens: 64 # 16-600, default 64 max_input_chars: 8000 # 100-100000, default 8000 timeout: 3s # 100ms-30s, default 5s on_error: block # block (default) or allow ``` 5. Read what it would have done on the request log (guardrail outcome `would_block`) and on the evaluation results of the evaluator, then switch `mode` to `block`. The console has the same fields in **Guardrails → New guardrail → Evaluator (judge)**. ## What a check does - **Pass** (or an assessment of `none`): the request goes on. - **Fail**: in block mode the request is refused with `400 guardrail_blocked` at input (the provider is never called), and the answer is replaced by the guardrail's refusal at output (the generation was already billed). In monitor mode nothing changes; the outcome is `would_block`. - **The judge cannot answer** (its model failed, the timeout passed, the text is longer than `max_input_chars`, the evaluator was deleted or unpublished, the flag or the team's plan is off): `on_error` decides. `block` answers `503 guardrail_unavailable`, a different code from a content block; `allow` lets the request through and records `error_allowed`. A judge guardrail never blocks without a verdict or your explicit `on_error: block`. - Text longer than `max_input_chars` is never cut: the check fails as `text_too_large`. At output an answer that cannot be checked is always withheld, whatever `on_error` says. - A **stream** cannot be judged whole: a streamed request on an alias with an output judge guardrail is refused before it is sent (`400 guardrail_output_unsupported`). ## Who may judge whose text The evaluator must belong to the request's team, or to a team in the same organization. A request of another organization fails the check with `evaluator_out_of_scope` (and `on_error` decides): one tenant's evaluator never reads another tenant's text, and its definition is never used for another tenant's traffic. ## Cost, latency and recursion - The judge's call is a **helper call** of the request's own team (origin `helper`, kind `guardrail`, parent the request), made as the request's key narrowed to the judge alias. It is budgeted, rate-limited and priced like any other traffic of that team, and its request ID is `.guardrail-judge.0` (input) or `.guardrail-judge-output.0` (output). - The team's own ceiling (team policies), its plan and the judge alias's model policies apply to the call: the judge alias comes from a tenant's evaluator, so it gets no exemption. A refusal is a check that failed, and `on_error` decides. - The request key's own model list is replaced by the judge alias for this one call, as for a moderation guardrail: the key never asked for the judge, so its list does not decide; the team's ceiling does. - One attempt only, bounded by `timeout` and `max_tokens`. The evaluator's own temperature applies; its own `max_tokens` is replaced by the guardrail's. - The call is a **child span of the guardrail span** in the request's trace (stored, and over OTLP), so the trace shows the guardrail, its judge request and that request's provider attempt. - A call a judge makes (an evaluator, an experiment or a judge guardrail) is **never checked by a judge guardrail**, so a guardrail on the judge's own alias cannot call itself. - Measured cost on the request path: [judge guardrails performance](/docs/performance/judge-guardrails/). The gateway adds about 5 ms at the median on top of the judge model's own time. ## Keeping it working - An evaluator that an enabled judge guardrail runs **cannot be disabled or deleted**, and a version the guardrail could not run (a decision model, JavaScript, no pass criteria) **cannot be published**, while the guardrail depends on it: the API answers `409 evaluator_in_use` naming the guardrail. Change or disable the guardrail first. Pausing it is allowed: a paused evaluator stops judging live traffic and still backs the guardrail. Deleting the evaluator's whole team is not stopped by this rule: the guardrail then fails its checks and counts as misconfigured. - A judge guardrail that cannot reach a decision for a reason of configuration (the flag, the team's plan, an evaluator out of scope or gone) counts `outcome="misconfigured"` on `gateway_guardrail_findings_total` for each check and logs `judge_guardrail_misconfigured` at most once a minute per guardrail and reason. `on_error` still decides each check, so watch this signal when `on_error` is `allow`. - Scope a judge guardrail to the teams of its evaluator's organization with [guardrail policies](/docs/features/guardrails/#policies-per-team-key-or-model): the other organizations' requests always fail the check with `evaluator_out_of_scope`. ## Every decision is a result Each check is written, off the request path, as an [evaluation result](/docs/features/evaluation-results/) on the request, in the request's team: the evaluator's name and version, the assessment, the judge's explanation (encrypted, for content readers), the judge cost from the ledger, and in its metadata the guardrail, the stage, the mode, the decision (`pass`, `blocked`, `would_block`, `error_blocked`, `error_allowed`) and the latency. The usual analytics answer "how much did this guardrail cost" and "how often did it block": group evaluation results by `evaluation` with `judge_cost_usd` and `evaluation_fail`. A check that never reached an evaluator (flag off, not entitled, out of scope) writes no result; the request log still records its outcome. ## Evaluate on guardrail cases The gateway ships labeled guardrail cases (prompt injection, PII, secrets). `POST /api/v1/admin/evals/datasets/from-guardrail-cases` copies them into an evaluation dataset of your team (`team_id`, optional `name` and `frameworks`); each item's expected output is `fail` (must be stopped) or `pass`. Run an experiment with your evaluator on it before it guards traffic. A judge guardrail can also be measured in **Guardrails → Catalog → Evaluate**, which runs the judge as the evaluator's own service account. ## Where it shows - The guardrail span: `evaluator_id`, `judge_request_id` and the outcome. - An alias's **Used by** panel (with `alias_evaluator_usage`): the judge guardrails backed by an evaluator that judges on that alias, and, for readers of guardrails, every guardrail that checks the alias. ## See also [Guardrails](/docs/features/guardrails/) · [Evaluators](/docs/features/evaluators/) · [Evaluation results](/docs/features/evaluation-results/) · [Route experiments](/docs/features/route-experiments/) # Extensions **Last updated:** 2026-11-22T07:10:00-03:00 (UTC-3) Extensions let an operator add small pieces of logic to the gateway - today a custom guardrail - without changing the gateway itself and without giving that logic access to the host. A plugin is a WebAssembly module, or JavaScript source, plus a signed manifest. The gateway runs it in process, in a sandbox, a fresh instance for every call. | Flag | Default | What it turns on | | --- | --- | --- | | `extensions` | `false` | The runtime, the admin API under `/api/v1/admin/extensions`, the execution audit and the console page **Settings → Extensions** | | `extension_guardrails` | `false` | Guardrail provider type `extension` (requires `extensions` and `guardrails`) | | `extension_submissions` | `false` | Team administrators submit plugin versions for review (requires `extensions`) | | `extension_javascript` | `false` | The JavaScript runtime (QuickJS on the same sandbox), used by [MCP code mode](/docs/features/mcp-code-mode/) and, with `extension_guardrails`, by [JavaScript plugins](#javascript-plugins) (requires `extensions`) | All are operator controls under plan entitlements. With them off nothing is loaded, compiled or run. ## The sandbox A plugin runs on [wazero](https://wazero.io) (pure Go, no CGO), with WASI preview 1 and nothing behind it: - no file system, environment variables, arguments or standard input; output streams are discarded; - a fake clock and deterministic randomness; - no sockets. What a plugin can do is limited to the **`aigw` host functions** (ABI `aigw-ext-v1`): | Function | What it does | | --- | --- | | `input_len() -> i32`, `input_read(ptr, len) -> i32` | Read this call's input (for a guardrail, a JSON document) | | `output_write(ptr, len) -> i32` | Append to the answer; past the limit the call ends with `output_limit` and nothing is returned | | `result_read(ptr, len) -> i32` | Read the last host result (the `http_call` answer) | | `http_call(ptr, len) -> i32` | Only when the manifest grants it: send one HTTP request through the gateway | A module that imports anything else - an ungranted host function, another import module, an imported memory - is refused when it loads. Tables live outside the memory ceiling, so a table may have at most 65,536 entries and plugins run without the WebAssembly reference-types feature: `table.grow` and multiple tables do not compile. Go, TinyGo and AssemblyScript output needs nothing more; for Rust, build with `-C target-feature=-reference-types`. Every call has a deadline (the call is interrupted, even inside an infinite loop), a memory ceiling in 64 KiB pages, an output limit and an HTTP call budget. Calls are admitted per replica and per team; past either bound a call is refused at once and counted, never queued. A trap, a panic or a non-zero exit inside the plugin is an outcome of that call; the gateway keeps running. Activating another version stops new calls on the old one at once and releases it when the calls already running finish. **Network only through the host.** `http_call` takes `{"method", "url", "headers", "body"}`. The URL's origin must be in the plugin's signed manifest **and** in the calling team's binding. A header may reference a secret by name - `{"name": "Authorization", "value": "Bearer ", "secret": "API_TOKEN"}` - and the gateway appends the calling team's value inside the host; the plugin never sees it, and an answer that echoes the secret back is refused. Requests go through the same pinned, redirect-free egress client as every other integration (private ranges, loopback and cloud metadata refused unless allowed in `extensions.http`). The answer is `{"status", "content_type", "body"}`, bounded by `extensions.http.max_response_bytes`. **What the sandbox does not cover.** Calls share the process and CPU caches, so timing side channels between tenants are not prevented; tenants that need physical isolation need separate replicas. A plugin can spend its whole budget. A signature proves who approved a plugin, not that its logic is right. See the [threat model](/docs/security/threat-model/#extension-runtime-t058). ## Manifest and signature ```json { "id": "ticket-guard", "version": "1.0.0", "name": "Ticket guard", "description": "Denies a code name, redacts ticket references", "kind": "guardrail", "abi": "aigw-ext-v1", "host_functions": ["http_call"], "egress": ["https://classifier.internal.example"], "secrets": ["API_TOKEN"], "limits": {"memory_pages": 512, "timeout_ms": 200, "max_output_bytes": 65536, "max_http_calls": 1} } ``` Lists are sorted and unique, so a manifest has one canonical encoding. Limits are capped by the boot ceilings in the `extensions` block. The signature is Ed25519 over `ai-gateway extension signature v1\n` followed by the hex SHA-256 of `{"manifest": , "module_sha256": }`, made offline with `extsign`: ```bash go run ./cmd/extsign keygen -private-key release.key # once; prints the public key go run ./cmd/extsign sign -private-key release.key -key-id release \ -manifest manifest.json -module plugin.wasm # prints {"key_id", "value"} ``` The operator lists the public keys it trusts in `extensions.trusted_keys` (boot configuration only; no API adds one). The gateway checks the signature **every time it loads a version**, never trusting what is stored: a tampered module or manifest, or a key removed from the list, makes the version refuse to load, and the hook fails according to its `on_error`. ## JavaScript plugins With `extension_javascript` and `extension_guardrails` on, a guardrail plugin can be JavaScript source instead of a WebAssembly module. It runs on the same pinned QuickJS engine as [MCP code mode](/docs/features/mcp-code-mode/), inside the same sandbox, with the same signature, lifecycle, team bindings, limits, admission and audit as a WebAssembly plugin. There is no compile step: you sign the `.js` file itself. The manifest says so with `"runtime": "javascript"` (a manifest without `runtime` is WebAssembly; `"runtime": "wasm"` is refused, so a manifest keeps one canonical encoding). The runtime is signed with the rest of the manifest, so a signature never moves a payload to the other runtime. `extensions/examples/javascript-guardrail` has a complete example: `plugin.js` (deny a code name, redact `TCK-123…` tickets, like the Go example) and its `manifest.json`. ```js function guardrail(request) { // request: {hook, stage, texts, model, team_id} - the same input a // WebAssembly plugin reads with input_read. if (request.texts.some((t) => t.includes("forbidden"))) { return { action: "deny", reason: "forbidden_word" }; } return { action: "allow" }; } ``` - **Entry point.** The source must define `function guardrail(request)` (a function declaration or a top-level `const guardrail = ...`) that returns the verdict object **synchronously**: `{"action": "allow"}`, `{"action": "deny", "reason": "label"}` or `{"action": "redact", "texts": [...], "reason": "label"}`. The gateway serializes it with `JSON.stringify` and validates it as strictly as a WebAssembly verdict: unknown fields, another action, a `reason` outside `[A-Za-z0-9_./-]{1,64}` or a `redact` without exactly one text per input text are a malformed verdict, which follows `on_error`. A missing `guardrail`, a promise (an `async` function), a non-object or an exception is the outcome `program_error`, which also follows `on_error`. - **What the script sees.** Each call is a fresh QuickJS instance: top-level code runs again on every call and nothing - globals, prototypes, closures - survives into the next call or reaches another team. The source runs in strict mode as the body of a function (opened on its first line, so error positions match the file), after a prelude that removes the QuickJS `std` and `os` objects; reached again through `import("qjs:std")` they find no file system, environment or process, because the sandbox has none. Top-level declarations are local to the call, so a plugin may shadow any name, `host` included, without breaking the call. The only host object is the frozen global `host`. There is no `fetch`, `require`, timers or real clock. - **Network.** `host.http_call(request)` exists only when the manifest grants `http_call`. It takes the same `{"method", "url", "headers", "body"}` as the WebAssembly host function, goes through the same checks (signed egress and team binding, secrets by reference, budget, response bound, secret echo refusal) and returns `{"status", "content_type", "body"}`. A refusal throws an `Error` whose `code` is `not_granted`, `denied`, `budget`, `invalid_request`, `upstream` or `too_large`; the script may catch it. Without the grant the gateway refuses the operation itself, not just the missing function. - **Limits.** `limits.memory_pages` is the instance's whole memory and must be at least 32 (2 MiB); the script heap is that memory minus 1 MiB kept for the engine. An exhausted heap (even by many small objects, when QuickJS can only throw `null`; a script that throws `null` itself is treated the same way) or runaway recursion ends with `memory_limit`, a loop with `timeout`, a verdict longer than `max_output_bytes` with `output_limit`. These are outcomes the client can force, so the guardrail fails closed whatever `on_error` says, as for WebAssembly. - **Upload.** The JSON body carries the text in `source` instead of `module_base64`: `{"manifest": {...}, "source": "function guardrail(request) {...}", "signature": {...}}`. The signed digest is the SHA-256 of the UTF-8 bytes of `source`, so sign exactly the file you send (`extsign sign ... -module plugin.js`). The source must be UTF-8 without NUL bytes and at most `extensions.max_module_bytes`; the request body is bounded at 4/3 of that plus 64 KiB (past it, `413 module_too_large`), which leaves room for ordinary JSON escaping. The console reads the file as strict UTF-8, keeping a byte-order mark, so the bytes it sends are the bytes you signed. On upload and on approval the source is compiled - never run - and a syntax error is refused as `invalid_source`. Team submissions use the same `source` field. - **Runtime off.** With `extension_javascript` off, JavaScript versions cannot be uploaded, submitted or approved (`404 feature_disabled`), and an active JavaScript version does not run: the execution is recorded as `runtime_disabled` and the guardrail follows `on_error`. ## Lifecycle - **Upload** (global administrator): `POST /api/v1/admin/extensions` with the manifest, the module in base64 and the signature. The module is compiled and its imports checked before anything is stored. `activate: true` makes it the active version. - **Submit** (team administrator, `extension_submissions`): `POST /api/v1/admin/extensions/submissions` with an unsigned version for a team it administers. It is stored `pending_review` and runs nowhere. - **Review** (global administrator): approve with a signature by a trusted key over exactly the submitted manifest and module - approval cannot widen egress, secrets, host functions or limits - or reject. - **Activate, upgrade, roll back**: `POST .../{id}/activate {"version"}` points the plugin at an approved version (`""` deactivates it); `POST .../{id}/rollback` returns to the previous one. Every execution reads the active version live, so this applies on every replica without a restart. - **Inventory**: `GET /api/v1/admin/extensions` lists every version with its manifest, module digest and size, status, signature verdict (checked now against the trusted keys) and whether this replica has it loaded. Building it never runs plugin code. It also carries the `extensions` object: every ceiling of the YAML block under its own name (`max_module_bytes` ... `audit_retention_days`, `http.*`, `code_mode.*`), effective and read-only (it was named `limits` and held five of them). `trusted_keys` is served as fingerprints and `http.allow_loopback_http` and `http.allowed_private_cidrs` not at all: they widen what a plugin may reach, which stays boot trust. A plugin installed by the global administrator can serve every team. A plugin a team submitted belongs to that team and **runs only for its requests**; for any other team it does not apply. ## Teams: bindings, egress and secrets A team picks a plugin with a binding (`PUT .../{id}/bindings/{team}`, team administrators for the teams they administer): `enabled` and `egress`, which must be origins from the active version's signed manifest - a binding only narrows. Secrets are set per team (`PUT .../bindings/{team}/secrets/{name}`), only for names the manifest lists, write-only and encrypted with the provider keyring (AES-256-GCM bound to plugin, team and name). Without an enabled binding a plugin runs with no network at all. Removing a binding cuts its egress and secrets on the next call. ## Guardrail hook With `extension_guardrails` on, a guardrail can delegate to a plugin: ```yaml guardrails: - id: tickets name: Ticket references mode: block # or monitor: record the verdict, never enforce it stages: [input, output] provider: type: extension extension: ticket-guard on_error: block # block (default) or allow ``` The plugin gets the texts the guardrail would send an external service, after the gateway's own masking: ```json {"hook": "guardrail", "stage": "input", "texts": ["..."], "model": "alias", "team_id": "team-id"} ``` and answers `{"action": "allow"}`, `{"action": "deny", "reason": "label"}` or `{"action": "redact", "texts": ["...one replacement per text..."]}`. On the input stage a redaction rewrites the request text in place, before any external guardrail service sees it; a denial answers 400 `guardrail_blocked`. On the output stage (and in streamed windows under `guardrail_streaming`) the answer is not rewritten, so `deny` and `redact` both withhold it like a block, `logprobs` and stored Responses answers included ([Held rewrites](/docs/features/guardrails/#held-rewrites)). The contract is the same for WebAssembly and JavaScript plugins. A trap, a JavaScript `program_error`, a refused load or a malformed verdict follows `on_error`. What the client can force - text above `extensions.max_input_bytes`, a concurrency refusal, a deadline, the memory or output limit - always fails closed, whatever `on_error` says. ## Audit Every execution writes one row (`GET /api/v1/admin/extensions/executions`): runtime (`wasm` or `javascript`), hook, plugin, version and module digest, team, key, outcome (`ok`, `timeout`, `memory_limit`, `output_limit`, `trap`, `exit_nonzero`, `program_error`, `refused_concurrency`, `refused_team_concurrency`, `load_refused`, `runtime_disabled`...), verdict, duration, HTTP calls and refusals, output size. Never the input, the output or a secret. Records are kept `extensions.audit_retention_days` (default 30) and pruned in the background. Lifecycle actions (upload, submit, approve, reject, activate, bind, secret changes) go to the administrative audit as `extension.*`. ## Languages | Language | How | Status here | | --- | --- | --- | | Go | `GOOS=wasip1 GOARCH=wasm go build` with the SDK in `extensions/sdk/go/aigw` | Built and run by the test suite (`extensions/examples/go-guardrail` and the adversarial test plugin) | | TinyGo | The same Go source: `tinygo build -target=wasip1 -opt=z -no-debug -o plugin.wasm` (needs `wasm-opt` from binaryen) | Example built here with TinyGo 0.44.0 and wasm-opt 133 (1.2 MB module); kept as test data and run by the suite, including its redaction | | AssemblyScript | `extensions/sdk/assemblyscript/aigw.ts`; `asc assembly/index.ts -o plugin.wasm --runtime stub --use abort= -O3` | Example built here with AssemblyScript 0.28.20; the module is kept as test data and run by the suite | | Rust | `extensions/examples/rust-guardrail`: `RUSTFLAGS="-C target-feature=-reference-types" cargo build --release --target wasm32-wasip1` | Example built here with rustc 1.100.0 (64 KB module); kept as test data and run by the suite | | JavaScript | QuickJS-ng compiled to WebAssembly (`github.com/fastschema/qjs` v0.0.6, MIT), pinned by SHA-256 `88fcbeead33cca3ec8394feb0fb3eec8047ec9ac5062aba7a63799cee11989b7`, under `extension_javascript` | Run by the suite; used by [MCP code mode](/docs/features/mcp-code-mode/) and by [JavaScript plugins](#javascript-plugins) (`extensions/examples/javascript-guardrail`, run by the suite) | | Python, ML libraries, own databases | Out of process: an HTTP service called by the [generic guardrail API](/docs/features/guardrails/#generic-guardrail-your-own-api) (`provider.type: generic_api`); see [Out-of-process plugins](#out-of-process-plugins-python-and-ml) | Example `extensions/examples/python-guardrail`, run in a container against the gateway binary by an opt-in test | Native shared-library plugins are not supported: they need CGO, do not work on Windows, require the exact toolchain and dependencies and cannot be unloaded. ## Out-of-process plugins (Python and ML) Python is not run inside the sandbox. What Python brings - ML models, PII libraries, a team's own database - needs a full interpreter, native extensions and memory well beyond a guardrail call, so it runs as your own HTTP service and the gateway calls it with the existing [generic guardrail API](/docs/features/guardrails/#generic-guardrail-your-own-api). Nothing new is added to the gateway: no flag, no protocol, no process started by the gateway. `extensions/examples/python-guardrail` is a complete service with the same rules as the sandbox examples (deny the code name, redact `TCK-123…` tickets), using only the Python standard library, with a `Containerfile` pinned by digest (Python 3.14.10 on Alpine), a non-root user and a health check. Replace its `check(texts)` with your own logic. ```bash cd extensions/examples/python-guardrail IMAGE=$(docker build -q -f Containerfile .) GUARD_API_KEY=change-me docker run -d --name python-guardrail -p 127.0.0.1:8080:8080 -e GUARD_API_KEY "$IMAGE" ``` | Variable | Default | Meaning | | --- | --- | --- | | `GUARD_PORT` | `8080` | Listen port | | `GUARD_HOST` | `0.0.0.0` | Listen address | | `GUARD_API_KEY` | empty (no check) | When set, a request without this value in `x-api-key` gets `401` | | `GUARD_MAX_BODY_BYTES` | `4194304` | Larger requests get `413` | | `GUARD_DELAY_SECONDS` | `0` | Test hook only: wait before answering | Point a guardrail at it; the gateway sends the key from `api_key_env` as `x-api-key`: ```yaml guardrails: - id: python-policy name: Python policy mode: block stages: [input] provider: type: generic_api endpoint: http://python-guardrail:8080/check api_key_env: GUARD_KEY # the same value as GUARD_API_KEY apply_redactions: true # apply the redacted texts (default false: advice only) timeout: 2s # this check's deadline, 100ms-30s (default 5s) on_error: block ``` **What it receives and answers.** `POST /check` with `{"input_type": "request" | "response", "texts": [...], "request_data": {"user_api_key_team_id", "user_api_key_alias", "user_api_key_end_user_id"}, "model", "call_id", "trace_id"}` (plus `additional_provider_specific_params` when `params` is set), already masked by the local detectors. It answers `200` with `{"action": "BLOCKED"}`, `{"action": "NONE"}` or `{"action": "GUARDRAIL_INTERVENED", "texts": [...]}`. `GET /health` answers `200 {"status": "ok"}` for the container health check or a Kubernetes probe; it never reads texts. The service logs method, path and status only, never texts or headers. **Redaction.** The example answers `GUARDRAIL_INTERVENED` with the redacted texts, as the generic API defines. By default the gateway treats them as advice and lets the request through unchanged. With `apply_redactions: true` it applies them: on input each text replaces the one sent, in place (roles, tool calls and structure unchanged); on a non-streaming answer (stage `output`) they replace the visible text, and a change to reasoning, a transcript or a tool call, an answer with token logprobs or a stored Responses answer withholds the answer ([Held rewrites](/docs/features/guardrails/#held-rewrites)). The answer must carry exactly one string per text sent, in the same order, each at most twice the original plus 4,096 bytes; anything else is a failure that `on_error` decides. A streamed window cannot be rewritten, so a redaction ends the stream like a block. Use `on_error: block` with it: with `allow`, a check that does not finish lets the original through. See [Generic guardrail](/docs/features/guardrails/#generic-guardrail-your-own-api). **Timeouts and failures.** Each check has a deadline in the gateway: the guardrail's `timeout`, from `100ms` to `30s`, default `5s`. The deadline cancels the call. A service that answers later, refuses the connection, answers a status other than `200` or an unknown action is a failure, and `on_error` decides: `block` (the default) answers `503` and nothing reaches the provider; `allow` lets the request through and logs the failure. Guidance: - Keep the service well under the deadline (a p99 of a few hundred milliseconds), and give your own model or database calls a deadline shorter than the guardrail's `timeout`, so a slow dependency becomes a clear answer instead of a gateway timeout. - Choose `on_error` per guardrail: `block` for policy and compliance checks, `allow` only where availability matters more than the check. - Run more than one replica behind a Service and use `/health` for readiness; one stopped replica then costs no failed checks. - On the output stage, answers longer than 100,000 characters are withheld (`502`) without calling the service, whatever `on_error` says. **Tested here.** `TestPythonGuardrailExampleOverGenericAPI` (`internal/deploytest`, opt-in with `GATEWAY_T058_PYTHON_GUARDRAIL=1`, needs Docker) builds the image, runs it in containers and puts the real gateway binary, with PostgreSQL, in front of it: deny (400), redaction in the service answer with the request passing unchanged without `apply_redactions` and redacted with it, on the request and on the answer, allow, a service slower than the deadline (the default 5 s and a guardrail `timeout: 1s`) and a stopped service, each failure with `on_error: block` (503) and `allow` (200). All its containers and its image are removed afterwards. ## Cost of a call Instantiate plus call of a guardrail, measured on an Apple M4 Pro (`go test ./internal/extensions -bench Guardrail`): | Plugin | 1 KiB of text | 64 KiB of text | | --- | --- | --- | | Go example (standard toolchain, 5 MB module; Go runtime start-up, `encoding/json`, `regexp`) | 3.1 ms | 69 ms | | AssemblyScript example (10 KB module; substring check) | 0.10 ms | 3.9 ms | | Rust example (64 KB module; substring check) | 0.12 ms | 1.3 ms | | TinyGo build of the Go example (1.2 MB module; `encoding/json`, `regexp` redaction) | 0.82 ms | 15 ms | | JavaScript example (1 KB source on QuickJS; `RegExp` redaction) | 1.9 ms | 25 ms | The standard Go toolchain's WebAssembly start-up dominates small calls; for hot paths prefer Rust or AssemblyScript, or TinyGo when the plugin is Go (about 4x faster than the standard toolchain on the same source). A JavaScript plugin pays a fresh QuickJS instance and a parse of its source on every call (about 1.7 ms before any work) and then runs interpreted: the 64 KiB case is the regular expression replacing about 3,000 tickets. A JavaScript program with three host calls runs in about 1.3 ms. ## Configuration ```yaml extensions: trusted_keys: [] # {id, public_key (base64 Ed25519)}; boot trust only max_module_bytes: 16777216 # 1024-67108864 max_memory_pages: 1024 # 1-16384 pages of 64 KiB per call max_timeout_ms: 1000 # 1-30000 per call max_input_bytes: 1048576 max_output_bytes: 1048576 max_concurrency: 32 # calls per replica team_max_concurrency: 4 # calls per team per replica audit_retention_days: 30 # execution records http: max_calls: 4 timeout_ms: 2000 max_response_bytes: 262144 allow_loopback_http: false allowed_private_cidrs: [] ``` Every value is a ceiling: a plugin manifest may ask for less, never more. `0` takes the default. | Key | Default | What it does | | --- | --- | --- | | `extensions.trusted_keys` | `[]` | Ed25519 keys (`id`, base64 `public_key`) that verify plugin signatures; removing one makes every version it signed refuse to load | | `extensions.max_module_bytes` | `16777216` | Largest uploaded module, 1024 B–64 MiB | | `extensions.max_memory_pages` | `1024` | A plugin's linear memory per call, in 64 KiB pages, 1–16384 | | `extensions.max_timeout_ms` | `1000` | Deadline of one call, 1–30000 ms; the call is interrupted when it passes | | `extensions.max_input_bytes` | `1048576` | Largest input handed to the sandbox, 1 KiB–16 MiB | | `extensions.max_output_bytes` | `1048576` | Largest output a plugin may return, 1 KiB–16 MiB | | `extensions.max_concurrency` | `32` | Calls one replica runs at once, 1–4096; past it a call is refused at once and counted, never queued | | `extensions.team_max_concurrency` | `4` | Calls of one team per replica, 1–4096 and at most `max_concurrency` | | `extensions.audit_retention_days` | `30` | How long execution records are kept, 1–3650 days | | `extensions.http.max_calls` | `4` | `http_call` host calls one plugin call may make, 1–64 | | `extensions.http.timeout_ms` | `2000` | Deadline of one `http_call`, 100–30000 ms | | `extensions.http.max_response_bytes` | `262144` | Largest `http_call` response body, 1 KiB–16 MiB | | `extensions.http.allow_loopback_http` | `false` | Lets `http_call` reach a loopback HTTP address, for local testing | | `extensions.http.allowed_private_cidrs` | `[]` | Up to 16 private networks `http_call` may reach; the destination must also be in the signed manifest and the team binding | Restart to apply. The `code_mode` sub-block is described in [MCP code mode](/docs/features/mcp-code-mode/). ## Console **Settings → Extensions** shows the runtime (trusted key fingerprints, every ceiling including the HTTP and code mode ones, this replica's outcome counters), each plugin with its versions (each marked WebAssembly or JavaScript), signature verdicts, load status and team bindings, and the recent executions with their runtime. Global administrators upload, approve with a signature, activate and roll back; team administrators submit versions, bind plugins to their teams and set write-only secrets. The upload form takes a `.wasm` module or, when the manifest says `"runtime": "javascript"`, a `.js` file that it sends as `source`. Viewers and operators read. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `POST /api/v1/admin/extensions/{id}/activate` | Makes an approved version the active one (install, upgrade or rollback), or deactivates the plugin | | `POST /api/v1/admin/extensions/{id}/rollback` | Reactivates the previous version | | `POST /api/v1/admin/extensions/{id}/versions/{version}/approve` | Approves a pending submission with the reviewer's signature by a trusted key | | `POST /api/v1/admin/extensions/{id}/versions/{version}/reject` | Rejects a pending submission | | `PUT /api/v1/admin/extensions/{id}/bindings/{team}` | Binds a plugin to a team and sets its allowed egress | | `DELETE /api/v1/admin/extensions/{id}/bindings/{team}` | Removes a team's binding and its secrets | | `PUT /api/v1/admin/extensions/{id}/bindings/{team}/secrets/{name}` | Stores a write-only team secret for the plugin, encrypted | | `DELETE /api/v1/admin/extensions/{id}/bindings/{team}/secrets/{name}` | Removes a team's secret | # Cache **Last updated:** 2026-11-12T13:19:55-03:00 (UTC-3) Repeated questions cost the same every time. The cache returns the answer already obtained without calling the provider. It is isolated so that one team never receives another team's answer, and authorization and limits apply before it. ## What exists | Feature | What it does | Flag | Learn more | |---|---|---|---| | **Exact cache** | Same question, same parameters: same answer, for a TTL. Isolated by identity, team and credential | `exact_cache` | [Exact cache](/docs/features/exact-cache/) | | **Semantic cache** | Answers questions with the same meaning by comparing embeddings; exact or by similarity | `semantic_cache` | [Semantic cache](/docs/features/semantic-cache/) | | **Backends** | Per-process memory, or Redis and Memcached shared across replicas, switchable from the console | `distributed_exact_cache`, `cache_backend_management` | [Backends](/docs/operate/cache-backends/) | | **Chat cache on Redis** | Keeps the chat answer cache in the Redis backend instead of PostgreSQL, shared by every replica on the namespace | `distributed_semantic_cache` | [Semantic cache](/docs/features/semantic-cache/#shared-across-replicas-on-redis) | | **Client control** | `Cache-Control: no-store` or `{"cache": {"no-cache": true}}` | (always) | [Semantic cache](/docs/features/semantic-cache/) | | **Status and purge** | Hit and miss panel, backend health check and per-model purge | `exact_cache` | [Exact cache](/docs/features/exact-cache/) | ## Guarantees - **Before the cache:** authorization and RPM apply; a hit does not bypass revocation or limits. - **In PostgreSQL:** the semantic cache content is encrypted. - **In Redis and Memcached:** the exact cache content is also encrypted and tamper-proof, and so is the chat cache when it lives in Redis. Managed bearer authentication has a separate optional [credential cache](/docs/features/managed-key-cache/). Its snapshots, expiry proof and security constraints do not cache model responses or require a response-cache backend. # Exact cache for embeddings and moderation **Last updated:** 2026-11-21T15:06:38-03:00 (UTC-3) Indexing the same documents again, or moderating the same text twice, doesn't have to cost another call. The exact cache returns the response already obtained for an **embeddings** or **moderations** request that is identical, byte for byte, and made with the same key. Flag: `exact_cache`. The cache is used only when all three agree: the flag is on, the alias has the policy on and the request carries `X-Gateway-Cache: allow`. For chat responses, use the [chat answer cache](/docs/features/semantic-cache/), which is exact without an embeddings alias; `exact_chat_cache` adds tenant-prefixed, normalized keys, per-request lifetimes and zero-cost hits to it ([exact chat cache rules](/docs/features/semantic-cache/#exact-chat-cache-rules)). ## How to turn it on ```yaml features: embeddings: true exact_cache: true models: - id: embedding-default capabilities: [embeddings] cache: enabled: true ttl: 30s # 1 s to 5 min targets: - {provider: compatible-provider, model: upstream-embedding-id} ``` | Key | Default | What it does | | --- | --- | --- | | `models[].cache.enabled` | `false` | Turns the exact cache on for this alias; needs the `exact_cache` flag | | `models[].cache.ttl` | required in a `cache` block | How long an entry is served, 1 s to 5 min | - The alias must have a single target and the `embeddings` or `moderations` capability. - The policy can also be edited in the console's model editor and through `PUT /api/v1/admin/models/{id}`, with versioning, audit and revert to the YAML. - With [plans](/docs/features/entitlements/), the team needs the `exact_cache` entitlement. ## How to use it ```bash curl -i http://localhost:8080/v1/embeddings \ -H "Authorization: Bearer $GATEWAY_API_KEY" \ -H 'Content-Type: application/json' \ -H 'X-Gateway-Cache: allow' \ -d '{"model": "embedding-default", "input": "test text"}' ``` - The response carries `X-Gateway-Cache: hit` or `miss`. Without that header, the request did not go through the cache. - The request must be **identical**: different whitespace, property order or parameters count as a different request. - **Moderation with images:** only inputs that carry their whole content are cacheable: text, and images as data URLs. A request with an image `https` URL always reaches the provider and carries no `X-Gateway-Cache` header, because the image behind a URL can change while the request stays byte for byte the same. Part types other than `text` and `image_url` are not cached either. See [Moderation](/docs/features/moderations/). - Cached responses come with `Cache-Control: private, no-store`, so no proxy or browser stores them. ## Isolation and security - **Everything is checked before the cache:** key, scopes, team policy, RPM, models and capability. A hit still counts toward RPM, and revoking the key denies access even when the response is stored. - **Isolated per key:** the cache identity includes the key, the team, the credential presented, the alias, the configuration and the provider credential. Nothing is shared between keys or teams. - **A configuration change** or a change to the provider credential invalidates the entries. - The cache does not deduplicate concurrent calls. ## What is stored Only `200` responses, as complete and valid JSON, without `error`, with `data` (embeddings) or `results` (moderations), up to the configured response limit (default 64 KiB). Never stored: errors, truncated responses, streams, responses with `Vary: *`, a `Vary` the key does not cover (below), `Cache-Control` or `Pragma`, an authentication challenge (`WWW-Authenticate` and similar), `Authorization`, `Cookie`, `Set-Cookie2`, `Content-Encoding`, `Content-Range` or trailers, and requests with `Cache-Control`, `Pragma`, `Cookie` or `Range`. There is no revalidation and no stale response. A `Set-Cookie` on the response does not prevent storing it. Providers set cookies for their own edge (OpenAI sets one on every response), and the gateway never sends a provider a client's cookie or one the provider set: it keeps no cookie jar, a client's `Cookie` is never forwarded, and `Cookie` can be neither a forwarded client header nor a fixed connection header. The only `Cookie` a provider can receive is a connection whose own credential is configured that way (`auth.type: header` with `header: Cookie`), and that value is the connection's credential, already part of the cache identity. So the answer cannot depend on a per-client or provider-set cookie. The provider's cookie is never passed on to the client, on a miss or a hit, and is not stored: only the body and its `Content-Type` are. A `Vary` on the response does not prevent storing it when the key already covers every header it names. OpenAI answers every embeddings call with `Vary: Origin`; before this rule nothing from OpenAI was ever stored, and every lookup was a `miss`. A provider's answer can depend only on the request the gateway sent it, and the only client values that request carries are the body, the query and the [forwarded client headers](/docs/features/providers/#forwarded-client-headers), all part of the key (in memory and in the shared backend alike); everything else is the connection's configuration and credential, part of the cache identity. So a `Vary` naming a header the gateway did not send (`Origin`, which it never sends unless an operator forwards it) or a forwarded client header is stored. Still refused: `Vary: *`, and a `Vary` naming a header the gateway itself set on that call (such as `Content-Type`), whose value the key does not hold. The content stays in process memory (or in the [shared backend](/docs/operate/cache-backends/)). It does not go to PostgreSQL, logs, telemetry or metrics. The request and trace IDs are always those of the current request. **Cost:** a hit records no new tokens, and [valuation](/docs/features/usage-valuation/) marks the event as `unknown/cache_hit`, without making up savings. ## Capacity (in-memory backend) | Resource | Default or policy | | --- | --- | | Entries | Default 256, configurable 1–256, with LRU eviction | | Size per entry | Default 64 KiB, configurable 256–65536 bytes | | Accounted memory | Default 32 MiB, configurable 2048–33554432 bytes | | TTL | Required 1 s to 5 min per alias; no backend default | | Scope | One process; each replica has its own cache | Restarting the process empties the memory cache. Integer zero selects the existing capacity default. The model editor’s `30s` creation preset does not supply a missing YAML/API TTL. Capacity and TTL constraints are shared by the existing backend and console consumers; see [parameter definitions](/docs/reference/parameter-registry/). To share the cache across replicas, select an optional compatible remote backend as described in [cache backends](/docs/operate/cache-backends/). ## Monitoring and clearing **Providers → Exact response cache** shows limits, occupancy, counters and the alias policies, and clears the cache after confirmation. | Endpoint | Permission | | --- | --- | | `GET /api/v1/admin/cache` | `providers:read` (admin, operator, viewer) | | `DELETE /api/v1/admin/cache` | `providers:manage` (admin, operator), with CSRF | With the in-memory backend behind a load balancer, status and clearing reach the replica that answered (`process_instance_id` tells you which one). The counters are not meant for billing. With `metrics_endpoint`, `/metrics` adds the fleet-wide view: every lookup by result (`hit`, `miss`, `bypass`) and the reason of a bypass, what became of each miss's answer (`stored`, or `skipped` with the rule that refused it), the shared backend's calls by operation with their latency and errors, and which cache serves (`memory` or `distributed`). The answer's `X-Gateway-Cache` header says only `hit` or `miss`, and is absent on a bypass; the series say why. A cache that answers `miss` every time while `gateway_exact_cache_stores_total{result="skipped"}` grows is refusing what the provider returns, and the `GatewayExactCacheNotStoring` alert fires. Series, reasons and queries: [exact cache series](/docs/features/observability/#exact-cache-series). ## See also - [Semantic cache](/docs/features/semantic-cache/): chat responses. - [Cache backends](/docs/operate/cache-backends/). - Reference: [RFC 9111](https://www.rfc-editor.org/rfc/rfc9111.html). This cache is explicit application memoization, not a transparent HTTP cache. ## Conditional target eligibility [Conditional routing](/docs/features/conditional-routing/) runs before cache lookup. Exact identity privately includes the eligible target set; a warm entry cannot serve an ineligible caller/tag context. This preserves the existing single-raw-target embeddings/moderations profile and does not enable multi-target Chat caching. # Chat answer cache **Last updated:** 2026-11-21T09:54:10-03:00 (UTC-3) A chat question that was already answered can come back from the cache, without calling the provider. The comparison is **exact** or, with an embeddings alias, **by meaning** of the user's last message: "what is the capital of France?" and "tell me the capital of France" get the same answer. Flag: `semantic_cache`. Isolation is strict: only the final question is compared by meaning; the rest of the conversation must be identical. And the cache is separated per key (or per team). ## How to turn it on ```yaml features: chat_completions: true embeddings: true semantic_cache: true models: - id: gpt targets: [{provider: openai, model: gpt-4o-mini}] semantic_cache: enabled: true ttl: 1h # 1s to 24h embedding_model: nomic # without it, the cache is exact only threshold: 0.9 # required with embedding_model; no default scope: key # key (default) or team max_input_chars: 2000 # longer questions only match exactly - id: nomic capabilities: [embeddings] targets: [{provider: llama, model: nomic}] ``` `semantic_cache.enabled` turns the alias's cache policy on or off without removing it. The TTL is required whenever the policy block is present; `1h` is the console’s creation preset, not a gateway default. With an embeddings alias, the similarity threshold must be finite and between `0.5` and `1`; its editor preset is not a backend default. Scope defaults to `key`, and omitted or zero `max_input_chars` selects `2000` (maximum `8000`). These constraints are shared with the existing backend and console consumers; see [parameter definitions](/docs/reference/parameter-registry/). The same fields are in the API (`PUT /api/v1/admin/models/{id}`) and in the model editor in the console. In **Providers**, the "Chat answer cache" panel shows the backend, the policies and the live entries, and deletes an alias's entries. ## How an answer is found 1. The last message must be from the user and contain only text. A conversation that ends in a tool result, or a question with an image, proceeds without the cache. 2. The **bucket** is an HMAC of: - the scope (key, or team with `scope: team`); - the alias and the configuration of the alias and of the embeddings model; - the connection of every provider those two aliases name (protocol, base URL, API version, fixed headers and auth type, never the credential), so repointing a provider never serves what the previous endpoint answered; - the alias's output guardrails; - every parameter (except `stream`) and every previous message. Changing any of them leads to a different bucket. 3. Within the bucket, the same question matches without an embedding. 4. With `embedding_model`, the question is embedded as the calling key itself, through the normal `/v1/embeddings` route: quota, ledger and logs see the call. The most similar entry with cosine similarity at or above `threshold` wins, among the 500 newest in the bucket. 5. If the key cannot call the embeddings alias, or if the embedding fails, the lookup is exact only and the chat proceeds normally. Input guardrails, quota and usage recording run before the lookup. A blocked prompt never receives an answer from the cache. ## Response | Header | Value | |---|---| | `X-Gateway-Cache` | `hit` or `miss` (absent when the policy does not apply) | | `X-Gateway-Cache-Kind` | `exact` or `semantic` | | `X-Gateway-Cache-Similarity` | similarity of the semantic hit, to 4 decimal places | | `X-Gateway-Provider` | provider that generated the stored answer | - **id:** a hit gets a new `id` and `created`. - **Stream:** with `stream: true`, the answer comes back as SSE chunks, with `usage` when `stream_options.include_usage` asks for it, and ends in `[DONE]`. - **Usage:** the recorded usage has no new tokens, and valuation uses the reason `cache_hit`. Only 200 responses with a non-empty `choices`, up to 256 KiB, read to the end, are stored. With an output guardrail, the already-masked response is stored, the same one the client received. A **streamed** response is stored too. The gateway reassembles the `chat.completion` from the chunks the client received: text, `reasoning_content`, tool calls with concatenated arguments, `finish_reason` and `usage`. It is only stored if the stream ends in `[DONE]`, with every choice closed and no field it cannot reassemble (`refusal`, audio, logprobs). Aliases with an output guardrail do not store streams: the stream does not go through the mask, and the entry could later be served as JSON without it. ## Client control | Request | Effect | |---|---| | `Cache-Control: no-cache` | does not look up, but stores the new answer | | `Cache-Control: no-store` | looks up, but does not store | | `X-Gateway-Cache: bypass` | neither looks up nor stores | | body `"cache": {"no-cache": true}` or `{"no-store": true}` | the field is removed before the provider | ## Storage - **With PostgreSQL:** - entries live in `gateway_semantic_cache` and apply to every replica; - the vector is `REAL[]` and the dot product is computed in SQL; - the answer is encrypted with AES-GCM, with a key derived from `admin.session_key_env` and the bucket as associated data; - the database stores neither the question nor the answer in readable form; - replicas with different secrets cannot open each other's entries and treat that as a miss; - an answer is written after the response, off the request path, with at most 16 writes in flight per process. When all 16 are busy (a slow database), the answer is not stored and the write is counted as `dropped`; on shutdown the process waits up to 6 seconds for the writes in flight; - each write trims the bucket to its newest 500 entries and removes up to 100 expired ones, skipping rows another replica is already deleting, so concurrent writers never wait on or deadlock with each other. - **With Redis** (`distributed_semantic_cache`): see [Shared across replicas on Redis](#shared-across-replicas-on-redis) below. PostgreSQL then carries no chat cache reads or writes. **Operations:** - `GET /api/v1/admin/semantic-cache` (`providers:read`) and `DELETE /api/v1/admin/semantic-cache?model=` (`providers:manage`). - Metric `gateway_semantic_cache_total{model,result}`, with `result` = `exact_hit`, `semantic_hit`, `miss`, `bypass`, `store`, `dropped`, `error` or, on Redis only, `skipped` (lookup not attempted while the breaker below is open). - `?model=` takes any name a configured model serves. Answers are stored under the served name: the model, the canonical model of an `alias_of` name, or the concrete name a wildcard alias resolved (`openai/gpt-4o` through `openai/*`). Purging `openai/gpt-4o` removes that name's answers; purging `openai/*` (what the console sends) removes every name under that prefix, including names a more specific alias under the same prefix served. A name no configured model serves answers 404 `model_not_found`: it would purge nothing. To remove the answers of a model you deleted from the configuration, purge without `?model=`. ## Exact chat cache rules The exact chat cache is this cache without `embedding_model`: an identical conversation gets the stored answer. The operator flag `exact_chat_cache` (off by default, requires `semantic_cache`) applies stricter rules to every chat cache policy, exact or semantic, instead of adding a second cache: ```yaml features: semantic_cache: true exact_chat_cache: true chat_cache_cross_tenant: false # share past the team; off by default models: - id: gpt semantic_cache: enabled: true ttl: 1h # the longest an answer is kept; clients can only shorten it scope: team # key (default) or team # share: organization # or all; only with chat_cache_cross_tenant ``` - **The key begins with the organization and team.** With `scope: key` it is organization, team and key; with `scope: team`, organization and team. Answers never cross teams unless the policy sets `share` **and** the operator flag `chat_cache_cross_tenant` is on: `share: organization` serves every team of the caller's organization, `share: all` every organization. A key without an organization (organizations off, or a team in none) is not one tenant: `share: organization` keeps it within its scope. Without the flag `share` is saved but ignored. A shared bucket also shares its trimming (the newest 500 entries) and tells one tenant, through `X-Gateway-Cache: hit`, that another asked the same thing: share only between tenants that trust each other. - **The key covers the whole normalized request:** every parameter that reaches the provider (model configuration, `tools`, `tool_choice`, `response_format`, `temperature`, `seed`, `max_tokens` and the rest), every earlier message, and the last message's fields besides its text (`name`, for example). Object keys are sorted and insignificant whitespace removed at every level, so two requests that differ only in key order or spacing share an entry; numbers keep their exact text. A value with a repeated member name, or with a surrogate escape, is keyed by its exact bytes instead, since a provider may read either duplicate. Without an embedding model the last message's content itself is in the key, so text parts never match one string joined by newlines. Only `stream` and `stream_options` are left out, so a streamed and a JSON request share an entry. The provider connections, output guardrails and forwarded client headers stay in the key as before. Turning the flag on starts a new key space: entries stored before it are not read (they expire with their TTL). - **Per-request lifetime, capped by the admin:** `X-Gateway-Cache-TTL: 30` (seconds, up to 86400, or a Go duration such as `2m`) or the body field `"cache": {"ttl": 30}` stores the answer for that long, never longer than the alias `ttl`. An unreadable value is ignored and the alias `ttl` applies. `Cache-Control: no-cache` / `no-store`, `X-Gateway-Cache: bypass` and `cache.no-cache` / `cache.no-store` work as described in [client control](#client-control). - **Streams are replayed, not refused:** a streamed answer is stored when the stream ends cleanly and every part can be reassembled, as described in [response](#response); a hit on a `stream: true` request is replayed as chunks ending in `[DONE]`. Streams on an alias with an output guardrail are not stored. - **A hit costs nothing and is visible:** the usage event has the cache kind (`cache_kind`, the `cache_kind` analytics dimension, the request journey), no tokens, and a **known valuation of zero** with reason `cache_hit` (without the flag a hit is `unknown/cache_hit`). It still counts toward RPM, since admission runs before the lookup, and the gateway logs `chat_cache_hit` with the request ID, alias, kind, provider and whether it was a stream (never the question or the answer). The `share` field is in YAML, the model API (`semantic_cache.share`) and the console model editor (**Cache sharing past the team**). Both flags are operator controls. ## Shared across replicas on Redis PostgreSQL already shares the cache between replicas that use the same database and `admin.session_key_env`. When you run Redis for the [exact cache](/docs/operate/cache-backends/), you can keep the chat cache there instead, so the database carries no cache traffic and every replica on the same Redis namespace shares hits. Flag `distributed_semantic_cache` (runtime, operator control, off by default). It requires `semantic_cache` and a **Redis** `cache_backend`; memory and Memcached are refused at load and on every flag or backend change. ```yaml features: semantic_cache: true distributed_semantic_cache: true cache_backend: backend: redis namespace: gateway_production url_env: GATEWAY_CACHE_URL # rediss://user:password@host:6380/0 key_env: GATEWAY_CACHE_KEY # base64 of 32 random bytes, the same on every replica timeout: 250ms tls: {enabled: true} ``` Nothing else changes: the alias policy (`semantic_cache` on the model, TTL, threshold, scope, `max_input_chars`), client controls, headers, valuation and guardrail rules are the same as with PostgreSQL. The connection, TLS, ACL and console management are those of the [cache backend](/docs/operate/cache-backends/); a console change of backend moves the chat cache with it. `distributed_exact_cache` is independent: either can be on without the other. **How it is stored.** Redis has no similarity search without a module (the stock `redis:7` image answers `unknown command 'FT._LIST'`), so the gateway keeps its own small index per bucket: | Key | Content | TTL | |---|---|---| | `:sc:e:` | one answer: AES-GCM sealed body (up to 256 KiB), provider, expiry and the question's float32 vector | the alias TTL | | `:sc:i:` | per bucket and vector size, a list with one sealed record per question: hash, expiry and an int8 copy of the vector with its rounding-error norm | extended to the longest TTL in it | | `:sc:epoch`, `:sc:alias:` | random generations; a purge replaces one | none | - Every name is an HMAC and every value is sealed with a key derived from `cache_backend.key_env` and the key's own name (associated data included), so Redis sees neither questions, answers, aliases nor teams, and a value copied under another name does not open. Replicas with a different `key_env` compute different buckets and names: a miss, never an error. - A lookup is at most four bounded round trips: the two generations, the exact answer, then (after the embedding) the bucket list and one pipelined read of up to 8 candidates. The int8 copy only bounds each candidate's similarity from above; the candidates are re-scored against their float32 vectors and an answer is served only when that exact score reaches `threshold`, as in PostgreSQL. The int8 copy is four times smaller than float32: measured on local Redis 7.4, a full bucket of 500 questions of 1,536 dimensions is a 0.79 MB read (1.1 ms) instead of 3.1 MB (1.9 ms). - A store writes the answer and appends its record with one `RPUSH`/`LTRIM` script, so concurrent replicas writing to a busy bucket never conflict. The list keeps the newest 500 records, or fewer when their vectors would make one read exceed 1 MiB (about 325 for 3,072 dimensions, 124 for 8,192). An older question leaves the list but still matches exactly until its TTL. Vectors of another size (an embeddings alias that falls back to a provider with other dimensions) go to their own list, so each list keeps its own bound. - Expiry is checked against the sealed timestamp as well as the Redis TTL, so a server that ignores TTLs never serves an expired answer. **When Redis fails.** The request never fails because of the cache. The first operation of a lookup decides: if Redis does not answer within `cache_backend.timeout`, the request goes on as a **miss** (`X-Gateway-Cache: miss`), spends no embedding and stores nothing. The failure counts as `result="error"` and logs `semantic_cache_backend_unavailable` (error class only, never the endpoint) at most once per 30 seconds with the number suppressed. For the next 2 seconds the process skips Redis altogether (counted as `skipped`); then one request probes it again, so a black-holed server costs at most one timeout per 2 seconds. Only lookups open this breaker: a failed background write, a cancelled client request and one key the gateway cannot read (a reply past the frame bounds, a key of another type) are counted and logged but leave the cache on for every other bucket. A boot with the flag on checks the connection, read, write and list primitives on keys of its own and refuses to start if they fail, like `distributed_exact_cache`. Turning the flag on at runtime does not run that check: failures show up as misses and `error` counts. **Status and purge.** `GET /api/v1/admin/semantic-cache` reports `backend: redis`, `entries_known: false` and `entries: -1` per alias: there is no reliable inventory without scanning the server. A purge replaces the alias generation (or the global one with no `?model=`); every replica stops reading the old answers on its next lookup and they expire with their TTL; the response says `purged: -1`. A purge also reaches the backend the flag does not select, best effort, so switching the flag later does not bring back answers you purged; if that second purge fails the response says `inactive_purge: failed` (the answers there expire with their TTL). On Redis the generation belongs to the declared models[] entry, so purging one concrete name of a wildcard alias also invalidates the other names that wildcard served (PostgreSQL removes only that name); purging `openai/*` rotates that wildcard and every declared entry under the prefix, matching the PostgreSQL prefix delete. A Redis failure part way through answers 503; repeat the purge. **Capacity is the server's.** The gateway bounds each value (an answer of up to 256 KiB plus its vector, a bucket list of up to 1 MiB) and each read, but not the number of buckets: every combination of scope, history and parameters is its own bucket and lives up to the alias TTL (24 hours at most). Set `maxmemory` with `volatile-lru` (or `allkeys-lru`) on the Redis server: every cache key has a TTL except the generations, and an evicted generation only turns its answers into misses. With `noeviction`, a full server also stops the exact cache's writes. These keys are outside the exact cache's slot budget (`max_entries`, `max_bytes`), which still bounds only the exact cache. **Trust.** Values are authenticated, so a client of the same Redis without the key cannot plant or alter an answer; tampering only produces misses. Redis remains trusted infrastructure, as for the exact cache: someone who can write to it can delete entries, fill it, or put back an old generation to make a purged answer reachable again until it expires. Use TLS, an ACL limited to the namespace prefix (commands `GET`, `GETRANGE`, `SET`, `RPUSH`, `LTRIM`, `LRANGE`, `PTTL`, `PEXPIRE`, `EVAL`/`EVALSHA`) and a private network. **Differences from PostgreSQL, all on the safe side.** When more than 8 candidates bound above the best exact score, the best of the 8 read is served (still at or above `threshold`, maybe not the highest). Buckets of very large vectors compare fewer than 500 questions. Counts are unknown. The answer is served with the same headers; `X-Gateway-Cache-Similarity` is the exact float32 score. **Upgrade.** Turning the flag on starts with an empty shared cache; PostgreSQL entries are not copied and stay there until they expire. Turning it off goes back to PostgreSQL; Redis entries expire with their TTL. ## Threshold calibration Absolute similarity depends on the embeddings model. Measured with nomic-embed-text v1.5 (llama.cpp): | Pair | Similarity | |---|---| | "What is the capital of France?" ~ "what's the capital city of France?" | 0.973 | | "How do I reverse a list in Python?" ~ "How can I reverse a Python list?" | 0.978 | | "What is the capital of France?" ~ "Tell me the capital of France" | 0.956 | | "Is it safe to take ibuprofen with alcohol?" ~ "... paracetamol ..." | 0.831 | | "Convert 10 USD to EUR" ~ "Convert 100 USD to EUR" | 0.823 | | "What is the weather in Paris today?" ~ "... London ..." | 0.798 | | "What is the capital of France?" ~ "... Germany?" | 0.767 | | "Qual é a capital da França?" ~ "What is the capital of France?" | 0.746 | With this model, 0.9 separates paraphrases from pairs that change the meaning: a different medicine, a different amount, a different city. Even so, a high similarity does not prove the answer fits. For questions whose meaning depends on a number or a name, use the exact cache (without `embedding_model`). When you change the embeddings model, measure again with the similarity header. ## Limits - On aliases with an output guardrail, only non-streaming responses populate the cache. - Chat Completions only. Responses, Messages and native Gemini proceed without the cache. - Each miss with `embedding_model` costs one extra embedding, which counts toward the key's RPM and quota. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `DELETE /api/v1/admin/semantic-cache` | Deletes every chat cache entry, or one alias's with `?model=` | ## See also - [Exact cache](/docs/features/exact-cache/): embeddings and moderation. - [Cache backends](/docs/operate/cache-backends/). - [Valuation](/docs/features/usage-valuation/): how hits show up in cost. ## Conditional aliases If the answer alias or embedding alias declares [target conditions](/docs/features/conditional-routing/), semantic answer caching is bypassed. This preserves the routing boundary instead of claiming unproved cross-condition hits. Existing unconditional profiles remain unchanged; auto-router example-vector memoization has its own bounded private context namespace. # Observability **Last updated:** 2026-11-27T06:40:15-03:00 (UTC-3) When something goes wrong, the question is always the same: what happened to *this* call? The gateway records every request with its `request_id` and W3C trace, shows aggregate usage, and warns you when a limit is getting close. Prompts and responses never go to logs or telemetry. ## What exists | Feature | What it does | Flag | Learn more | |---|---|---|---| | **Request logs** | Every call with key, team, model, provider, status, tokens, latency, and cost; filters, columns, live tail, and CSV | `request_logs`, `request_log_live_tail`, `request_journey`, `agent_sessions` | [Observability](/docs/features/observability/) | | **Analytics** | Usage, performance, consumers, and cost by period, with comparison and drill-down to the logs | `usage_analytics` | [Analytics](/docs/features/analytics-experience/) | | **Analytics store** | Optional copy of the usage events (ClickHouse engine, `analytics_store` block) that answers usage analytics and request log pages on large deployments; PostgreSQL stays the source of truth and answers whenever the copy is off, behind or unreachable | `analytics_store_usage`, `analytics_store_request_logs` (`clickhouse_analytics`, `clickhouse_request_logs` until 0.0.1-rc.2) | [Analytics store](/docs/features/analytics-store/) | | **Sessions and end users** | Groups the calls of one conversation or of one end user of your app | `session_tracking`, `end_user_tracking` | [Observability](/docs/features/observability/) | | **Attempts** | Every retry and fallback of a request | `request_attempts` | [Observability](/docs/features/observability/) | | **OTLP traces and logs** | Spans and logs in the OpenTelemetry standard, including `gen_ai.*` | `otlp_logs`, `otlp_traces` | [Observability](/docs/features/observability/) | | **Request replay** | An operator sends a captured request again as a new request of their own, with origin replay and a link both ways to the request it replays; refused with the reason when the content was not captured | `request_replay` | [Replay a request](/docs/features/trace-explorer/#replay-a-request) | | **Sessions** | Traces → Sessions: the traces that share a session ID as one row each, with traces, duration, cost, tokens, end user, agents, failed evaluations and one column per session evaluator; a session opens with its results, child sessions and a transcript of one turn per trace; clients can end a session's idle wait | `session_explorer` | [Sessions and end users](/docs/features/sessions-and-users/) | | **Agent usage** | Observability → Agent usage: the agents that call models through the gateway with usage over time, last seen, versions, p95 latency, tokens, cost, spans and error rate, the most expensive and slowest, and a comparison of two versions (model, tools, instructions) | `agent_insights` | [Agent usage](/docs/features/agent-usage/) | | **End user pages** | Traces → Users: the end users a client declared with sessions, traces, cost, tokens and failed evaluations, and a page per end user with its traces, sessions and evaluations; summed on read, so erasure removes them | `end_user_pages` | [Sessions and end users](/docs/features/sessions-and-users/) | | **Trace explorer** | The Traces screen: traces and spans over one query bar with lenses, facets and a time range; each trace as a tree, a time-ruled waterfall and an agent graph, with its evaluations, feedback, the gateway's own records and captured content by permission | `trace_explorer` | [Trace explorer](/docs/features/trace-explorer/) | | **Query language and saved views** | One query language for the Traces screen, the request log, evaluator rule filters and alert rules: AND, OR, NOT, groups, lists and ranges over one catalogue of fields with the gateway's own facts (fallback, canary arm, cache, guardrail outcome, customer, prompt revision, evaluation results); a facet of any field; text search over captured content for content readers; saved views for a person, a team or an organization | `trace_query` | [Query language and saved views](/docs/features/query-language/) | | **Custom dashboards** | Pages you build yourself: a time series as lines or bars, a single figure or a Markdown note over the usage metrics (evaluation metrics included) and over the query language of the Traces screen, with filters, a breakdown and a live preview; private, for a team or for an organization, every widget answered with the reader's own permissions; every save is a version you can view and restore | `custom_dashboards` | [Custom dashboards](/docs/features/dashboards/) | | **Agent runs** | Coding-agent runs recognized from the requests alone, with nothing set up on the client: the agent's name, the calls of one run under the client's own run ID or a derived one, turns, the tool steps the client reports, subagent branches and compactions; the Agent runs screen lists runs and opens one as a thread. The typed task text is kept only under `agent_recognition.task_capture`, off by default | `agent_recognition` | [Agent runs](/docs/features/agent-recognition/) | | **Agent transcript ingest** | `POST /v1/traces` accepts a coding agent's own transcript as OTLP/HTTP JSON spans in the OpenTelemetry GenAI conventions, from a key with the scope `traces:write`, and files them under the run the traffic recognized; message content in the upload is discarded | `agent_transcript_ingest` | [Transcript ingest](/docs/features/agent-recognition/#transcript-ingest) | | **OTLP ingest of application spans** | `POST /v1/traces` accepts an application's own OpenTelemetry spans (protobuf or JSON, GenAI and OpenInference), so the application's agent, tool and model spans and the gateway's own form one trace; connectors keep the tree, instrumentation issues are recorded per span, message content only under the team's `app_spans` capture purpose | `otlp_ingest` | [Application spans over OTLP](/docs/features/otlp-ingest/) | | **Public trace API** | Keys of a team read its traces, spans, evaluation results and evaluators, and keep evaluators as code from CI; client helpers in Python, TypeScript and Go | `public_trace_api` | [Public trace API](/docs/features/public-trace-api/) | | **Structural items on spans** | The shape of each conversation on its request span and OTLP span, without any text: message count and roles, tools declared and called by name, attachment counts, token split; for teams that capture no content | `span_structural_items` | [Content capture](/docs/features/content-capture/#structural-items-on-the-span-span_structural_items) | | **OTLP metrics** | The `/metrics` series pushed to an OTLP/HTTP receiver on an interval; off by default | `otlp_metrics` | [OTLP metrics](/docs/features/observability/#otlp-metrics) | | **Prometheus metrics** | `/metrics` and a ready-made Grafana dashboard | `metrics_endpoint` (`prometheus_metrics` until 0.0.1-rc.2) | [Observability](/docs/features/observability/) | | **Model server metrics** | The own Prometheus metrics of self-hosted model servers (vLLM, llama.cpp), scraped per connection and shown in `/metrics` and OTLP with a `provider` label; off by default | `provider_metrics_scrape` | [Model server metrics](/docs/features/observability/#model-server-metrics) | | **Provider request labels** | The caller's organization, team and key ID sent to Vertex AI as request labels, so the Google Cloud bill can be grouped like the gateway's reports; values hashed for teams whose policy forbids plain identifiers; off by default | `provider_request_labels` | [Provider request labels](/docs/features/provider-request-labels/) | | **Log destinations** | Metadata for every call in S3, GCS, Azure Blob, Langfuse, Datadog, or HTTP | `log_destinations` | [Observability](/docs/features/observability/) | | **Request audit events** | One versioned JSON line per finished inference request on stdout, metadata only, for an audit pipeline such as Vector | `logging.request_events` (setting) | [Request audit events](/docs/features/request-events/) | | **Alerts** | Budget near its limit, guardrail blocks, and failures, sent to a webhook, Slack, Teams, email, or PagerDuty | `alert_channels` | [Alerts](/docs/features/alerting/) | | **Durable receipts** | Every accepted request leaves a receipt before it goes to the provider; nothing is lost silently | `durable_usage` | [Durability](/docs/features/durable-usage/) | | **Usage in streams** | Tokens are also measured in SSE responses | `stream_usage` | [Usage in streams](/docs/features/stream-usage/) | | **Retention** | Deletes old metadata by age, with confirmation | `metadata_retention` | [Retention](/docs/features/metadata-retention/) | | **m7 ai** | Questions in plain language about traffic, cost, errors, configuration, audit and the docs, answered from the data you may see, with every step shown; also the structured usage query API (any group-by, hourly buckets, cost) | `ask_ai` | [m7 ai](/docs/features/ask-ai/) | | **m7 ai actions** | m7 ai proposes key, team, budget and team-membership changes; each is shown with its current and new values and runs once, as you, only after you confirm it | `ask_ai_actions` | [Administrative actions](/docs/features/ask-ai/#administrative-actions) | # Logs, traces and metrics **Last updated:** 2026-11-27T14:42:00-03:00 (UTC-3) When a user says "the response was slow" or "it failed", you need to find that request and see what happened: which model, which provider, how many attempts, how long. The gateway gives every request an ID, propagates the W3C trace to the provider, records the metadata in the console and exports logs, traces and metrics to the tools you already use. **Telemetry and request history contain metadata only.** Logs, traces and metrics omit prompts and responses. The separate [encrypted content capture](/docs/features/content-capture/) feature can retain request and response content only when explicitly enabled; it is not a telemetry exporter. ## Correlation 1. The client can send `X-Request-Id` (1 to 128 characters) and a W3C `traceparent`. Without valid values, the gateway generates its own. 2. The response returns `X-Request-Id` and the request's `traceparent`. 3. Each call to the provider gets the same `X-Request-Id` and the `traceparent` of a child span. Retries and fallbacks show up as separate spans in the same trace. To investigate: copy the `request_id` or the `trace_id` from the console and find, in your log backend, the `request` log and every `upstream_attempt` with the same ID. Internal model helpers called within a request retain its trace and use a fresh server span plus a separate provider-attempt span. Their existing derived request IDs, such as `.classify`, `.route`, `.route-index` and `.cache`, identify the helper operation. A background operation without an existing request span starts its own trace. Outbound model-catalog pages also carry the initiating request ID and a fresh child `traceparent`, including public catalogs and authenticated connection discovery. The catalog still uses the configured provider credential, refuses redirects and keeps its existing cache behavior; a cached result makes no outbound call. Correlation headers contain identifiers only, never a prompt, response or credential. ## Failure events and ownership Unexpected server failures log one safe cause at their owning boundary, with `status`, `code`, route where available and the trusted HTTP request/trace/span IDs. A storage library returns its error to that owner; it does not add a second global logger. `failAs` preserves existing domain event names and finite provider/resource metadata, while canonical status/cause/correlation fields cannot be replaced by added attributes. - `request_failed` and domain events such as `feature_refresh_failed` identify gateway failures. A committed change whose refresh fails still reports the existing synchronization outcome; logging does not undo the write. - `provider_response_failed` and agent HTTP events describe an upstream **attempt**, using finite HTTP status/cause/provider metadata. They never include response bodies, authorization, headers or URLs. Join them to the final HTTP event with `request_id`; an attempt may fail before a successful fallback, so its status is not necessarily the client's final status. - A client cancellation is Info/499, not a server/provider fault. Operator stop remains the expected 503 policy outcome. SCIM retains its SCIM error envelope when classifying these outcomes. - Cached failures still produce an event for the current request with `cache_replayed`; caching does not erase that request's failure journey. - `otlp_logs_export_failed` and `otlp_traces_export_failed` use finite `reason` (`encode`, `request`, `transport`, `http_status`), `status` and dropped-record/span counts. They use the existing base JSON handler, bypassing export of their own diagnostics. This avoids recursive failures when a Collector is down; endpoint/query/response text is never logged. `telemetry_shutdown_failed` identifies the affected signal and cleanup failure. These are batch/background diagnostics, not invented single-request spans. For example, filter structured output by the returned request ID: ```sh jq 'select(.request_id == "example-request-id") | {msg, request_id, trace_id, span_id, route, status, code, error}' gateway.jsonl ``` The console's request-log explorer remains persisted request metadata; it does not become an index of every stdout/OTLP event. Use the matching IDs in the configured log backend to find detailed causes. CLI/configuration errors before the runtime logger is initialized retain their existing stderr diagnostics. ## History in the console With `usage_analytics` (PostgreSQL), each authorized call becomes an event with key, team, model, provider, status, duration and tokens. The console uses these events in **Request logs** and in [Analytics](/docs/features/analytics-experience/), without Prometheus or Grafana. | Feature | Flag | | --- | --- | | Selectable columns and server-side sorting | `request_log_columns` | | Filter by exact HTTP status | `request_log_status_code` | | CSV export of up to 10,000 filtered rows | `request_log_export` | | Automatic refresh of the first page every 5 s, while the tab is visible | `request_log_live_tail` | | Time to first byte (`ttfb_ms`; TTFT for streams) | `request_timing` | | How many attempts to the provider each request made (Attempts column) | `request_attempts` | | Which deadline ended an operation (`timeout_kind`; Timeout column) | Recorded by [timeout controls](/docs/features/stream-timeouts/); column selection uses `request_log_columns` | | The end user of your app (`X-Gateway-End-User` or OpenAI's `user` field) | `end_user_tracking` | | Session (`X-Gateway-Session-Id`), to follow a conversation or an agent run | `session_tracking` | | Request journey: stages, related trace requests, recording gaps and a permalink in the request details | `request_journey` | | Agent session graph: the steps of a session with declared agents, turns and parent/child sessions, apart from what the gateway observed ([below](#agent-session-graph)) | `agent_sessions` | | Agent runs: coding-agent runs recognized from the requests alone, listed by agent, task and owner and opened as a thread ([agent runs](/docs/features/agent-recognition/)) | `agent_recognition` | | Verified client address of each request, kept apart from usage with its own retention, for filtering, journey, export and erasure ([details](/docs/security/source-ip-controls/#persisted-client-addresses)) | `client_source_metadata` | | Recycle bin: deleted keys, teams and workloads, with author and request ID | `recycle_bin` | - **End user:** 1 to 128 characters, declared by the key, not authenticated. It becomes a filter, a column and the `by_end_user` ranking. An invalid header gives `400`. - **Session:** filtering Request logs by a session shows its summary (requests, errors, duration, tokens, models, keys and up to 20 end users). API: `GET /api/v1/admin/sessions/{id}`. - **On a phone** (below 768 px) each request is a card that names every column, and the filter form folds into its summary after **Apply**, so the first result is on screen. On a wider screen the default columns fit; long IDs are shortened in the middle (hover for the whole ID, or copy it), and a table wider than its box says so under it and scrolls sideways. - Team roles only see their own teams' events. - With [key owners](/docs/features/identity-ownership/) and [tags](/docs/features/usage-tags/), each event also stores the owner and the tags. ### Request journey `request_journey` (off by default; requires `request_logs`) replaces the fixed three-step sketch in the request details with what the gateway actually persisted: ```yaml features: request_logs: true request_journey: true ``` - **Stages** of the latest record: client request received (principal, key, team, owner, end user, session, operation), admission and guardrails (`passed`, `refused` with the gateway error code, `blocked` with the guardrail), routing (requested and served model, auto-route alias and baseline, `cache_hit`), upstream provider (provider, attempts, service tier, timeout; `failed`, `skipped` after a cache hit, `not_reached` after a refusal), response (status, duration, time to first byte, tokens) and, when you may see cost, valuation (`known`, `partial`, `unknown` or `unvalued`, with its basis). - **Not recorded**: every journey states the storage contract's own limits (per-attempt provider/status/timing, internal stage durations, guardrails that passed, spans, bodies) and the gaps of this record, such as attempts or time to first byte not recorded (the flag was off or the record predates it), token usage not reported (unknown is not zero) or no valuation. - **Provider sends** (`journey_attempt_lines`, off by default; requires `request_journey` and [`attempt_charge_lines`](/docs/features/usage-valuation/)): a retried or fallen-back request lists each send under the upstream stage, oldest first, from its charge lines: provider, upstream model, outcome (`answered`, `provider_error`, `transport_failure`, `unmeasured_answer`), HTTP status and which send was final; with cost visible also each send's valuation, amount and tokens, never its rate. The "per-attempt provider/status/timing" gap then narrows to `attempt_timing_not_persisted`: only the timing of each send is unknown. A request with one send needs no list (the record is that send). A retried record from before the lines were on keeps the old gap. The lines are read in the journey's own snapshot, after the team filter. - **Stored spans** (`span_store`, off by default): when the [span store](/docs/features/traces/) has the request's spans, the journey links its trace (`stored_trace` with the trace and request span ID, and an **Open trace** button) and no longer lists the gaps the spans cover: `stage_timing_not_persisted`, `attempt_detail_not_persisted`, `attempt_timing_not_persisted`, `guardrail_passes_not_persisted` and `spans_in_trace_backend`. A request without stored spans (older, sampled out) keeps them. - **Records with this request ID**: clients may reuse an ID; up to 20 records are listed (the newest kept) and the stages describe the latest. - **Same trace**: up to 20 other requests that share the trace ID (the earliest kept), with request ID, operation, model, status and duration only; each opens its own journey. - **Copy link** gives `https:///ui/#/logs/request/`. The link carries only the request ID: opening it signs in as usual and asks the server again with that session. The [Evals](/docs/features/evals/#from-an-evaluation-to-its-request) screens link every request ID they show to this permalink. - **Reading the drawer:** times are local, like the request table (hover for the exact UTC instant); amounts print as exact decimals (`US$0.00000186`), never rounded or zero-padded; long principals, keys and IDs stay on one line, shortened in the middle, with the whole value on hover and a copy button. Authorization is the request log's: `logs:read`, plus live team membership for team roles, applied in SQL before both limits, so another team's records neither appear nor use up a limit. A missing and an out-of-scope request ID give the same `404`, so a link reveals nothing to someone outside its team; removing a membership closes the link on the next request. Fields follow the same flags as the CSV export: tags with `usage_tags`, session with `session_tracking`, end user with `end_user_tracking`, owner with `identity_ownership`, requested model with `model_aliases`, savings fields (avoided and cached tokens, auto-route baseline) with `cost_optimization`, and cost with `usage_valuation` plus `analytics:read`. Bodies are never returned. API: `GET /api/v1/admin/requests/{id}/journey`, answered with `Cache-Control: private, no-store`: ```json { "request_id": "f8a8a2afe721ea6dede1673b4af78962", "permalink": "/ui/#/logs/request/f8a8a2afe721ea6dede1673b4af78962", "stages": [ {"id": "upstream", "state": "recorded", "facts": [{"name": "provider", "value": "openai"}, {"name": "attempts", "value": "1"}]} ], "trace": {"trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "related": [], "truncated": false}, "gaps": [{"code": "attempt_detail_not_persisted", "stage": "upstream", "message": "Only the number of upstream attempts is stored; ..."}], "valuation_shown": false } ``` With the flag off the endpoint answers `404 feature_disabled` and the drawer keeps the sketch built from the list row. No migration: the journey reads existing columns and indexes. ### Agent session graph A coding agent needs none of the headers below: with [`agent_recognition`](/docs/features/agent-recognition/) the gateway reads the agent, the run and its subagents from the client's own requests, and a recognized run appears here as a session (the run ID is the session, the client the agent, the run that spawned it the parent session). The headers are for your own agent code, and they win over what recognition reads. `agent_sessions` (off by default; requires `session_tracking`, which requires `request_logs`) turns a session into a graph of its steps. An agent framework already groups its calls with `X-Gateway-Session-Id`; with the flag on it may also declare, per request: | Header | Meaning | Rules | | --- | --- | --- | | `X-Gateway-Agent-Id` | The agent that made the call (`planner`, `researcher`, ...) | 1–128 printable characters, one value | | `X-Gateway-Turn-Id` | The turn (one user message and the calls it causes) the call belongs to | Same | | `X-Gateway-Parent-Session-Id` | The session that spawned this one, for a sub-agent run | Same; ignored when equal to the session ID | ```yaml features: request_logs: true session_tracking: true agent_sessions: true ``` ```bash curl -s http://gateway/v1/chat/completions -H "Authorization: Bearer $KEY" \ -H 'X-Gateway-Session-Id: run-42' -H 'X-Gateway-Agent-Id: planner' -H 'X-Gateway-Turn-Id: turn-1' \ -H "traceparent: $TRACEPARENT_FROM_PREVIOUS_ANSWER" -d @request.json ``` An invalid or repeated header answers `400 invalid_agent_context` before any provider call; with the flag off the headers are ignored. These labels are **asserted**: the client declares them, nothing authenticates them, and they never authorize, route, cache or bill. The graph sets them apart from what the gateway **observed** itself: - **Steps**: every usage event of the session (model calls, with operation, model, provider, status, duration and provider-reported tokens) and every MCP tool execution through the gateway (`tool_call`, by configured tool grant and server, with status and duration, including a call that failed at the MCP server; recorded with `usage_analytics` on, after the complete response). A step's finish reasons come from the [GenAI telemetry](#genai-semantic-conventions); `tool_calls`, `tool_use` and `function_call` (Chat Completions and Messages) mark a step that asked for a tool. Responses and Gemini answers report `stop` for a tool request, so their tool requests are not marked. - **Observed links**: `caused_by_span` when a request's W3C `traceparent` names the server span of an earlier step (the client continued the trace from the gateway's answer, which returns its own `traceparent`); traces group the steps that share a trace ID. Request IDs are never used to infer a link: a client chooses them. The gateway's own helper calls (classification, routing, guardrail moderation) carry no session and are not steps; a [semantic fallback](/docs/features/routing-strategies/#semantic-fallbacks) is a step of its own, with the same session and agent headers. - **Asserted links**: agents and turns group steps; `same_turn_next` links each step to the previous step of its turn; parent sessions and child sessions (other sessions whose steps name this one as parent) are listed with their own step counts. - **Totals** add each listed step once (`truncated` says when later steps exist). Token sums are `null` when no model call reported them, with `input_reported_steps` and `output_reported_steps` out of `model_calls`: unknown is not zero. Child sessions are never added: their usage stays in their own graph, so a parent and its sub-agents are not double counted. The console shows **Show agent graph** under the session summary of a session-filtered Request logs page: one lane per declared turn (and one for steps without a turn), a time ruler from the session's start to its last step, a bar per step on that axis labelled with its duration, each link labelled `observed` or `asserted`, and child/parent sessions that open the same view. API: `GET /api/v1/admin/sessions/{id}/graph?from=&to=` (default the last 24 hours, at most 90 days), answered with `Cache-Control: private, no-store`: ```json { "session_id": "run-42", "parent_sessions": [], "child_sessions": [{"session_id": "run-42-research", "basis": "asserted", "steps": 3, "first_at": "...", "last_at": "..."}], "agents": [{"id": "planner", "basis": "asserted", "steps": [0, 1, 2]}], "turns": [{"id": "turn-1", "basis": "asserted", "steps": [0, 1, 2]}], "steps": [ {"index": 0, "kind": "model_call", "request_id": "r1", "span_id": "c8460d20618f472f", "operation": "chat", "model": "agent", "status": 200, "finish_reasons": ["tool_calls"], "tool_requested": true, "agent_id": "planner", "turn_id": "turn-1", "agent_context_recorded": true}, {"index": 1, "kind": "tool_call", "request_id": "r2", "tool_name": "lookup", "tool_server": "kb", "status": 200, "agent_id": "planner", "turn_id": "turn-1"}, {"index": 2, "kind": "model_call", "request_id": "r3", "parent_span_id": "c8460d20618f472f", "finish_reasons": ["stop"]} ], "edges": [ {"from": 0, "to": 1, "relation": "same_turn_next", "basis": "asserted"}, {"from": 0, "to": 2, "relation": "caused_by_span", "basis": "observed"} ], "totals": {"steps": 3, "errors": 0, "input_tokens": 14, "output_tokens": 4, "token_reported_steps": 2, "child_sessions": 1, "includes_child_sessions": false}, "gaps": [{"code": "bodies_not_recorded", "stage": "", "message": "..."}] } ``` - **Authorization** is the request journey's: `logs:read`, plus live team membership for team roles, applied in SQL before every limit (200 steps, earliest kept; 50 child sessions; 5 parent declarations). A missing and an out-of-scope session give the same `404`; a parent session is a link only when the reader may see one of its steps in the range. Removing a membership closes the graph on the next request. Session IDs are chosen by clients and not namespaced: two teams may send the same ID, so a global role sees the steps of both (each with its key and principal) and a team role only its own. - **Partial, late and duplicate data**: the graph is a read of what PostgreSQL holds at `observed_at`; a step written later appears on the next read. Requests made while the flag was off, or whose agent row could not be written, stay as steps with `agent_context_recorded: false` and the `agent_context_missing` gap. Each agent row belongs to exactly one usage event (request, trace, key and the event's start), so a client that reuses a request ID gets one row per request, never another request's labels; a repeated write of the same event keeps the first. Trace sampling (the `traceparent` flags) and exporter loss do not change the graph, which never reads exported spans. A cancelled request is a step with status `499` (`client_closed`). - **Persistence and retention**: migration 131 adds `gateway_agent_steps`, apart from usage events, receipts and the ledger, whose fingerprints do not change. A model-call row lives as long as its usage event: every replica deletes, each minute, rows older than the oldest remaining usage event, so the table follows [metadata retention](/docs/operate/operations/) and never outlives it; a tool row has no usage event, so with an active metadata retention policy it expires after the same number of days, and while metadata is preserved it follows the oldest usage event, never before 90 days (the longest read range). Rows are written after the usage event, never affect the request and log `agent_step_record_failed` on error. - **Never recorded**: prompts, answers, tool arguments and tool results; per-attempt spans. Tools are known only from finish reasons and gateway MCP executions. With the flag off the endpoint answers `404 feature_disabled`, the console shows no graph and existing rows stay until retention removes them. **Upgrade step:** run migration 131 with this release and upgrade every replica before enabling the flag; an older replica ignores the headers and answers the endpoint 404. `timeout_kind` is `first_byte`, `idle`, `max_duration`, `client_stall`, `request` or `attempt` when that timeout ended the operation; absent values remain absent. It is exported as `gateway.timeout_kind` on the root span and retained in usage/log metadata, without payloads. A successful fallback does not inherit the previous attempt’s timeout label. Historical metadata stays readable under existing team/log permissions when the timeout feature is later disabled. A provider attempt to an `openai` target names the OpenAI API it used in `openai.api.type` (the OpenTelemetry OpenAI attribute: `chat_completions` or `responses`) on its span. On an [`api: auto`](/docs/features/protocol-translation/#api-auto-the-api-chosen-per-request) target, its `upstream_attempt` log also carries `wire_api` (same values) and `wire_api_reason`, one of `reasoning_effort_object`, `reasoning_effort_max`, `tools_with_reasoning_effort`, `responses_translation_refused` or `chat_completions_sufficient`; the attempt log of any other target keeps its fields unchanged, since its API is the configured one. Each attempt of a fallback or retry has its own value. An attempt to a Claude target with [`prompt_cache: {mode: auto}`](/docs/features/prompt-caching/) that placed cache points adds `prompt_cache_points` (how many, 1 to 4) to its `upstream_attempt` log; no other attempt gains the field. ## Stored spans With `span_store` the gateway also keeps its own spans (request, routing decision, provider attempts with timing and ledger cost, cache lookups, guardrails, MCP tools, helper calls) in PostgreSQL, written off the request path, and the console opens any request as a trace tree. The stored spans use the same trace and span IDs as the OTLP export below, so both views line up. Settings, retention, sampling, the API and the metrics are in [Traces and the span store](/docs/features/traces/). ## Logs and traces (OTLP) The structured request and attempt logs have `request_id`, `correlation_id`, `trace_id`, `span_id`, route, status and duration. Every other log written while serving a request (a failure, a stream cut short, a storage error) carries the same `request_id`, `trace_id` and `span_id`, so one search returns the whole journey. Once the request's key is authenticated, every line also carries the identity hierarchy: `key_id`, `principal`, `team` and, with `organizations` on, `organization_id` (empty when none applies), on stdout and OTLP alike. That includes a request refused right after authentication (the source network, an invalid attribution header, a scope the key lacks, organization or team policy storage unavailable); a key that is unknown, expired or revoked authenticates nobody, so its `401` names no caller. The `request` line adds `traceparent: ignored_malformed` when the client's `traceparent` did not parse and was replaced by a trace of the gateway's own. Exported OTLP spans carry the same identity as `gateway.key.id`, `gateway.principal`, `gateway.team.id` and `gateway.organization.id`, and model call attempts carry the generation parameters the client sent (`gen_ai.request.temperature`, `gen_ai.request.max_tokens` and the others listed in [traces](/docs/features/traces/#what-a-trace-holds)). None of these are metric labels. The gateway sends logs and traces over OTLP/HTTP, in binary protobuf by default, to any OTLP receiver: an OpenTelemetry Collector, or directly a pipeline such as Vector ([below](#without-a-collector-vector-and-s3)). The send queue is bounded: if the Collector fails, the request goes on and telemetry may be lost. ### Destinations and startup The `otlp_logs` and `otlp_traces` boot flags enable the two exporters independently. With a flag enabled, its destination is selected once at startup, in this order: nonempty signal-specific environment override, explicit YAML value, default. An empty environment override falls back to YAML/default. The defaults are `http://127.0.0.1:4318/v1/logs` and `http://127.0.0.1:4318/v1/traces`: ```yaml telemetry: otlp: logs_endpoint: http://collector:4318/v1/logs traces_endpoint: http://collector:4318/v1/traces ``` | Key | Default | What it does | | --- | --- | --- | | `telemetry.otlp.logs_endpoint` | `http://127.0.0.1:4318/v1/logs` | OTLP/HTTP address the logs exporter sends to, with the signal path | | `telemetry.otlp.traces_endpoint` | `http://127.0.0.1:4318/v1/traces` | OTLP/HTTP address the traces exporter sends to, with the signal path | The shipped base YAML and its Helm copy explicitly contain the loopback URLs, so their source is `yaml`; only an omitted/empty YAML endpoint without an override reports `default`. `telemetry.otlp.protocol` selects the encoding for both signals: `http/protobuf` (the default, `application/x-protobuf`) or `http/json` (`application/json`). Every OTLP receiver must accept protobuf; some accept nothing else (Vector's `opentelemetry` source, measured on 0.61). The standard `OTEL_EXPORTER_OTLP_PROTOCOL` variable overrides the YAML when an exporter is enabled. Any other value, gRPC included, stops the boot with the setting named. The overrides are `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` and `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`. Each URL is used as supplied: include the signal path yourself. Use an absolute `http` or `https` URL with a hostname and a valid port if supplied, up to 2,048 bytes; user info, query and fragment are rejected. YAML destinations are validated even when their flag is off; environment overrides for disabled exporters are ignored. No general `OTEL_EXPORTER_OTLP_ENDPOINT`, gRPC or OTLP authentication/header configuration is provided by this setting. Metrics have their own exporter, [below](#otlp-metrics). ### The service every signal names Every exported log, span and metric carries the same resource attributes, so a backend joins the three signals of one deployment and tells deployments apart: | Attribute | Value | Set by | | --- | --- | --- | | `service.name` | `ai-gateway` | Fixed | | `service.version` | The gateway's version (`gateway version` prints it) | `telemetry.otlp.service_version`, or `service.version` in `OTEL_RESOURCE_ATTRIBUTES` | | `deployment.environment.name` and `deployment.environment` | Your environment, such as `production` or `staging`; left out when not set | `telemetry.otlp.deployment_environment`, or `deployment.environment.name` (or `deployment.environment`) in `OTEL_RESOURCE_ATTRIBUTES` | ```yaml telemetry: otlp: deployment_environment: production # service_version: 2026.11.2 # only to name a build differently from its version ``` Set `deployment_environment` on every installation you export from: it is what most backends use to split production from staging, and the gateway cannot guess it. The older name `deployment.environment` is written next to `deployment.environment.name` because several backends still read only the older one. The values are read once at startup, take 1 to 128 printable characters, and come from the standard `OTEL_RESOURCE_ATTRIBUTES` variable first, then the YAML, then the binary's version (for the version only); an override value that is not valid is ignored. Other keys of `OTEL_RESOURCE_ATTRIBUTES` are not exported. The same attributes go on [log destinations](#log-destinations) that speak OTLP, and **Settings → Infrastructure** shows the values in effect with their source. They are not metric labels on `/metrics`. ### A link back to the console on every span With `telemetry.otlp.console_url` set to the console's address, every exported span carries `gateway.console.url`, the span in the console's trace view (`/#/traces/?span=`): from a trace in your APM backend, one click opens the same trace in the gateway with its routing, attempts, cost and evaluations. Unset (the default), no link is exported. ```yaml telemetry: otlp: console_url: https://gateway.example.com/ui # absolute http(s), no query or fragment ``` The address is read once at startup and shown in **Settings → Infrastructure** (Resource line). It is an attribute of the span, not of the resource, and names no team or key: whoever follows it still signs in and sees only what their role allows. To link the other way, from the console to your APM, use `spans.apm_link_template`. A reachable Collector is needed to receive telemetry, not to boot or serve inference. Without one, export may fail or drop records from the bounded queues; the gateway continues serving requests. In a container, loopback refers to that container: use the Collector service address when it is a separate service. Disabling both flags keeps structured JSON stdout logs. ### Without a Collector: Vector and S3 A Collector is optional. Any OTLP receiver can take the gateway's logs and traces directly, for example [Vector](https://vector.dev/) writing them to an S3 bucket. Measured on 2026-11-07 with the Quickstart stack, Vector 0.61 and MinIO standing in for S3: ```yaml # vector.yaml sources: otlp: type: opentelemetry grpc: {address: 0.0.0.0:4317} http: {address: 0.0.0.0:4318} # OTLP/HTTP: protobuf only, the gateway's default sinks: s3_logs: type: aws_s3 inputs: [otlp.logs] bucket: otel key_prefix: "logs/%Y-%m-%d/" region: us-east-1 endpoint: http://minio:9000 # omit for AWS S3 force_path_style: true # MinIO and other S3-compatible stores encoding: {codec: json} framing: {method: newline_delimited} s3_traces: type: aws_s3 inputs: [otlp.traces] bucket: otel key_prefix: "traces/%Y-%m-%d/" region: us-east-1 endpoint: http://minio:9000 force_path_style: true encoding: {codec: json} framing: {method: newline_delimited} ``` - **Credentials:** give Vector its S3 credentials through `AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY`, or an IAM role. On 0.61, a `${VAR}` placeholder inside the sink's `auth` block was sent literally. - **Gateway:** point it at Vector with `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=http://vector:4318/v1/logs` and `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://vector:4318/v1/traces`. With Compose, put both in an override file next to `compose.yaml`; the bundled Collector service can stay stopped. - **Decoding:** without a `decoding` option, Vector writes one JSON line per record, with hex `trace_id`/`span_id` and the gateway's attributes as fields. `decoding: {codec: otlp}` keeps the raw OTLP structure, but Vector's JSON encoder then prints the binary IDs as unreadable text. - **Correlation:** a request's log record and its server and provider spans share the request's `trace_id`, and carry `request_id`/`request.id`. Prompts and answers are never exported. - **When the receiver is down or stalled:** requests are unaffected. Measured, the latency stayed under 1 ms on average with Vector stopped and with it paused. Records that could not be sent are dropped from the bounded queue and counted in `gateway_otel_dropped_total{signal}`; alert on its rate. ### On Kubernetes: Vector to Cloud Storage The same pattern on GKE, with the logs written to a Cloud Storage bucket. The kit of the multi-region validation ships it as a manifest ([`deploy/validation/gke-multiregion/manifests/vector.yaml`](https://github.com/m7gtw/gateway/blob/main/deploy/validation/gke-multiregion/manifests/vector.yaml)): a ServiceAccount, the configuration below, a one-replica Deployment, a Service on 4318/4317 and a NetworkPolicy that admits only the gateway Pods. ```yaml # vector.yaml (Vector 0.61, distroless-libc image pinned by digest) data_dir: /var/lib/vector sources: otlp: type: opentelemetry http: {address: "0.0.0.0:4318"} # protobuf, the gateway's default protocol grpc: {address: "0.0.0.0:4317"} sinks: bucket: type: gcp_cloud_storage inputs: [otlp.logs] bucket: my-gateway-logs key_prefix: "logs/us-central1/%Y-%m-%d/" filename_extension: ndjson compression: none encoding: {codec: json} framing: {method: newline_delimited} batch: {timeout_secs: 10} # one object about every 10 s while logs flow healthcheck: {enabled: false} # it reads bucket metadata, which object creation alone does not grant ``` - **Identity, without a key:** with Workload Identity Federation for GKE, grant `roles/storage.objectCreator` on the bucket to the Kubernetes ServiceAccount itself, `principal://iam.googleapis.com/projects//locations/global/workloadIdentityPools/.svc.id.goog/subject/ns//sa/vector`. Vector takes its token from the GKE metadata server. Create-only is enough: every object name carries a UUID, so nothing is overwritten. - **Gateway, with Helm:** set `gateway.otlpLogsEndpoint: http://vector:4318/v1/logs` as well as `telemetry.otlp.logs_endpoint` in the YAML. The chart sets `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` whenever its Collector is on, and that environment override wins over the YAML. With `networkPolicy.egress.enabled`, add an `extraRules` entry to the Vector Pods on 4318. - **What lands:** one JSON line per record, with the gateway's attributes (`request_id`, `trace_id`, route, status, duration) as fields. Prompts, answers, keys and tokens are never in the records. - **Losing the receiver:** the gateway's log queue holds 1,024 records and a batch that fails to send is not retried, so records produced while Vector is away are dropped (counted in `gateway_otel_dropped_total{signal="logs"}`); inference is unaffected. Run Vector with a persistent buffer, or more than one replica behind the Service, when the logs must survive its restarts. Measured on GKE (2026-11-21), with this configuration and identity: turning the logs on was a `helm upgrade` under load with no failed request of 1,782; the request IDs of 40 requests were all in the bucket within about 27 s; no secret value or secret-shaped string (provider keys, gateway tokens, bearer values) appeared in any of the 13 objects; and deleting the Vector Pod under traffic affected no request (none of its records were lost in that short outage, which the bounded queue does not guarantee). The rest of the production setup around it is in [run on Kubernetes in production](/docs/operate/kubernetes-production/#shipping-logs-over-otlp). **Settings & sources → Infrastructure** and the existing administrative configuration summary show only each signal's enabled state, whether an active validated destination was captured at boot, its source (`default`, `yaml` or `environment`) and its restart requirement. They never return the destination URL, host or environment-variable name. **Configured is not a health check or proof of delivery.** A disabled signal shows configured `false` and source `null`, without erasing latent YAML; unavailable metadata is not presented as a configured destination. Endpoints and these flags require a restart/rollout, and subsequent runtime configuration refreshes retain that applied boot snapshot. Request and attempt records use typed attributes; context enrichment preserves an explicit or logger-bound request/trace/span ID instead of adding it twice. This changes internal encoding, not the log contract or telemetry controls. The request and attempt field names, order, types and levels remain compatible. What to look for when a request fails: - **`request_failed`** (Error for a 5xx): the gateway could not serve the request; `code` is the error code the client received and `error` the cause. Some failures keep an older, specific name (`key_lookup_failed`, `analytics_query_failed`, ...). - **`upstream transport failure`** (Warn, one per attempt) and **`upstream_transport_failure`** (Error): the provider could not be reached; `provider` names the connection and `error` the cause, with the URL's query and credentials removed. - **`stream_copy_failed`**: an answer was cut after it started; `side` identifies the provider (Warn), client (Info), or administrative gateway stop (`gateway`, Info). `bytes_sent` records how much was written. An administrative stop uses the bounded `gateway_panic` result where an attempt result is recorded; it is not a provider-health observation. - **`client_closed_request`** (Info): the client went away before the answer. It is recorded with status **499**, in the request log, the metrics and the usage events, and is not counted as a provider failure nor by the circuit breaker. - **Administrative emergency stop:** a request interrupted before its headers gets `503 gateway_panic`, rather than the client-disconnection status `499`. If an unfinished answer already started, the connection is interrupted without replay or a new HTTP status. The first cancellation cause wins: a client departure or deadline that happened first retains its own classification. IDs still identify the affected journey; the stop must not count as a provider-health failure. See [operations](/docs/operate/operations/#emergency-stop-panic). - **`panic in request`** and **`background_panic`** (Error): a defect, with its `stack`. When the answer had already started, the connection is aborted so the client does not take a truncated answer as complete. MCP tool executions also produce a log and a span, with the tool and the result, without arguments or responses. ## GenAI semantic conventions Exported spans follow the [OpenTelemetry GenAI semantic conventions](https://github.com/open-telemetry/semantic-conventions-genai) (development status) for every model call, so a tracing backend that understands `gen_ai.*` shows the operation, provider, models, finish reasons and token usage without gateway-specific parsing. They ride on the existing exporters: `otlp_traces` for spans and `logging.request_events: stdout` for the [request event's `gen_ai` member](/docs/features/request-events/). No new flag; the attributes appear as soon as those are on. Two spans describe each model call: - **Provider attempt** (span kind `CLIENT`, one per send, retries and fallbacks included): what was sent where. Its name is `{gen_ai.operation.name} {gen_ai.request.model}`, such as `chat gpt-4o-mini`, for `chat`, `text_completion`, `embeddings` and `generate_content`; other operations keep `POST provider.`, passthrough keeps ` provider.passthrough`. The span still ends when the response headers arrive. - **Request** (span kind `SERVER`, the gateway's root span): what the client asked for and received, ended when the answer is complete. Operations that are not model calls (vector stores, containers, conversations, fine-tuning, token counting, stored-response reads, deletes and cancels) carry no `gen_ai.*`. Token usage is on this span only, so a backend that sums `gen_ai.usage.*` over a trace counts each request once, however many attempts it made. | Attribute | Type | Attempt span | Request span | Value | | --- | --- | --- | --- | --- | | `gen_ai.operation.name` | string | ✓ | ✓ | `chat` (Chat Completions, Messages, Responses), `text_completion`, `embeddings`, `generate_content`; other operations use the gateway's name (`images`, `audio_speech`, `rerank`, `moderations`, `passthrough`, ...), as the convention allows. | | `gen_ai.provider.name` | string | ✓ | ✓ (not on a cache hit) | Well-known product of the connection: from its preset, then its protocol and endpoint: `openai`, `azure.ai.openai`, `azure.ai.inference`, `anthropic`, `aws.bedrock`, `gcp.gemini`, `gcp.vertex_ai`, `cohere`, `ollama`; another protocol keeps its own name. An OpenAI-compatible endpoint reports `openai`, as the convention prescribes for clients that cannot tell. | | `gen_ai.request.model` | string | ✓ upstream model (`targets[].model`) | ✓ model the client sent | | | `gen_ai.request.stream` | boolean | ✓ | ✓ | Present (`true`) only when the client asked for a stream. | | `gen_ai.response.model`, `gen_ai.response.id` | string | | ✓ | Only what the answer relayed without translation reported. Absent for a translated answer (another protocol, the Responses API behind Chat Completions, Messages/Responses/generateContent ingress), whose body names the alias, and for a cache hit. With `responses_lifecycle` on ([OpenAI Responses](/docs/features/capabilities/#openai-responses)), the ID is the gateway-issued response ID the client received. | | `gen_ai.response.finish_reasons` | string[] | | ✓ | One per generation in provider order, at most 16 (`stop`, `length`, `tool_calls`, `end_turn`, `MAX_TOKENS`, ...). A Responses answer maps `completed` to `stop`, `incomplete` to its reason and `failed` to `error`. Translated answers carry the canonical reason. Streams are read only with `stream_usage`. Absent on a cache hit. | | `gen_ai.response.time_to_first_chunk` | double (s) | | ✓ | Successful streams only (not an error answer or a semantic fallback): time to the first byte written to the client. | | `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens` | int | | ✓ | Provider-reported counters; absent when not reported, never zero by default. | | `gen_ai.usage.cache_read.input_tokens`, `gen_ai.usage.cache_write.input_tokens`, `gen_ai.usage.reasoning.output_tokens` | int | | ✓ | Same sources as the request event's `tokens.cache_read`, `cache_write` and `reasoning`. | | `gen_ai.conversation.id` | string | ✓ | ✓ | `X-Gateway-Session-Id`, under `session_tracking`; caller-declared. With [`agent_recognition`](/docs/features/agent-recognition/), a recognized coding-agent run that declared no session carries its run ID here (the client's own, or a derived one). Otherwise no fallback ID is invented. | | `gen_ai.agent.name` | string | | ✓ | Under [`agent_recognition`](/docs/features/agent-recognition/): the recognized client (the name of the rule that matched, such as `claude-code`). | | `gateway.agent_run.class`, `gateway.agent_run.basis`, `gateway.agent_run.turn`, `gateway.agent_run.compacted`, `gateway.agent_run.tool_steps` | string, string, int, boolean, int | | ✓ | Under `agent_recognition`: the request class (`main`, `subagent`, `compaction`, `auxiliary`), how the run ID was known (`client`, `declared`, `derived`), the number of typed messages in the context window, `true` when that window starts from a compaction summary, and the tool steps this request reported. Labels and counts, never text. | | `gateway.agent.id`, `gateway.turn.id`, `gateway.conversation.parent_id` | string | | ✓ | The [asserted agent labels](#agent-session-graph), under `agent_sessions`. | | `server.address`, `server.port` | string, int | ✓ | | Host and port of the connection's base URL (default 443/80); never the path, query or user information. | | `error.type` | string | ✓ | ✓ | Attempt: the provider's HTTP status (`429`, `500`, ...), or `timeout`, `cancelled`, `transport_error` before any answer; the span status is then error. Request: the status the client received, when 400 or more, or `stream_interrupted` when the provider cut an answer that had already started (the status is then the 200 already sent; the span status is error and `gateway.stream_cut` says `provider`). | | `gateway.provider.id`, `gateway.model.alias` | string | ✓ | `gateway.provider.id` | The configured connection ID and the alias the request resolved. | MCP tool calls are `execute_tool` spans named `execute_tool ` with `gen_ai.tool.name` (the configured tool grant name), `gen_ai.tool.type: extension`, `gen_ai.conversation.id` and `error.type`; a tool listing keeps the `MCP operation` span. With [`agent_recognition`](/docs/features/agent-recognition/#tool-steps), each tool a coding agent ran itself and reported in its next request is also an `execute_tool ` span, a child of that request's span: `gen_ai.tool.name`, `gen_ai.tool.type: function`, `gen_ai.tool.call.id`, `gen_ai.conversation.id`, `gateway.tool.reported_by: client` and, when the client reported a failure, `gateway.tool.reported_error: true`. The gateway did not see that tool run, so the span has no duration, and it never carries arguments or results. The span the gateway stores for it is named `client tool` and keeps the tool's name in an attribute shown only with `content_structure:read`; the exported span keeps the convention's name. The `X-Request-Id` and a child `traceparent` already reach the MCP server. **Content is never exported.** The conventions' opt-in content attributes (`gen_ai.input.messages`, `gen_ai.output.messages`, `gen_ai.system_instructions`, `gen_ai.tool.definitions`) are not emitted at all; request and response bodies are retained only by [encrypted content capture](/docs/features/content-capture/), under its own policy. Every string is checked before export: identifiers (models, response IDs, provider names, tools) must be 1–256 characters of letters, digits and `_ . : / @ + = -`, finish reasons 1–64 of letters, digits and `_ . -`; anything else is left out rather than sent. No request or response ID enters a metric label. **Upgrade note.** Before this release, attempt and other provider spans used `gen_ai.provider.name` for the connection ID and `gen_ai.request.model` for the alias. They now carry the convention's values; the connection ID moved to `gateway.provider.id` and the alias to `gateway.model.alias`. Spans that are not model calls (provider health checks, video task polls, containers, conversations, skipped attempts) keep their names and now name their connection `gateway.provider.id` and their model `gateway.model`, and no longer use `gen_ai.*`. Attempt span names changed from `POST provider.chat` / `POST provider.` to `chat ` (and the other well-known operations) as above. Update trace queries and dashboards that filter on the old names. The [Langfuse destination](#log-destinations) format is unchanged. ## Inspect the startup minimum log level `logging.level` selects the minimum severity of the shipped JSON logging pipeline. The default is `info`; the other accepted values are `warn` and `error`. The existing OTLP log wrapper delegates its enabled check to the same handler, so this selection also filters that pipeline's exported records. JSON is the fixed shipped stdout format, not another configurable format field. Log content still excludes request payloads and credentials at every supported level. With `boot_settings_view` and the existing global configuration-read permissions, `GET /api/v1/admin/config` adds optional `infrastructure.logging_settings`: one read-only `logging.level` row with its captured value, default `info`, source and rollout requirement. **Settings & sources → Infrastructure → Structured logs** shows the same information inline, alongside the unchanged per-signal OTLP status. This remains the startup inspector; the optional runtime editor below is separate. Omitted, null or empty YAML level uses **Default**; an explicit valid value, including `info`, retains **YAML** provenance. There is no log-level environment override. Capture follows successful construction/installation of the owned logger; an uncaptured or arbitrary injected logger is **Unavailable**, and the view does not infer its filter from configuration. The existing normalized summary remains compatible when the visibility flag is off. Configuration refresh preserves the startup capture; changing YAML requires a rollout. The threshold continues to filter existing Info events, including `config_applied`, at `warn` or `error`. The view does not force an announcement through the chosen filter, prove Collector delivery or report every producer's custom logger. Persisted **Request logs** and usage analytics have their own recording flags and permissions; this stdout/OTLP threshold does not disable that database history. When an existing refresh observes lost view/access, the page clears the captured data; a later authorized refresh can reload it. The startup inspector adds no polling or writer. Optional runtime management below retains this immutable capture. ## Change the minimum severity without restarting Enable `features.logging_management` (default `false`) with `ui` and PostgreSQL configured. The YAML `logging.level` remains the baseline (`info` by default; `warn` and `error` are also accepted). In **Settings & sources → Runtime logging**, a global admin can save an override or revert it to YAML; a global viewer can inspect current state. `logging:read` and `logging:manage` are separate permissions. Inference keys, operators and team-scoped roles cannot use this control. The flag grants no permission and does not depend on the startup-view flag. The canonical API is `GET`, `PUT` and `DELETE /api/v1/admin/logging`. GET supplies the current global configuration version, saved override, effective policy/source and separately observed applied level/source. PUT accepts exactly `{"version":4,"level":"warn"}` using the version just read; DELETE accepts only that current version. Mutation requires the authenticated same-origin session and CSRF token. The API reference includes runnable session-based examples. Unknown members, duplicate/case-fold names, nulls, noncanonical levels and trailing payloads are rejected. There is no debug/payload logging switch. Changes are persisted with the shared optimistic configuration version and actor/request-ID audit in one PostgreSQL transaction. Each current replica validates the complete snapshot before applying its owned logging controller. Synchronization uses the existing refresh loop; it is not instantaneous cluster-wide application. JSON, bound/context/stdlog handlers and the OTLP log wrapper share the current minimum. An in-flight request uses the threshold in effect for each log record; its authorization, response and billing are unchanged. Filtering occurs at the handler enabled check; already accepted or queued records can arrive after a change, without retroactive deletion. Info records, including request/startup announcements, can be suppressed; persisted Request logs, audit history, metrics and trace export retain their own controls. The **startup** `logging_settings` row, YAML source and V1–V11 parameter metadata remain immutable and require rollout for changes to their baseline. They do not pretend a runtime edit happened at boot. The new view distinguishes effective policy from an unavailable custom logger: unknown applied values/sources are paired null, and a process without an owned controller refuses mutations with `503 logging_controller_unavailable`. Main installs its owned controller before the first refresh. A successful refresh reasserts the accepted minimum even when the stored version has not changed. Turning `logging_management` off restores that replica's YAML/default minimum and retains the dormant saved override. Re-enabling applies it again after refresh. Revert deletes an existing override; a missing override returns 404. Invalid/corrupted configuration or database failure leaves the last valid local threshold and snapshot in service. If persistence succeeds but local refresh fails, the mutation reports `configuration_sync_pending`: reload before retrying, since the write may already be committed. A conflict preserves the authorized console draft and its original version. Reloading shows the latest state without silently rebasing the draft; the admin explicitly adopts that version after review. Losing access or disabling the feature removes the draft and ignores late replies. After a known denial, the console refreshes parent authorization; a successful viewer read of logging alone cannot restore a management form. The console never echoes untrusted diagnostic bodies. ### Rollout and recovery Back up the database and preserve external secrets, then deploy a binary supporting additive migration97 and the new flag to every replica before enabling runtime control. Already-running older binaries do not implement the controller; do not advertise them as synchronized. Their newer-schema guard also prevents restarting against schema97. There is no automatic schema downgrade: remove/revert the override with a supporting binary, and follow the explicit backup/restore rollback procedure if reverting the binary version. Migration history must not be edited to bypass the guard. After rollout, read `/api/v1/admin/logging` on the actual replicas and compare applied/source with effective policy. Test a bounded local request and correlate its request ID with the mutation audit and the records permitted by the chosen severity. A missing Info log after selecting `warn` is not proof of missing request execution. Restore the baseline with the versioned revert action rather than changing the controller outside configuration ownership. ## Asynchronous log writes ```yaml logging: write_mode: async # default; or sync ``` `logging.write_mode` (default `async`, read at startup; change it with a rollout) selects where the JSON log records are encoded and written to stdout: - **`async`**: one worker goroutine encodes and writes the records, taken from a bounded queue of 1,024 records, and writes whole lines in batches of up to 32 KiB (a batch is flushed as soon as the queue is empty). The request goroutine only hands its request line over. - **Order:** records reach stdout in the order they were logged, one queue and one worker; the lines of one request stay in order. - **Backpressure, no loss:** when the queue is full the caller waits for room; no record is dropped. Waits are counted in `gateway_log_queue_waits_total`. - **Records written before the caller goes on:** a record at Error level or above, and any record carrying a value other than a string, number, boolean, duration or time (an error, a map, a structure, a group), waits until everything queued before it is on stdout and is then written by the caller itself before the log call returns. So error lines are never left in the queue, and no value the caller may change later is read by another goroutine. - **Shutdown:** a graceful shutdown or a startup failure writes every queued record before the process exits (bounded by a 2-second window; if stdout is stuck past it, the count left is written to stderr). A record logged after that is written directly. - **Limit:** a crash that skips shutdown (an unrecovered panic, `SIGKILL`, an out-of-memory kill) loses the Info and Warn records still queued, at most 1,024 records. Choose `sync` when every line must be on stdout before the next line of code runs. - **`sync`**: every record is encoded and written on the goroutine that logs it, as before this setting existed. Both modes write the same records with the same fields; the level filter (`logging.level` and the runtime override), the request, trace and span IDs and the OTLP log export are applied before the queue and do not change. With `logging.request_events: stdout` the log and the events still share stdout through one serialized writer, and no record is ever split between two writes. On the rig in [how performance is measured](/docs/performance/method/#per-request-cpu-cuts-2026-11-18-t173), `async` measured higher throughput and a lower median latency than `sync`, with CPU per request within the noise of it; that measurement is why it is the default. With `boot_settings_view`, `GET /api/v1/admin/config` returns `infrastructure.logging.write_mode` (`mode`, `source` `default` or `yaml`, `default`, `restart_required`, `active`: whether this process writes through the queue, `queue_capacity`), and **Settings & sources → Infrastructure → Log writes** shows it, read-only. This is an operator control, not a feature flag. ## Request audit events With `logging.request_events: stdout` (default `off`, read at startup), every finished inference request also writes one JSON line `{"event":"gateway.request","schema_version":1,...}` to stdout, next to the log: a stable, versioned record for an audit or billing pipeline, with IDs, timings, routing, attempts, tokens, cost, key, team, organization, end user, tags, guardrail outcomes and parameter policy names, never content or credentials. A collector tells events from log records by the `event` member. The queue is bounded and never delays a request; losses are counted in `gateway_request_events_dropped_total`. Schema, Vector example and limits: [request audit events](/docs/features/request-events/). ## Log destinations With `log_destinations`, each request becomes a metadata record (the request log row's fields, including `feedback_key` when the request carried [`X-Gateway-Feedback-Key`](/docs/features/evaluation-results/#feedback-keys)) delivered in batches to: - S3, GCS or Azure Blob, as JSON Lines; - Langfuse, as a `generation` span over OTLP (v3 and v4); - Datadog; - an HTTP endpoint. ```yaml features: log_destinations: true log_destinations: - id: archive type: s3 # s3, gcs, azure_blob, langfuse, datadog or http bucket: gateway-logs region: us-east-1 prefix: requests/ - id: dd type: datadog api_key_env: DD_API_KEY ``` At most 10 destinations; the block is YAML only (restart to change). | Key | Types | Default | What it does | | --- | --- | --- | --- | | `log_destinations[].id` | all | required | Unique lower-case identifier, shown in **Settings & sources** and the status API | | `log_destinations[].type` | all | required | `s3`, `gcs`, `azure_blob`, `langfuse`, `datadog` or `http` | | `log_destinations[].bucket` | `s3`, `gcs` | required | Bucket the JSON Lines files are written to | | `log_destinations[].region` | `s3` | required | AWS region of the bucket | | `log_destinations[].prefix` | object stores | empty | Relative path of the objects inside the bucket or container (letters, digits, `.`, `-`, `_`, `/`) | | `log_destinations[].credential` | `s3`, `azure_blob` | `auto` | Where the cloud credential comes from: for S3 `env`, `web_identity`, `container` or `cli`; for Azure `client_secret`, `workload_identity` or `managed_identity` | | `log_destinations[].profile` | `s3` | empty | AWS profile name of the shared configuration, for `cli` or `auto` | | `log_destinations[].account_url` | `azure_blob` | required | `https://.blob.core.windows.net` | | `log_destinations[].container` | `azure_blob` | required | Blob container the files go to | | `log_destinations[].endpoint` | `langfuse`, `http` | required | HTTPS address of the Langfuse instance or the HTTP receiver | | `log_destinations[].public_key_env` | `langfuse` | required | Variable holding the Langfuse public key | | `log_destinations[].secret_key_env` | `langfuse` | required | Variable holding the Langfuse secret key | | `log_destinations[].api_key_env` | `datadog` | required | Variable holding the Datadog API key | | `log_destinations[].site` | `datadog` | `datadoghq.com` | Datadog site, such as `datadoghq.eu` or `us5.datadoghq.com` | | `log_destinations[].service` | `datadog` | `ai-gateway` | `service` attribute of each log | | `log_destinations[].auth_header_env` | `http` | empty | Variable holding the whole `Authorization` header value sent to the receiver | | `log_destinations[].flush_seconds` | all | `10` | How often a batch is sent, 1–300 seconds | | `log_destinations[].max_batch` | all | `500` | Records per batch, 1–5000 | | `log_destinations[].allow_insecure_http` | all | `false` | Allows `http://` to a loopback address, for local testing only | Each destination has its own bounded in-memory queue. Full intake drops records instead of delaying inference. Ordinary delivery failures can drop a batch after bounded retries; a missing cloud credential retains a bounded batch with backoff until recovery or retirement. Retries may duplicate delivery. **Settings & sources** shows current worker-generation status and can send a correlated synthetic test record. This is best-effort export, not durable or exactly-once delivery. ## Metrics (Prometheus) The feature flag `metrics_endpoint` turns on `GET /metrics`, in the Prometheus text format. It is an operator control: set it in the `features` block of the gateway YAML (`metrics_endpoint: true`, as the bundled configuration does) or toggle it at runtime from **Settings → Features** or `PUT /api/admin/features/metrics_endpoint`; with it off, `/metrics` answers 404 `feature_disabled`. It is named by what it serves, not by the format; until 0.0.1-rc.2 it was `prometheus_metrics`, which is now refused naming `metrics_endpoint`, and a stored override under the old id is renamed by migration 195 ([upgrading from 0.0.1-rc.2](/docs/operate/operations/#upgrading-from-001-rc2-infrastructure-names)). Do not confuse it with `telemetry.otlp.metrics_endpoint`, the OTLP receiver address of the `otlp_metrics` push below. With `metrics_endpoint`, `/metrics` exposes: - requests by route and status, with a duration histogram; - attempts by provider, model and outcome; - `gateway_provider_errors_total{provider,model,class}`: failed provider attempts, `class` one of `transport` (connection error or timeout), `invalid_response`, `status_5xx`, `status_429`, `stream_interrupted` (the provider cut an answer that had already started: a stream after its first byte, or a body on the buffered relay; that attempt is also in `gateway_upstream_attempts_total` as `result="response"`, because its headers arrived). Client cancellations and administrator stops are not provider errors; - `gateway_usage_write_failures_total`: usage records the gateway could not persist (the request was served; its usage row is missing); - with a database, `gateway_database_up` and `gateway_database_ping_seconds` (see [high availability](/docs/operate/kubernetes-availability/#process-drain)); with `secret_manager`, `gateway_secret_manager_secrets` and `gateway_secret_manager_failing_secrets`; - in-flight requests, heap, goroutines and dropped OTLP records; - `gateway_request_events_written_total` and `gateway_request_events_dropped_total{reason}` (`queue_full`, `write_error`), with [request audit events](/docs/features/request-events/) on; - `gateway_log_queue_waits_total` (log records whose caller waited because the queue was full) and `gateway_log_queue_failed_total` (queued records whose handler failed while being written), with [asynchronous log writes](#asynchronous-log-writes) (`logging.write_mode: async`, the default); - With `inference_request_metrics` (operator flag, off by default): `gateway_inference_requests_total{provider,model,streaming,outcome}` and the `gateway_inference_request_duration_seconds` histogram with the same labels, one count per finished inference request ([below](#inference-series)); - With `pricing_coverage` (operator flag, off by default; requires `usage_valuation`): `gateway_pricing_coverage_total{provider,model,status}`, every answered model call by whether its cost could be computed ([below](#inference-series)); - With [`rate_limit_observe_mode`](/docs/features/rate-limits/#observe-only-policies): `gateway_rate_limit_would_limit_total{policy}`, the requests an observe-only rate policy admitted past its limit; - With [`evaluation_metrics`](/docs/features/evaluation-metrics/): `gateway_evaluations_total`, `gateway_evaluation_score`, `gateway_evaluation_runs_total`, `gateway_evaluation_judge_cost_usd_total`, `gateway_evaluation_pending` and `gateway_evaluation_label_overflow_total`, with bounded evaluation, value and team labels. With [`evaluation_monitors`](/docs/features/evaluation-monitors/#metrics-and-logs): `gateway_evaluation_monitor_evaluations_total{type,outcome}` and `gateway_evaluation_monitor_transitions_total{type,kind}`. - `gateway_topics_units_total{facet,topic,origin}` and `gateway_topics_fits_total{kind,status}` ([Topics](/docs/features/topics/#telemetry)): units assigned by a fit (`initial`) or as they arrive (`online`), and fits by kind and status. `topic` is `assigned` or `outlier`; with `topics.metric_topic_labels: N` it names the N largest topics of each facet and folds the rest into `other`. - `gateway_guardrail_findings_total{guardrail,outcome}` (`masked`, `blocked`, and `would_block`/`would_mask` for [monitor guardrails](/docs/features/guardrails/#monitor-mode-try-a-guardrail-before-enforcing-it); `misconfigured` counts the checks of a [judge guardrail](/docs/features/judge-guardrails/#keeping-it-working) that cannot decide for a reason of configuration), `gateway_alert_deliveries_total{channel,outcome}`, `gateway_alert_rule_alerts_total{transition,severity,scope,source}` and `gateway_alert_rule_scans_total{outcome}` (the [alert rules](/docs/features/alert-rules/#alerts-as-telemetry)), `gateway_mcp_health_checks_total{server,outcome}` and `gateway_admin_bearer_failures_total{reason}` (rejected admin API Bearer calls with the shared token: `invalid`, `too_short`, `rate_limited`; see [the console](/docs/features/console/#automation-with-token_bearer)), `gateway_console_login_rejections_total{reason}` (refused console token sign-ins: `invalid`, `locked_out`) and `gateway_console_login_lockouts_total` (client addresses locked out; see [lockout after failed sign-ins](/docs/features/console/#lockout-after-failed-sign-ins)); - `gateway_caller_concurrency_in_flight{subject}` (`key`, `team`) and `gateway_caller_concurrency_admission_total{result}` (`admitted`, `refused`), with [concurrency caps per key and team](/docs/features/access-control/#concurrent-requests-per-key-and-team) on; - per-target capacity and semantic cache, described in the [routing](/docs/features/routing-and-admission/#how-to-monitor-it) and [cache](/docs/features/semantic-cache/) guides; - the [exact cache series](#exact-cache-series): lookups, stores, shared-backend calls and the cache in use; - with `span_store`, the span writer's series: `gateway_span_store_spans_total{kind,result}`, `gateway_span_store_queued_requests_total`, `gateway_span_store_queue_depth`, `gateway_span_store_batches_total{result}`, `gateway_span_store_ledger_reads_total` and the `gateway_span_store_write_seconds` histogram ([span store metrics](/docs/features/traces/#metrics)); - the inference series below: tokens, cost, time to first token, provider latency, circuit state, fallbacks and remaining budget. Labels come only from configuration (route, status, provider, model, guardrail or channel IDs); never a request ID, user or content. Protect `/metrics` with a network or ingress policy. ### Inference series | Series | Type | Labels | Measured | | --- | --- | --- | --- | | `gateway_tokens_total` | counter | `provider`, `model`, `type` (`input`, `output`, `cached`, `cache_write`, `reasoning`) | Tokens the provider reported for a finished request, the same values the usage ledger records. A count the provider did not report is not added (unknown is not zero). Streams count only when their usage is known ([usage in streams](/docs/features/stream-usage/)). With OpenAI-style usage, `cached` is part of `input` (the prompt tokens read from the provider's cache), so do not add the two. `cache_write` is what the provider wrote to its prompt cache (Anthropic's cache creation tokens) and `reasoning` the output spent reasoning, which providers count within `output`. | | `gateway_cost_usd_total` | counter | `provider`, `model`, and `price_source` with `cost_price_source_label` | The request cost in USD when its valuation is known (`usage_valuation`, a price, proven usage, a successful answer); the value is the one sent in the cost header. An unknown cost is never counted. Prometheus stores a float: the ledger stays the exact record. With the operator flag `cost_price_source_label` (off by default) each series also says where the price came from: `catalog` (an automatic price catalog), `price_book` (an operator's [price book](/docs/features/automatic-pricing/) entry where no automatic price existed) or `price_book_override` (a price book entry that replaced an available automatic price). Turning the flag on starts new series with the label beside the old unlabelled ones, which stop growing; sum by `provider, model` to read both. | | `gateway_inference_requests_total` | counter | `provider`, `model`, `streaming` (`true`, `false`), `outcome` (`ok`, `error`, `canceled`) | With `inference_request_metrics`: every finished inference request once, by the configured provider and model that served it. `canceled` is a client that went away (`499`, or a stream it stopped reading) and is not an error; `error` is any other failure, an error status or an answer the provider or the gateway cut short. A retry or fallback inside the request is one request here (attempts are in `gateway_upstream_attempts_total`). | | `gateway_pricing_coverage_total` | counter | `provider`, `model`, `status` (`complete`, `partial`, `inconsistent`, `unavailable`) | With `pricing_coverage`: every answered call (a 2xx answer) once, by whether its cost could be computed from the same valuation the ledger records. `complete`: a known cost, a valid zero included (an exact-cache hit). `partial`: the final usage did not arrive whole, or a cached-token category has no published price (`partial_counters`, `usage_unreported`, `cache_usage_unreported`, `cache_price_unavailable`, `image_output_split_unreported`, `service_tier_unreported`), or the durable outcome of the call is not settled yet. `inconsistent`: the reported counters are negative or do not add up (cached tokens above the input), or a known amount does not equal its parts. `unavailable`: no price applies (no rate, an unsupported rate, a model the rate does not name). The status never changes the cost: it describes it. A failed call is not counted. The same status of each stored call is the `pricing_status` dimension of [`/analytics/query`](/docs/features/usage-valuation/#pricing-coverage). Coverage of a window is `sum by (status) (increase(gateway_pricing_coverage_total[1h]))`; a window without samples is unknown coverage, not full coverage. | | `gateway_inference_request_duration_seconds` | histogram | as above | With `inference_request_metrics`: the end-to-end duration of the same requests, so a streamed answer's latency is read apart from a buffered one's. | | `gateway_time_to_first_token_seconds` | histogram | `provider`, `model` | Streamed answers with status below 400: from the request start to the first body byte the client received. | | `gateway_provider_latency_seconds` | histogram | `provider`, `model`, `result` | Each provider attempt, like the attempt span: from the attempt start (destination admission included) until the response headers or a transport failure. `result` is the attempt outcome of `gateway_upstream_attempts_total`. | | `gateway_circuit_breaker_state` | gauge | `provider`, `model` (upstream model), `state` (`closed`, `open`, `half_open`) | Number of circuit-breaker destinations of this replica in each state, read at collection. Present with `circuit_breaker`; destinations appear after their first attempt and reset when the configuration changes. | | `gateway_fallbacks_total` | counter | `model`, `kind` (`target`, `context_window`, `content_policy`) | `target`: each move to another target of the same model during a request. `context_window`/`content_policy`: each time a [semantic fallback](/docs/features/routing-strategies/#semantic-fallbacks) is dispatched. | | `gateway_budget_remaining_usd` | gauge | `policy` | Remaining USD of each configured budget policy (`budget_usd`) in its current period, with `budget_limits` and a database. Per-end-user policies are not exported. Read from the shared ledger once per collection, bounded by `storage.database.acquire_timeout`; a failed read emits no series. Every replica reports the same value: aggregate with `max`, not `sum`. | **Cardinality bound.** `provider` and `model` are configured IDs: the provider ID and the model ID that served the request (the canonical model, not a client-sent alias). Any other value, such as a name that is not in the current configuration, is recorded as `other`. `type`, `result`, `state` and `kind` are fixed words, `policy` a configured policy ID. `gateway_tokens_total`, `gateway_cost_usd_total`, `gateway_time_to_first_token_seconds`, `gateway_provider_latency_seconds`, `gateway_provider_errors_total` and `gateway_fallbacks_total` also hold at most 2,048 label sets each per process (the breaker gauge is bounded by the breaker's own 4,096 destinations, the budget gauge by the configured policies); past that, new label sets are recorded with `provider` and `model` set to `other`, so a configuration that changes many times cannot grow a family without bound. A series for a provider or model you remove stays until the process restarts, like the other Prometheus counters. No key ID, user, team, request ID, end user, tag or other client-controlled value is a label. Examples: ```promql # Output tokens per second by model, the autoscaling signal sum by (model) (rate(gateway_tokens_total{type="output"}[2m])) # p95 time to first token histogram_quantile(0.95, sum by (le, model) (rate(gateway_time_to_first_token_seconds_bucket[5m]))) # Spend per hour by provider sum by (provider) (increase(gateway_cost_usd_total[1h])) # Share of spend valued at a price book entry (cost_price_source_label) sum(increase(gateway_cost_usd_total{price_source=~"price_book.*"}[1h])) / sum(increase(gateway_cost_usd_total{price_source!=""}[1h])) # Error rate without the clients that gave up (inference_request_metrics) sum(rate(gateway_inference_requests_total{outcome="error"}[5m])) / sum(rate(gateway_inference_requests_total{outcome!="canceled"}[5m])) # p95 of streamed requests histogram_quantile(0.95, sum by (le) (rate(gateway_inference_request_duration_seconds_bucket{streaming="true"}[5m]))) # Open circuits sum by (provider, model) (gateway_circuit_breaker_state{state="open"}) > 0 # Remaining budget (same value on every replica) max by (policy) (gateway_budget_remaining_usd) ``` ### Exact cache series The [exact cache](/docs/features/exact-cache/) of embeddings and moderations (T057). Each family appears once the first matching event happens, except the gauge, which is always there. No alias, key, team or backend address is a label: every label value is one of the fixed words below. | Series | Type | Labels | Measured | | --- | --- | --- | --- | | `gateway_exact_cache_lookups_total` | counter | `result` (`hit`, `miss`, `bypass`), `reason` | Each embeddings or moderations request, once. `hit` and `miss` carry `reason="none"`; a `bypass` (the cache was not consulted, no `X-Gateway-Cache` header on the answer) carries why, below. Other operations are not counted. | | `gateway_exact_cache_stores_total` | counter | `result` (`stored`, `skipped`, `failed`), `reason` | What became of each `miss`'s answer: kept (`stored`, `reason="none"`), not kept by rule (`skipped`, with the reason) or refused by the shared backend (`failed`, `reason="backend_error"`). A miss whose provider call failed before any answer adds nothing. | | `gateway_cache_backend_operation_duration_seconds` | histogram | `operation` (`validate`, `generation`, `purge`, `get`, `set`), `result` (`ok`, `error`) | Each call to the shared cache backend (Redis or Memcached, `distributed_exact_cache`): the boot and console checks (`validate`), reading or moving the shared generation marker (`generation`, `purge`), the lookup (`get`) and the write (`set`). Buckets from 0.5 ms to 2.5 s; `_count` is the number of calls. | | `gateway_cache_backend_errors_total` | counter | `operation` | The calls above that failed (timeout, refused connection, TLS, protocol). A failed lookup is a `bypass` with `reason="backend_error"`: the request goes to the provider, never fails because of the cache. | | `gateway_exact_cache_backend` | gauge | `backend` (`memory`, `distributed`) | 1 for the cache that serves: `memory` (per replica) or `distributed` (the shared backend). Both 0 when `exact_cache` is off, the backend configuration is invalid, or a shared backend is configured while `distributed_exact_cache` is off, which bypasses every lookup. | Bypass reasons (`gateway_exact_cache_lookups_total{result="bypass"}`): | `reason` | Meaning | | --- | --- | | `feature_disabled` | `exact_cache` is off. | | `distributed_disabled` | A shared backend is configured and `distributed_exact_cache` is off: the gateway does not fall back to memory, so nothing is cached. The boot log warns with `exact_cache_bypassed` (`reason: distributed_disabled`). | | `backend_unavailable` | The cache backend configuration is invalid (the boot check refused it). | | `provider_network` | The alias's provider network policy is not ready (`provider_network`). | | `alias_disabled` | The alias has no `cache` policy, or `cache.enabled: false`. | | `not_requested` | The request did not send exactly one `X-Gateway-Cache: allow`. | | `client_directive` | The request sent `Cache-Control`, `Pragma`, `Cookie` or `Range`. | | `uncacheable_request` | The alias has more than one target, the body is not a JSON object, asks for a stream, or (moderations) names a remote image. | | `no_key` | No authenticated key (the cache key needs one). | | `canceled` | The client left before the lookup finished. | | `config_changed` | A new configuration was published during the lookup. | | `backend_error` | A shared-backend call failed; see `gateway_cache_backend_errors_total`. | | `invalid_entry` | The shared backend returned an entry the gateway does not trust (another provider, an invalid body): it is not served. | Skipped-store reasons (`gateway_exact_cache_stores_total{result="skipped"}`): `response_status` (not a `200`), `too_large` (over `cache_backend.max_response_bytes`, or the entry over the byte budget), `response_vary` (`Vary: *` or a `Vary` naming a header the key does not cover; see [what is stored](/docs/features/exact-cache/#what-is-stored)), `response_headers` (`Cache-Control`, `Pragma`, an authentication challenge, `Authorization`, `Cookie`, `Set-Cookie2`, `Content-Encoding`, `Content-Range` or trailers), `content_type` (not JSON), `incomplete` (cut short, a length mismatch, the client left), `invalid_body` (no `data` or `results`, or an `error` field) and `config_changed`. ```promql # Hit ratio of the exact cache over the fleet sum(rate(gateway_exact_cache_lookups_total{result="hit"}[15m])) / sum(rate(gateway_exact_cache_lookups_total{result=~"hit|miss"}[15m])) # Why answers are not kept sum by (reason) (increase(gateway_exact_cache_stores_total{result="skipped"}[1h])) # p99 of the shared backend's lookups histogram_quantile(0.99, sum by (le) (rate(gateway_cache_backend_operation_duration_seconds_bucket{operation="get"}[5m]))) ``` A cache whose answers are all `miss` while `stores_total{result="skipped"}` grows is refusing what the provider returns; the `GatewayExactCacheNotStoring` [alert](#alert-rules) fires on it. ### Control snapshot freshness With `control_snapshot_metrics` (off by default), each replica also exports how current its control configuration is (T168): | Series | Type | Meaning | | --- | --- | --- | | `gateway_control_version` | gauge | The control configuration version this replica applies | | `gateway_control_refresh_age_seconds` | gauge | Seconds since its last successful refresh; absent until the first one | | `gateway_control_refresh_failures_total` | counter | Refreshes that failed; the replica keeps serving its last valid snapshot. A refresh cut short by its own request's cancellation or deadline is not counted | Replicas normally converge within one refresh interval. Useful queries: `max(gateway_control_version) - min(gateway_control_version)` (divergence across replicas), `max(gateway_control_refresh_age_seconds)` (the most stale replica) and `increase(gateway_control_refresh_failures_total[10m])`. The values describe what this replica applied, not what others did; no label carries request or tenant data. ### Model server metrics A self-hosted model server knows things the gateway cannot see from outside: how many requests wait in its queue, how full its cache is, how long its own first token takes. vLLM and llama.cpp publish them as Prometheus metrics. With `provider_metrics_scrape` on, the gateway reads them from each connection you opt in and shows them in `/metrics`, and through it in [OTLP metrics](#otlp-metrics), next to its own series for the same connection. The replicas of a [local inference](/docs/features/local-inference/) pool need no setting here: llama.cpp and vLLM replicas declare `/metrics` themselves, and the pool screen reads their running and waiting requests from the scrape. Turn it on in this order: 1. Give each model server its own connection (`providers[]`). Two replicas of one model are two connections, and the connection ID is how you tell their series apart. 2. Set `metrics_path` on each one, in the YAML or in the console's provider form (**Model server metrics path**). For vLLM and llama.cpp it is `/metrics`. 3. Turn the flag on. It is an operator flag, off by default, and applies without a restart. ```yaml features: provider_metrics_scrape: true providers: - {id: vr1, protocol: openai, base_url: http://10.0.0.5:8001/v1, api_key_env: LOCAL_PROVIDER_KEY, metrics_path: /metrics} - {id: vr2, protocol: openai, base_url: http://10.0.0.5:8002/v1, api_key_env: LOCAL_PROVIDER_KEY, metrics_path: /metrics} provider_metrics: # every field optional; read on each cycle, no restart interval: 15s timeout: 2s max_series: 500 allow: ["vllm:", "llamacpp:"] ``` What you get in `/metrics`, with the server's own names and the connection as the `provider` label: ```text # TYPE vllm:num_requests_running gauge vllm:num_requests_running{provider="vr1",model_name="qwen05"} 3 vllm:num_requests_running{provider="vr2",model_name="qwen05"} 5 gateway_provider_metrics_up{provider="vr1"} 1 gateway_provider_metrics_series{provider="vr1"} 349 ``` | Setting | Default | Bounds | What it does | | --- | --- | --- | --- | | `providers[].metrics_path` | empty (not scraped) | an absolute path of at most 256 letters, digits and `._~/-`; no `.` or `..` segment, no `//` | The path of the server's metrics. It is read on the host of `base_url` (scheme, host and port; the `/v1` of `base_url` is left out) and never on another host. At most 64 connections may set it | | `providers[].metrics_credential` | `false` | needs `metrics_path`, bearer authentication with one static secret and no credential pool | Sends the connection's bearer secret with the scrape. Use it only for a server that protects its metrics with its key (llama.cpp started with an API key does; vLLM does not) | | `provider_metrics.interval` | `15s` | 5s to 5m | How often each connection is scraped | | `provider_metrics.timeout` | `2s` | 100ms to 30s, at most `interval` | The bound of one scrape | | `provider_metrics.max_series` | `500` | 50 to 5,000 | The most series kept from one connection. A family that does not fit is dropped whole, so a histogram never loses some of its buckets | | `provider_metrics.allow` | `["vllm:", "llamacpp:"]` | 1 to 16 prefixes of 1 to 64 metric name characters; a prefix of `gateway_` is refused | Only families whose name starts with one of these are kept; the rest of what the server publishes (runtime and process metrics) is ignored | The gateway's own series about the scrape, one per connection: | Series | Type | Meaning | | --- | --- | --- | | `gateway_provider_metrics_up{provider}` | gauge | 1 while the last scrape succeeded, 0 after a failed one | | `gateway_provider_metrics_series{provider}` | gauge | Series kept from the last scrape | | `gateway_provider_metrics_scrapes_total{provider,result}` | counter | Scrapes by `result`: `ok` or `failed` | | `gateway_provider_metrics_dropped_series_total{provider}` | counter | Series left out for a bound: the series limit, more than 16 labels, an invalid label name, a label value over 128 bytes or with a control character, a repeated series or a value that is not a number | How it behaves: - **A failed scrape drops that connection's series.** A queue length from a minute ago is worse than none: alert on `gateway_provider_metrics_up == 0` instead. The gateway logs `provider_metrics_scrape_failed` once when a connection starts failing, with a fixed `reason` (`transport`, `timeout`, `status`, `too_large`, `redirect`, `credential`, `invalid_answer` or `empty_answer`), and the provider card in the console shows the same state. - **`empty_answer` means the path answered but nothing matched `allow`:** most often the wrong path or a server with another metric prefix. Add the prefix to `allow`. - **Only counters, gauges and histograms are kept.** A label called `provider` on the server's side becomes `exported_provider`. A series with a label value over 128 bytes or with a control character, and a series the server repeats, is dropped and counted, never altered. The answer is read up to 1 MiB; a larger one fails the scrape. - **The scrape sends nothing of a client's request,** follows no redirect and goes through the connection's [network profile](/docs/features/provider-network/) (proxy, CA, mutual TLS). The scraped values are never logged and are not used for routing, health checks, usage or cost. - **Each gateway replica scrapes on its own.** With three replicas, Prometheus sees each model server series three times, told apart by the gateway instance; aggregate with `max by (provider)` for gauges. Scale the extra series as connections × `max_series` × replicas. - **Where to see the settings:** the provider card shows the last scrape (`Metrics /metrics · 349 series`), the Providers page shows the effective `provider_metrics` values, and `GET /api/v1/admin/config` returns them as `provider_metrics` and, per connection, `metrics_path`, `metrics_credential` and `metrics_scrape`. The settings are changed in the YAML; the path and the credential choice also in the console. Useful queries: `sum by (provider) (vllm:num_requests_waiting)` (the queue behind each replica), `vllm:kv_cache_usage_perc` (how full each replica's cache is) and, for tokens per second while generating, `rate(vllm:generation_tokens_total[2m]) / rate(vllm:request_decode_time_seconds_sum[2m])`. ## Alert rules `deploy/observability/alert-rules.yml` holds Prometheus alert rules for the operational failures the gateway can see. The bundled Prometheus (`kubectl apply -k deploy/observability`) loads them. With the Prometheus Operator, the Helm chart ships the same file as a `PrometheusRule` when you set `serviceMonitor.enabled` and `serviceMonitor.alertRules` (both off by default): ```yaml serviceMonitor: enabled: true alertRules: true labels: {release: prometheus} # must match your Prometheus's serviceMonitorSelector and ruleSelector ``` Every threshold and `for` below is a **default to tune** to your traffic, not a measured recommendation. Edit the file (and the chart copy `deploy/helm/gateway/files/alert-rules.yml`, which the chart check compares byte for byte), then validate it: ```sh docker run --rm --entrypoint promtool -v "$PWD/deploy/observability:/rules:ro" -w /rules \ prom/prometheus:v3.1.0@sha256:6559acbd5d770b15bb3c954629ce190ac3cbbdb2b7f1c30f0385c4e05104e218 \ check rules alert-rules.yml docker run --rm --entrypoint promtool -v "$PWD/deploy/observability:/rules:ro" -w /rules \ prom/prometheus:v3.1.0@sha256:6559acbd5d770b15bb3c954629ce190ac3cbbdb2b7f1c30f0385c4e05104e218 \ test rules alert-rules-test.yml ``` `alert-rules-test.yml` checks that each rule fires after its `for` and not on a short blip or at low traffic. | Alert | Expression (summary) | `for` | Severity | | --- | --- | --- | --- | | `GatewayCircuitOpen` | `gateway_circuit_breaker_state{state="open"}` above 0 by provider and model | 1m | critical | | `GatewayProviderErrorRateHigh` | provider errors / attempts (without client cancellations) above **0.2** over 5m, with at least **20** attempts in the window | 10m | critical | | `GatewayProviderSlow` | p95 of `gateway_provider_latency_seconds{result="response"}` above **30 s** over 10m, with at least 20 answers | 15m | warning | | `GatewayDatabaseDown` | `gateway_database_up == 0` on a replica | 2m | critical | | `GatewayUsageWriteFailures` | any `gateway_usage_write_failures_total` increase in 10m | 0m | critical | | `GatewaySecretManagerFailing` | `gateway_secret_manager_failing_secrets > 0` | 15m | warning | | `GatewayTelemetryDropping` | `gateway_otel_dropped_total` rising in every 5m window, by signal | 15m | warning | | `GatewayExactCacheNotStoring` | at least **20** answers of a miss skipped or failed to store over 30m (provider errors left out), and none stored | 15m | warning | Notes on reading them: - **Circuit open** sums the replicas that report the destination open. A provider that keeps failing passes through `half_open`, which resets `for`; the error-rate alert covers that case. - **Provider slow** measures until the response headers. A non-streaming answer arrives whole, so long generations raise it: raise the threshold for reasoning models or watch [time to first token](#inference-series) instead. - **Usage write failures** fire on a single failure: the request was served and its usage row (spend, quota, analytics) is missing. - **Secret manager**: a failing secret keeps serving its last good value, so requests show nothing until the credential rotates. - **Exact cache not storing** means every lookup is a `miss`: the answers come back but a rule refuses them. The `reason` of `gateway_exact_cache_stores_total` names the rule. Distinct inputs do not fire it (their answers are still stored), and neither does a provider outage (`response_status` is left out). ### SLO rules `deploy/observability/slo-rules.yml` (T168) adds an availability objective and alerts on how fast its error budget burns. It is optional and off by default: with the Helm chart set `serviceMonitor.sloRules: true` (next to `serviceMonitor.enabled`) for a second `PrometheusRule`; with the bundled Prometheus, uncomment `/etc/prometheus/slo-rules.yml` in `deploy/observability/prometheus.yml` (the file is already in its ConfigMap). ```yaml serviceMonitor: enabled: true sloRules: true labels: {release: prometheus} ``` - **SLI:** the share of inference requests answered without a 5xx, from `gateway_http_requests_total` summed over every replica. Inference routes are Chat and text completions, Responses, Messages, embeddings, moderations, rerank, images, audio, video generations, OCR, Decisions, System One and Gemini `/v1beta/models/...`. Catalogs, files, batches, vector stores, MCP and administrative routes are left out, so cheap reads cannot dilute the ratio. A `429` or another 4xx counts as a request, not an error: it is the gateway applying a limit, not failing. - **Objective:** 99.5% (error budget 0.005). To change it, replace `0.005` in the two alerts; the recording rules do not depend on it. - **Recording rules:** `gateway:inference_requests:rate`, `gateway:inference_errors:rate` and `gateway:inference_error_ratio:rate` for the windows 5m, 30m, 1h and 6h. With no traffic in a window the ratio has no value, so an idle gateway neither fires nor counts as healthy. | Alert | Fires when | `for` | Severity | | --- | --- | --- | --- | | `GatewayInferenceErrorBudgetFastBurn` | the 5m and the 1h error ratios are both above 14.4 × 0.005 (7.2%): a 30-day budget gone in about two days | 2m | critical | | `GatewayInferenceErrorBudgetSlowBurn` | the 30m and the 6h error ratios are both above 6 × 0.005 (3%): the budget gone in five days | 15m | warning | The long window proves the burn is sustained; the short one clears the alert soon after recovery, and its ratio is the value the alert reports. Both alerts carry `slo: inference_availability`. Validate after editing, the same way as the alert rules (`check rules slo-rules.yml`, `test rules slo-rules-test.yml`); the chart copy `deploy/helm/gateway/files/slo-rules.yml` is compared byte for byte. These rules measure what the gateway answered; they do not certify an objective for a deployment, which stays the operator's to set and review. ### Alert events without Prometheus With `features.operational_alerts` (off by default; requires `alert_channels`), each replica also sends the same conditions to the [alert channels](/docs/features/alerting/#operational-events) that subscribe to them, on state transitions only. See [operational events](/docs/features/alerting/#operational-events). ## OTLP metrics The `otlp_metrics` boot flag (off by default, operator control, restart required) pushes the same series `/metrics` serves to an OTLP/HTTP receiver, such as an OpenTelemetry Collector. It does not need `metrics_endpoint`, and it changes nothing in `/metrics`. ```yaml features: otlp_metrics: true telemetry: otlp: protocol: http/protobuf # shared with logs and traces metrics_endpoint: http://collector:4318/v1/metrics metrics_interval: 60s metrics_timeout: 10s ``` | Field | Default | Bounds | Environment override | | --- | --- | --- | --- | | `telemetry.otlp.metrics_endpoint` | `http://127.0.0.1:4318/v1/metrics` | Same rules as the other endpoints: absolute `http`/`https`, valid host and port, no user info, query or fragment, up to 2,048 bytes | `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` | | `telemetry.otlp.metrics_interval` | `60s` | `1s` to `1h` | `OTEL_METRIC_EXPORT_INTERVAL` (milliseconds) | | `telemetry.otlp.metrics_timeout` | `10s`, or the interval when that is shorter | `100ms` to `1m`; an explicit value must not exceed the interval | `OTEL_METRIC_EXPORT_TIMEOUT` (milliseconds) | | `telemetry.otlp.protocol` | `http/protobuf` | `http/protobuf` or `http/json` | `OTEL_EXPORTER_OTLP_PROTOCOL` | The values are captured once at startup; the source of the endpoint (`default`, `yaml`, `environment`) appears in the `telemetry_boot` log and in the infrastructure view of the console, never the URL. YAML values are validated even with the flag off; an invalid value with the flag on stops the boot with the setting named. What the receiver gets: one `ExportMetricsServiceRequest` per interval with resource `service.name=ai-gateway` and scope `ai-gateway`. Each Prometheus family keeps its name and labels (as attributes): counters become cumulative monotonic sums, gauges stay gauges and histograms become cumulative explicit-bucket histograms with the same bounds. Units come from the name (`s`, `By`, `{token}`, `USD`). Start time is the process start. Behavior and failure: - One background worker collects a snapshot and sends it; nothing waits on it in the request path. There is no queue: every value is cumulative, so a send still running when the next interval comes skips that interval, and a failed send loses only that snapshot (the next carries the totals). - A Collector that is down, slow or rejecting costs only telemetry: the send is abandoned after `metrics_timeout`, its data points are added to `gateway_otel_dropped_total{signal="metrics"}`, and one `otlp_metrics_export_failed` warning (with a fixed reason: `unreachable`, `timeout`, `status_`, never the endpoint) is logged per failure streak, then `otlp_metrics_export_recovered` when sends succeed again. - On shutdown the exporter abandons a send in progress (the final snapshot carries its totals) and sends one last snapshot, bounded by `metrics_timeout` and at most 2 seconds, before the database closes. The shipped grace (180s) and the Helm cleanup allowance already include those 2 seconds; add them to a [shutdown grace period](/docs/operate/shutdown/#size-the-external-grace-period) you size yourself. - Collection takes the same locks as a `/metrics` scrape and, like a scrape, pings the database and, with `budget_limits`, reads budget remainders in one short transaction, each bounded by `storage.database.acquire_timeout`. Both hold a pool connection while they run, so a very frequent scrape or interval competes with requests for the pool. The example Collector configuration (`deploy/base/collector.yaml` and the Helm copy) has a `metrics` pipeline to the `debug` exporter. Helm sets `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` to its Collector (or `gateway.otlpMetricsEndpoint`); it is used only when `features.otlp_metrics` is on in the gateway YAML. Do not scrape `/metrics` and receive OTLP metrics into the same backend for the same replicas, or every series is counted twice. On Kubernetes with the Prometheus Operator, the Helm chart can render a ServiceMonitor for `/metrics` (`serviceMonitor.enabled`), and its optional NetworkPolicy limits who reaches the port that serves it (`networkPolicy.ingressFrom`); see [operations](/docs/operate/operations/#servicemonitor). ## Grafana (optional) The repository ships a provisioned Grafana dashboard (`deploy/observability/gateway.json`), a Prometheus that scrapes `/metrics` every 15 s and a Kustomize overlay to install them. The dashboard follows an SRE investigation: volume → success and p95 → slow route → attempts per provider → heap and goroutines → telemetry losses. You can also point your own Prometheus and Grafana at it. In the overlay, Prometheus and Grafana use `emptyDir`: the data is lost when the pod is recreated. The example Collector uses the `debug` exporter; connect a real backend for historical search. ## Limits - No payload capture: a call cannot be reproduced exactly. - The duration in stream metrics is measured at the end of the request; for attempts, up to the provider's headers. - PostgreSQL backup and retention are an operations responsibility; see [metadata retention](/docs/features/metadata-retention/). - Queue, circuit, cache, caller concurrency and the inference counters are per replica; sum them across replicas, except `gateway_budget_remaining_usd` (shared, use `max`). ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `GET /api/v1/admin/agent-runs` | Lists the coding-agent runs recognized in a time range, most recent first; `agent_recognition`, `logs:read` ([agent runs](/docs/features/agent-recognition/#api)) | | `GET /api/v1/admin/agent-runs/{id}` | One run as a thread: its model calls, reported tool steps, subagent branches and compaction dividers | | `GET /api/v1/admin/agent-runs/settings` | The effective `agent_recognition` block and the client rules in the order they are tried; `config:read` | | `POST /api/v1/admin/log-destinations/{id}/test` | Queues one synthetic record and flushes the destination now, to see the object written or the failure | ## See also - [Observability](/docs/features/feature-observability/): overview. - [Analytics](/docs/features/analytics-experience/), [analytics export](/docs/features/analytics-export/) and [alerts](/docs/features/alerting/). - [Usage in streams](/docs/features/stream-usage/) and [durable receipts](/docs/features/durable-usage/). ## Inspect external integration boot policies The read-only **Settings & sources → Inspect session, vector and integration policies** section and `GET /api/v1/admin/config` expose `infrastructure.integration_settings` to authorized global readers when `boot_settings_view` is enabled. Existing `secret_manager` and `log_destinations` flags still control operational behavior. The summary does not fetch a secret, contact a destination, activate an integration or replace the privileged status/test interfaces. For the secret manager, the view reports whether a manager was declared, an allowlisted manager kind and the existing `secret_manager.refresh_seconds` policy (default `300`, valid 10–86,400 seconds). It never reports credential names, addresses, namespace/path prefixes, authentication references, or fetched values. “Declared” does not mean authenticated, resolved or healthy. For log destinations, it reports the declaration count (at most ten) and declaration-ordered entries containing only a known destination type and two existing policies: | YAML parameter per destination | Default | Existing bound | | --- | --- | --- | | `flush_seconds` | `10` | 1–300 seconds | | `max_batch` | `500` | 1–5,000 records | Destination numbers are positions in the loaded list, not IDs or delivery-worker identities. No bucket, endpoint, host, path, credential/environment reference, object name or delivery-health data enters this safe projection. Use the existing authorized destination status for actual delivery counters. Every scalar includes its default, decoded `default`/`yaml` source and rollout requirement. Explicit default or zero values retain YAML origin while zero selects the existing fallback. Programmatic factories without decoded provenance report nullable declaration/value/source fields; they do not invent a configuration source. This metadata inspection preserves existing adapters and network behavior; it is not a new external-service or managed-cloud compatibility certification. ## Shared policy constraints The existing minimum-severity enum, integration refresh and destination batching limits use [shared parameter definitions](/docs/reference/parameter-registry/) with their actual Go and console consumers. The JSON/OTLP filtering and captured startup sources retain their existing behavior. Per-signal OTLP destinations, secret references and provider-specific connection schemas stay private; a definition or configured summary does not prove delivery. Boot changes require rollout, and the existing view and authorization controls still apply. ## Manage approved destination instances Enable `features.log_destination_management` (default `false`) with `log_destinations`, `ui` and PostgreSQL. **Settings & sources → Destination configuration** and `GET`, `PUT`, `DELETE /api/v1/admin/log-destination-policy` share a versioned full-list policy and actor/request-ID audit. `destinations:read` belongs to global admin/viewer; `destinations:manage` belongs only to global admin. Neither flag nor template grants permission. Existing status and synthetic-test permissions remain separate. Connection trust belongs to the operator's YAML declarations. A template binds type, target, bucket/account, cloud identity/profile and credential environment references. Runtime requests cannot select another endpoint, reference a new environment variable, or rebind infrastructure identity. The API returns only template ID, one of the six existing types and a sanitized target label; credential references, query strings and secret values remain private. Declare new connection trust in YAML and roll out the gateway before it can be selected in this editor. This restart boundary is explicit; the editor does not provision infrastructure or offer arbitrary secret/endpoint CRUD. For example, declare an approved connection: ```yaml features: ui: true log_destinations: true log_destination_management: true log_destinations: - id: approved_http type: http endpoint: https://logs.example/ingest auth_header_env: LOG_DESTINATION_AUTH flush_seconds: 10 max_batch: 500 ``` The operator supplies `LOG_DESTINATION_AUTH` through the deployment's Secret/environment. The web interface never receives its value or variable name. S3, GCS, Azure Blob, Langfuse and Datadog use their existing YAML connection contracts in the same way. An instance can select any approved template, including a second instance of one template; doing so intentionally exports an additional copy. PUT replaces the whole list, with exactly six fields per row: ```json {"version":4,"destinations":[{"id":"audit_copy","template_id":"approved_http","flush_seconds":10,"max_batch":500,"prefix":"runtime/","service":"ai-gateway"}]} ``` Use the current version and an ID from GET's template list. Up to ten distinct destination IDs are allowed. Batching zero chooses compiled defaults (`10` seconds and `500` records), not a template's custom batching. Prefix and service are exact replacements, including empty strings. Prefix follows the existing relative-path contract (up to 200 allowed characters, no leading slash or `..`); managed service labels are at most 256 UTF-8 bytes. Legacy longer YAML labels remain readable and unchanged, but must be shortened before a managed save. Unknown fields—including endpoint, type, profile, credential and `*_env`—are refused. Duplicate fields, nulls, aliases and invalid types are also refused. `[]` is an explicit policy disabling every destination. DELETE accepts only `{"version":4}` and restores the YAML list; a missing override returns 404. GET separates raw override from normalized effective rows, `source`, `applies_to:"new_completions"`, `restart_required:false` and `trust_requires_restart:true`. The startup inspector remains immutable and count/type/tuning-only. A 409 preserves the draft; reload, review and explicitly adopt the current version before saving. A known access denial cannot be undone by a viewer-only reload. Database/corrupt-snapshot failures retain the previous valid policy; `503 configuration_sync_pending` requires reading current state before retrying a possibly committed write. ### Generations, loss and recovery Each replica reconciles after validating/publishing its snapshot. The global configuration lock is released before any worker cancellation/reap wait. A management refresh can wait for bounded cancellation of an older retired generation while holding only the generation mutex; request intake does not wait for that mutex or network delivery. New completions use the newest available generation, including requests that started before delivery was enabled. A batch accepted by an older worker drains to its old target/credential; removing an instance cannot recall accepted work. Unchanged declarations keep their workers/counters. Replicas converge asynchronously. While `log_destination_management` is enabled, at most the current and one retired generation are retained (at most twenty workers for ten destinations). If another replacement overtakes draining workers, older retired work can be cancelled and lost. In this managed mode, intake never waits for replacement or delivery during a handoff and may drop metadata; the status API's `dropped_during_reconfiguration` counter and console report that process-local loss. Queue limits count records, not a guaranteed memory/RSS ceiling. Each generation has its own counters; replacing one does not produce a durable lifetime total. Missing credentials hold a bounded batch with backoff; shutdown/retirement still has a finite owner and can lose pending work. Disabling management restores the YAML list and historical lock/drain behavior, without the opt-in handoff-drop/obsolete-cancellation policy, but retains the dormant override for re-enable. Disabling delivery retires workers; re-enable creates the current effective generation. Restart reuses the persisted policy and starts new workers; memory queues are not recovered. A failed or slow destination does not delay inference or another destination. Per-record request/trace IDs remain intact. Synthetic tests use the triggering action's IDs. Batch calls propagate a derived request ID and W3C context anchored to the first available request span in the batch, before cloud signing; other records keep their own IDs in the batch. Unknown parentage is not fabricated. No prompt, response or credential is exported by this metadata path. Migration99 stores only nonsecret template IDs and tuning. Back up and roll out all replicas before enabling management. Old binaries refuse the newer schema on startup, and schema downgrade is unsupported. A saved policy referring to a template removed in a later YAML rollout is invalid: update/revert that policy before removing its template. [Upgrade and recovery](/docs/operate/operations/#schema-upgrades-and-pending-branch-adoption). ## Optional client-source recording `client_ip_logging` defaults off and requires the boot `source_ip_controls` profile. It adds only a verified canonical `client_ip` to structured stdout request records and `client.address` to OTLP; raw forwarding chains and IP metric labels are excluded. Private source remains available for authorization after collection opt-out, while a fresh request/internal boundary does not inherit old recording consent. Existing peer diagnostics and configured CIDRs are distinct. This does not add an IP field/filter to SQL log history, UsageEvent, receipts or the financial ledger; external collectors own retention. Persisted addresses with their own retention are the separate [`client_source_metadata`](/docs/security/source-ip-controls/#persisted-client-addresses) profile (T033.003). See [configuration and privacy](/docs/security/source-ip-controls/). ## Credential selection diagnostics Qualified weighted Chat dispatch may report finite configured provider/credential IDs with the existing request/trace context for selection and cooldown transitions. Do not record values, refs, ciphertext, fingerprints or provider payloads. Cooldown signals come only from qualified weighted dispatch response headers; primary/native/catalog calls are outside that monitor. An exhausted pool is not-sent availability, not a provider breaker failure or a paid attempt. The configured console policy is distinct from local observation and fleet health; [scope and recovery](/docs/features/provider-credentials/) describe cold restarts and generation fencing. # Traces and the span store **Last updated:** 2026-11-26T02:16:00-03:00 (UTC-3) The gateway already times and prices every step of a request: the routing decision, each provider attempt, the cache lookup, each guardrail and each MCP tool call. With the **span store** it keeps those steps as **spans** in its own PostgreSQL database, next to the request log, so you can open any request as a tree of timed, costed steps without running a tracing backend. Spans are W3C spans with the same trace and span IDs the gateway already exports over [OTLP](/docs/features/observability/#logs-and-traces-otlp), so the stored tree and your tracing backend line up. The span store never holds content: no prompt, answer, tool argument or result. It holds identifiers, timing, status, tokens, the ledger cost of each step and a short allowlist of attributes per kind. Bodies stay in [content capture](/docs/features/content-capture/), under its own policy. ## Turn it on ```yaml features: usage_analytics: true span_store: true ``` | Flag | Default | What it turns on | | --- | --- | --- | | `span_store` | `false` | The span store: collection on the request path, the writer, partitions, retention, the trace API and the trace drawer. Requires `usage_analytics` and PostgreSQL. An operator control, changeable at runtime from **Settings → Features** or `PUT /api/v1/admin/features/span_store` | | `trace_explorer` | `false` | The [Traces screen and the trace detail](/docs/features/trace-explorer/) over the stored spans. Requires `span_store` | | `analytics_store_spans` | `false` | Copies the stored spans to the [analytics store](/docs/features/analytics-store/). Requires `span_store` and the `analytics_store` block | Spans start when the flag is turned on; nothing is backfilled. A request older than the span store keeps its [request journey](/docs/features/observability/#request-journey) as before. ### Recommended setup Start with the shipped values: `sample_rate: 1.0` (every trace), all four `keep_always` rules, `retention_days: 14`. Watch `gateway_span_store_spans_total{result="dropped_queue_full"}` and the database size for a week. Each request writes 3 to 5 span rows (more with retries, guardrails and tools): at 100 requests per second that is roughly 26 to 43 million rows a day. If an analytics store runs next to the gateway, `spans.engine: analytics_store` takes those rows off the database entirely (see [Where spans are stored](#where-spans-are-stored) and the [measured comparison](/docs/benchmarks/span-store-engines/)). Otherwise, above about 50 requests per second sustained, lower `sample_rate` (errors, fallbacks, flagged and evaluated requests stay kept by `keep_always`) and turn on `analytics_store_spans` so long-range reads can move to the analytics store. ## What a trace holds Each request is one **request span**; its steps are children of it. A trace groups the requests that share a W3C trace ID: requests chained by a client `traceparent`, an agent run's requests, and the calls the gateway makes to itself (a moderation guardrail, embeddings for a vector store search). | Kind | One span per | Cost | Attributes | | --- | --- | --- | --- | | `request` | gateway request, the root of its steps; `subkind` is the operation | the request's valuation, or the sum of its known charge lines when the valuation is partial or unknown | route, status, attempts, `fell_back`, operation, requested model, cache kind, timeout kind, service tier, auto-route alias, blocking guardrail, stream cut, parent session, agent, `ttfb_ms`, `dropped_spans`, `valuation_reason` and the price entry (below), `traceparent: ignored_malformed` | | `routing` | target choice of an alias | `none` | strategy that ordered the targets (`ordered`, `weighted`, `cost`, `least_busy`, `latency`, `adaptive`, `affinity`: the one the enabled feature applied, not merely the one configured), candidates, chosen target, canary side, auto-route alias; `refusal: no_eligible_target` when nothing was eligible | | `provider_attempt` | provider send, in send order, and each target skipped before a send (an open circuit, an unhealthy target, a refused translation, a context window) | the attempt's own charge line; the whole valuation when the request made one send | `attempt`, `final`, `outcome` (`answered`, `provider_error`, `transport_failure` with no HTTP status, `skipped`), wire API, timeout kind, `sent`, skip reason; `fallback_reason` and `retry` (below), `ttfb_ms` on the final answered attempt, the generation parameters the client sent (`gen_ai.request.*`), `parameters_changed`, the price entry | | `cache` | response-cache lookup (exact or semantic) | `none` | kind, `hit`, similarity bucket of a semantic hit | | `guardrail` | guardrail check at the input or output stage | `none` | guardrail ID, stage, `mode` (`block`, `monitor`), outcome, findings | | `tool` | MCP tool call or tool listing | `none` | server, configured tool name, status | | `tool`, sub-kind `client_tool` | tool a coding agent ran itself and reported in its next request ([`agent_recognition`](/docs/features/agent-recognition/#tool-steps)) | `none` | The span is named `client tool`. `tool` (the name) and `call_id`, both only for readers with `content_structure:read` of the span's team; `reported_by: client`, `reported_error`, `agent`; no duration, never arguments or results | | `app`, sub-kinds `transcript_turn`, `transcript_call`, `transcript_tool`, `transcript_compaction` | step of a coding agent's own transcript, uploaded with `POST /v1/traces` ([transcript ingest](/docs/features/agent-recognition/#transcript-ingest)) | `none` | `source: transcript`, `agent`; `tool` and `call_id` of a tool (its span is named `transcript tool`), both only for readers with `content_structure:read`; model and token counts of a call; never content | - **Names** are the names the spans were exported with over OTLP: a request span is `POST /v1/chat/completions`; a model call attempt follows the GenAI convention, `{operation} {provider model}` (`chat gpt-4o-mini`), and other sends ` provider.` (`GET provider.containers`); a skipped target is `provider..skipped`; a tool call `execute_tool ` and a tool listing `MCP operation`. Search your tracing backend by the same name. One exception: a tool a coding agent reported is exported as `execute_tool ` and stored as `client tool` (a transcript's as `transcript tool`), because a stored span's name is shown in every list and the name of such a tool is shown only with `content_structure:read`. - **Why an attempt was made.** Every attempt after the first carries `fallback_reason`, what ended the step before it: `http_` (`http_500`, `http_429`), `timeout`, `transport_error`, `cancelled`, or the skip reason of a skipped target (`circuit_open`); `retry: true` when the same target was sent again (a retry policy), otherwise it fell back to another target. - **Generation parameters.** The numbers the client sent, recorded on each attempt with their OpenTelemetry names: `gen_ai.request.temperature`, `gen_ai.request.top_p`, `gen_ai.request.top_k`, `gen_ai.request.max_tokens` (`max_tokens`, `max_completion_tokens` or `max_output_tokens`), `gen_ai.request.frequency_penalty`, `gen_ai.request.presence_penalty`, `gen_ai.request.seed`, `gen_ai.request.choice.count` (`n`), and `gateway.request.reasoning_effort` (`none`, `minimal`, `low`, `medium`, `high`, `xhigh`). Gemini's `generationConfig` names map to the same keys. Text members (stop sequences, tools, messages) are content and never recorded. When a [request parameter policy](/docs/features/request-parameter-policy/) changed what an attempt sent, the attempt has `parameters_changed: true` and its `upstream_attempt` log line names the parameters. The same `gen_ai.request.*` attributes are on the exported OTLP attempt spans. - **Price entry.** A valued step names the price that valued it (shown to readers with `prices:read` who may see the cost; for others these attributes are left out): `price.source` (the catalog, or `manual` when the [manual price book](/docs/features/pricing/) priced it), `price.override: true` when that manual price replaced an available automatic one (spans stored by earlier versions may carry `price.manual_fallback` instead), `price.input_per_million`, `price.output_per_million` (or `price.unit` and `price.unit_price` for media), `price.effective_from` and `price.model`; the request span also has `valuation_reason` (for example `text_token_estimate`). - **Events.** Spans carry up to 16 events, each `{"name", "time", "attributes"}`: `attempt_failed` (outcome, `http_status` or `cause`, timeout kind), `retry` and `fallback` (reason), `target_skipped` (reason), and on the request span `refused` (the gateway's `error_code` and HTTP status, for a 4xx refusal other than a client's 499), `quota_refused` (policy, dimension, reset time, and the limit for the caller's own ceiling) and `traceparent_ignored`. Events are gateway facts, never provider bodies or stack traces. - **Helper calls** (a guardrail's moderation call, embeddings) are `request` spans with `origin: helper`, children of the request that made them. `origin` also marks the gateway's own traffic: `evaluation` (judges), `experiment` (experiment items), `playground` (evaluator tests), `shadow` (canary shadow copies); client traffic is `app`. - The kinds `judge` and `app` are reserved: judge runs and application spans received over OTLP are stored by later releases. - **Timing** is exact to the microsecond (`started_at`, `duration_us`). Local (pattern) guardrails run in one scan of the text and share its duration; provider and extension guardrails are timed one by one. A streamed answer's output guardrails span the relay. - **Cost** comes from the ledger the gateway already writes ([usage valuation](/docs/features/usage-valuation/) and [charge lines](/docs/features/usage-valuation/)): `cost_state` is `known`, `partial`, `unknown` or `none` (a step that costs nothing). Unknown is never zero. The attempts' known amounts add up to the request's known amount. - **Tokens** are what the provider reported; a missing count is unknown, never zero. - **Status:** a request span is `error` for a 5xx, a cut stream or a refusal the gateway made (a 4xx other than 499 with its own `error_code`, such as `model_forbidden`, `quota_exceeded` or `guardrail_blocked`; such a request is not kept by the `error` keep rule, which follows 5xx); an attempt for a failed send or an error status; a skipped target is `unset`. The exported OTLP server span keeps the HTTP convention (a 4xx leaves the status unset) and carries `error.type`; an answer cut after it started is an error there too, with `gateway.stream_cut` (`provider`, `client` or `gateway`); a provider cut has `error.type: stream_interrupted`, and the stored request span carries the cut's `error_code` (`stream_interrupted`, `stream_aborted` or `client_closed_stream`). A provider's own error answer relayed to the client has `error_code: upstream_http_error` on the stored request span (its body is never copied). - **Identity.** Every span carries the request's key, principal, team and, with `organizations` on, `organization_id`: the whole hierarchy, so a span joins up to its tenant without a lookup. The exported OTLP spans carry the same as `gateway.key.id`, `gateway.principal`, `gateway.team.id` and `gateway.organization.id`, and every log line of the request has `key_id`, `principal`, `team` and `organization_id` next to `request_id`, `trace_id` and `span_id`. - **Configuration** (flag `trace_explorer`). The request span carries `config_fingerprint`, `config_version`, `policy_revisions` and, for a translated request, `translation_lossy`: which configuration and which policies served the request, as hashes and names, never a value ([configuration at the time](/docs/features/trace-explorer/#configuration-at-the-time)). A replay's request span carries `replay_of`. - **Structural items** (flag `span_structural_items`, off by default). The request span can record the shape of the conversation without any of its text: one bounded `structure` attribute with the number of messages, their roles in order, the tools declared and the tool calls by name, attachment counts by type and the token split. The exported OTLP server span carries the same as `gateway.structure.*`. It is for teams that capture no content, and it is shown only to readers with `content_structure:read` of the span's team; the fields and bounds are in [content capture](/docs/features/content-capture/#structural-items-on-the-span-span_structural_items). - Each request span carries the request's key, principal, session, end user, customer and usage tags, so later filters need no join. [End-user erasure](/docs/features/metadata-retention/) removes the end user (or customer member) from their spans and summaries, and, when the job completes, from the analytics store copy, including spans the database has already dropped. ### Trace IDs and the caller's trace The trace ID is the W3C trace ID the gateway used and propagated; the span IDs are the ones exported over OTLP. `spans.caller_trace` decides what happens when a client sends `traceparent`: - `join` (default): the gateway continues the caller's trace. The request span's parent is the caller's span and `trace_source` is `caller`, so the client's own spans and the gateway's form one tree. - `link`: the gateway mints its own trace ID, keeps the caller's in `caller_trace_id` and `caller_parent_span_id` and adds a `caller` link on the request span. Choose it when clients you do not control could send other teams' trace IDs: a client can then never attach its requests to a trace it does not own. The response's `traceparent` header names the gateway's trace. The exported OTLP server span carries a span link to the caller's span, so an OpenTelemetry backend still joins the two traces without putting the gateway's spans inside the caller's; `request_id`/`correlation_id` stay the same in both. Either way every read filters by team first: a W3C trace that crosses teams shows each reader only their own team's spans and never counts the others. An organization administrator reads the teams of its organization only, so another organization's spans in a shared trace stay invisible. A `traceparent` that does not parse is ignored: the request starts a trace of its own, its request span has `traceparent: ignored_malformed` and a `traceparent_ignored` event, and its `request` log line has `traceparent: ignored_malformed`. ## Settings All settings sit in the `spans` block of the gateway YAML. The first ten are the **runtime policy**: `PUT /api/v1/admin/span-store/settings` or the console's **Span store** panel replaces them as a whole, and they apply from the next request on every replica after its configuration refresh. The last five are the writer's engine and capacity, read once at startup. ```yaml spans: sample_rate: 1.0 # 0-1 head sampling by trace (keyed hash of the trace id; every span of a trace kept or dropped together) keep_always: [error, fallback, guardrail_flagged, evaluated] # stored even when sampled out; [] keeps only the sample retention_days: 14 # 1-3650 daily partitions kept; never longer than an active metadata_retention max_spans_per_request: 64 # 1-1024; extra steps are counted on the request span (dropped_spans) max_spans_per_trace: 2000 # 1-100000; a batch for a trace at the bound is dropped and counted (dropped_trace_limit) max_attribute_bytes: 2048 # 256-16384 per span's attributes; longest values are dropped first caller_trace: join # join: continue the caller's W3C trace id; link: mint a gateway trace id and keep the caller's apart log_link_template: "" # https URL with {trace_id}, {span_id}, {request_id}, {caller_trace_id}: "Open in logs" in the trace drawer apm_link_template: "" # same placeholders: "Open in APM" retained_max_traces: 10000 # 0-1000000 annotated traces copied past retention into gateway_spans_retained # engine: database # database | analytics_store; unset derives it: analytics_store when the analytics_store block is configured, else database (see "Where spans are stored") queue_size: 8192 # 64-1048576 requests waiting; when full, a request's spans are dropped and counted, never awaited batch_size: 500 # 1-10000 spans per write (COPY plus one upsert of the touched trace summaries and one of the sessions); 5000 by default with engine analytics_store flush_interval: 1s # 100ms-1m between writes when the batch is not full max_connections: 2 # 1-16 database connections of the writer's own pool ``` | Setting | Default | Bounds | Applies | What it does | | --- | --- | --- | --- | --- | | `spans.sample_rate` | `1` | 0–1 | next request | Head sampling of traces by a keyed hash of the trace ID: every span of a trace is kept or dropped together, and every replica decides alike. `0` keeps only what `keep_always` keeps | | `spans.keep_always` | `[error, fallback, guardrail_flagged, evaluated]` | any of the four, each once | next request | Stores a request even when sampling dropped its trace: `error` (HTTP 5xx, a cut stream or a failed provider attempt), `fallback` (served after a move to another target, or by a semantic fallback), `guardrail_flagged` (a guardrail blocked or masked, or a monitor would have), `evaluated` (captured for live evaluation). `[]` keeps only the sample | | `spans.retention_days` | `14` | 1–3650 | next maintenance pass (hourly) | A span is kept at least this many days: a day's partition is dropped whole once the whole day is older than the retention. Never longer than an active [metadata retention](/docs/features/metadata-retention/): the shorter one applies | | `spans.max_spans_per_request` | `64` | 1–1024 | next request | Spans of one request, its request span included; further steps are counted in the request span's `dropped_spans` attribute | | `spans.max_spans_per_trace` | `2000` | 1–100000 | next write | Counted from the trace summary, in the same statement that updates it: once a trace holds this many spans, its later spans are dropped and counted as `dropped_trace_limit`. A trace below the bound takes one whole batch, so it can end up to one batch over it | | `spans.max_attribute_bytes` | `2048` | 256–16384 | next request | Encoded size of one span's attributes; the longest values are dropped first and `attributes_truncated` is set | | `spans.caller_trace` | `join` | `join`, `link` | next request | Continue the caller's trace, or keep the caller's IDs apart (see above) | | `spans.log_link_template` | `""` | empty or an https URL (http only for a loopback host), at most 1024 bytes | next read | **Open in logs** in the trace drawer. The only braces allowed are `{trace_id}`, `{span_id}`, `{request_id}` and `{caller_trace_id}`, each replaced URL-escaped with the root request's values. The gateway's stdout and OTLP log lines already carry `trace_id` and `span_id` | | `spans.apm_link_template` | `""` | same | next read | **Open in APM**, for example `https://apm.example.com/trace/{caller_trace_id}` | | `spans.retained_max_traces` | `10000` | 0–1000000 | next maintenance pass | Annotated traces kept past retention (see below); `0` keeps none | | `spans.engine` | derived: `analytics_store` when the `analytics_store` block is configured (and `analytics_store.spans_retention_days` is unset), else `database` | `database`, `analytics_store` | restart | Where the writer puts spans and every span read answers from: the database (PostgreSQL), or the [analytics store](/docs/features/analytics-store/) (ClickHouse). `analytics_store` requires the `analytics_store` block and refuses `analytics_store.spans_retention_days` (see [Where spans are stored](#where-spans-are-stored)) | | `spans.queue_size` | `8192` | 64–1048576 | restart | Requests waiting to be written. When the queue is full a request's spans are dropped and counted (`dropped_queue_full`); the request never waits | | `spans.batch_size` | `500`, or `5000` with `engine: analytics_store` | 1–10000 | restart | Spans per write. The analytics store wants few large inserts (about one per second per table), so its default is larger; a value you set wins | | `spans.flush_interval` | `1s` | 100ms–1m | restart | Pause before writing a batch that is not full | | `spans.max_connections` | `2` | 1–16 | restart | Connections of the writer's own database pool, apart from the request path's, so span writes never take a connection a request waits for. With `engine: analytics_store` the pool only reads the ledger of a request that did not carry its cost (rare) | | `analytics_store.spans_retention_days` | `90` | 1–3650 | restart | How long the analytics store keeps copied spans, as a table TTL (see below). Only for the copy (`engine: database`) | **API.** `GET /api/v1/admin/span-store/settings` (`config:read`) returns the policy in force (`spans`), the stored override or `null`, the YAML base with defaults (`yaml`), the source of each setting (`default`, `yaml` or `console`), the writer's settings with their sources and the retention applied. `PUT /api/v1/admin/span-store/settings` (`features:manage`, CSRF) takes `{"version": , "spans": {...every setting...}}`: a partial policy, an unknown or null member or a value out of bounds is refused naming the setting, and a stale version answers `409`. `DELETE /api/v1/admin/span-store/settings` with `{"version": }` removes the override and returns to the YAML. Both writes are audited (`span_store.set`, `span_store.revert`). ## Where spans are stored `spans.engine` chooses where the span writer puts spans and where every span read answers from. Choose it at deploy time; the measured comparison is in [Span store engines](/docs/benchmarks/span-store-engines/). When it is unset, the gateway derives it at startup and logs `span_engine_derived` once: the analytics store when the `analytics_store` block is configured, so span rows, about a quarter of the WAL and most of the disk leave PostgreSQL; otherwise the database. Setting `analytics_store.spans_retention_days` (the copy's own retention) keeps the database engine and its copy. An explicit `spans.engine` always wins. `GET /span-store` reports the source as `derived` (owner, 2026-11-23). - **`database` (default):** spans, summaries and the retained table live in PostgreSQL, as described on this page. This needs nothing besides the database. It suits most deployments up to a few hundred requests per second; above that the span rows become a large share of the database's writes. - **`analytics_store`:** the writer sends each batch straight to the [analytics store](/docs/features/analytics-store/) (ClickHouse), so the database writes no span rows at all. Use it when the analytics store already runs next to the gateway and span volume would weigh on the database. It requires the `analytics_store` block; the gateway refuses to start without it. What stays the same with `analytics_store`: - **The request path:** one non-blocking send to the same bounded queue. When the analytics store is down or slow, batches fail and are dropped and counted (`dropped_write_failed`, `last_error` such as `analytics_store_unreachable` or `analytics_store_timeout`), the writer pauses a second after each failure, the queue fills, and further spans are dropped and counted (`dropped_queue_full`). Once the store answers again the writer resumes on its own; spans dropped meanwhile are not written later. Requests never wait and never fail because of it. - **The API:** `GET /traces/{trace_id}`, the span read, `GET /requests/{id}/trace`, the journey's `stored_trace` and `span_state`, `/span-store` and the summary rebuild keep their contract; trace reads say `source: analytics_store`. Team and organization filters run inside every analytics store query, before any bound. When the analytics store cannot be read, the trace, span and request reads and the rebuild answer `503 analytics_store_unavailable`, never that the spans are gone; `/span-store` still answers with the writer's counters and `storage.unavailable: analytics_store_unavailable`, so the drops during an outage stay visible. - **What stays in PostgreSQL:** the request log, the ledger (costs, charge lines, receipts), keys and authorization. A span's cost still comes from the ledger the request wrote; only a request whose usage write failed has its ledger read back from the database. How the analytics store holds them: - **Tables:** spans go to `gateway_spans_v1` (the copy's table; the engine's rows have `copy_id` 0), one summary row per trace and batch to `gateway_trace_summaries_v1` (sorted by trace), folded on read with the same rules as the database's summaries, and annotated traces to `gateway_spans_retained_v2`. The gateway creates them; the shipped ClickHouse user's grants are enough. - **Retention:** a table TTL equal to the retention in force (`spans.retention_days`, never longer than an active metadata retention), moved by the hourly pass when it changes. ClickHouse removes expired rows during its background merges, so they can stay readable for a few hours past the cutoff. Annotated traces are copied to the retained table within a day of expiring, up to `spans.retained_max_traces`. - **Erasure:** a completed end-user erasure is applied within about 30 seconds with lightweight deletes: each labelled span is written again without the label and the labelled row is deleted; the summary rows likewise. - **`max_spans_per_trace`:** read from the summary rows before each batch. Two replicas writing the same trace at once can each let one batch through past the bound. Switching the engine moves no data. Spans written before the switch stay where they were until that engine's retention removes them. With `analytics_store`, a trace or request with no span in the analytics store is still read from the database (`source` says which); a trace with spans on both sides of the switch shows the analytics store's part only. Back on `database`, traces only the analytics store holds are read from it only with `analytics_store_spans` on, as copied traces. The span copy (`analytics_store_spans`) only runs with `engine: database`; with `analytics_store` the flag has nothing to copy. ## How spans are written On the request path the gateway only appends a small fixed struct per step to the request's recorder and, once it has answered and written the usage row, makes one non-blocking send of the recorder to the writer's queue. With `span_store` off nothing is collected and the request path does no added work: zero added allocations. With it on a request adds one allocation of about 1.1 KiB (the recorder, which holds two steps inline and the generation parameters; a request with more steps, a fallback for example, adds one more) and the enqueue. Measured numbers: see [Performance](/docs/performance/method/#span-store-request-path-cost). Everything else runs on one writer goroutine per replica: sampling and `keep_always`, span names and attributes, the ledger costs, then one transaction per batch: one upsert statement for every touched trace summary (which also applies `max_spans_per_trace`), a `COPY` of the spans, and one upsert statement for the touched session summaries. The ledger costs come from the valuation and charge lines the request itself just wrote, carried to the writer with its spans, so the writer reads nothing back; only when that usage write failed, or found the event already written, does the writer read the usage event, its valuation and its charge lines from the database (counted in `gateway_span_store_ledger_reads_total`). Either way the cost is the stored ledger's: unknown stays unknown, never zero. Each statement has a 5-second timeout. A failed write drops that batch, counts it (`dropped_write_failed`) and pauses the writer for a second, so a database outage fills the queue and drops beyond it instead of retrying without bound. At shutdown the writer writes what its queue still holds within a 3-second window ([shutdown](/docs/operate/shutdown/)); anything left is dropped. Spans live in `gateway_spans`, range-partitioned by UTC day of `started_at`. The writer and an hourly maintenance pass create today's partition and the next two days' ahead of time; replicas serialize on a database lock, so several replicas never race on the same partition. ## Retention Once a day's partition ends more than `spans.retention_days` ago, the maintenance pass drops it whole (so a span is kept at least that long): no row-by-row delete. Before it drops one, the spans of **annotated traces** (a person scored one of its requests, or put it in a review queue) are copied into `gateway_spans_retained`, up to `spans.retained_max_traces` traces; a trace read finds them there (`retained: true`). When the retained table is full the pass logs `span_retained_table_full` and drops the rest. Trace and session summaries last updated before the cutoff are deleted with their partition, unless their trace is retained. ## Trace and session summaries The writer keeps one summary row per team and trace (`gateway_trace_summaries`) and per team and session (`gateway_session_summaries`), in the same transaction as the spans: - **Trace:** first and last instant, the root request (span, request ID, name, origin), counts of spans, requests, LLM calls, tool calls, errors, cache hits, guardrail flags and dropped spans, `fell_back`, the cost (state and known amount, combined: known plus unknown is `partial`), input and output tokens, up to 16 models, session and end user. - **Session:** first and last instant, traces, requests, cost, tokens, end user, parent session, first trace and up to 16 agents. Summaries are derived data. `POST /api/v1/admin/traces/summaries/rebuild` (`analytics:rebuild`, global administrators) takes the query parameters `from` and `to`, the first and last UTC day as `YYYY-MM-DD` (at most 31 days apart; default the last 7 days), and recomputes the summaries of every trace with a span in those UTC days, and of every session they touch, from the stored spans. ## Read traces | Route | Permission | What it returns | | --- | --- | --- | | `GET /api/v1/admin/traces/{trace_id}` | `logs:read` | The trace's spans in your teams, oldest first (at most 2000, `truncated` when more exist), the summary when every returned span belongs to one team, `retained`, `valuation_shown`, `links` (the filled link templates) and `source` (`database`, or `analytics_store`, below) | | `GET /api/v1/admin/traces/{trace_id}/spans/{span_id}` | `logs:read` | One span and its `capture_state`: `not_captured`, `audit_only` or `evaluation`, with `capture_id` on the span. It says whether [content capture](/docs/features/content-capture/#one-policy-for-audit-and-evaluation-content_capture_evaluation) kept the request's content and whether judges may read it (needs `content_capture_evaluation`; `not_captured` otherwise). The request span carries the same two values as attributes, on both span engines, and the drawer shows them as *Content*. With `span_structural_items` the span's `structure` attribute is returned to readers with `content_structure:read` of its team and left out for anyone else. The `tool` and `call_id` attributes of a `client_tool` or `transcript_tool` span follow the same rule, here and in the trace read above | | `GET /api/v1/admin/requests/{id}/trace` | `logs:read` | The stored trace ID and request span of a request ID (the latest one of a reused ID), and `source` | | `GET /api/v1/admin/span-store` | `config:read` | This replica's writer counters, the partitions with row estimates, retained traces, the write lag (`write_lag_seconds`: this replica's latest batch, from the end of its oldest request to the commit), the retention applied, the policy in force, the writer settings and, with `analytics_store_spans`, the copy state | | `POST /api/v1/admin/traces/summaries/rebuild` | `analytics:rebuild` | Rebuilds summaries (above) | Team roles read only their live memberships' spans, filtered in SQL before the 2000 bound; a missing and an out-of-scope trace or request ID answer the same `404`. ### When a request has no spans The request log row is the durable anchor: it is never sampled and outlives the span retention, so a read that finds no spans tells you why, in the `404`'s `error.code`, the journey's `span_state` and its gaps: | `error.code` | Journey `span_state` | Meaning | | --- | --- | --- | | `spans_expired` | `expired` | Older than `spans.retention_days`: the partition was dropped. The request log row, ledger and receipts remain | | `spans_sampled_out` | `sampled_out` | Dropped by `spans.sample_rate`, judged with the rate in force now. A request the request log shows a keep rule kept (a 5xx or more than one attempt for `error`, more than one attempt for `fallback`, a blocking guardrail for `guardrail_flagged`) is never called sampled out; a guardrail monitor flag or a live evaluation capture is not on the request log row, so such a request whose spans were dropped reads as sampled out | | `trace_not_found` | `not_stored` | Served before the span store was on, its spans dropped (counted in `gateway_span_store_spans_total`), or not visible to you | With `analytics_store_spans` on, a trace the database's retention already dropped is read from the analytics store copy, which keeps spans for `analytics_store.spans_retention_days`: the answer has `source: analytics_store` and no summary, and the drawer marks it. The copy is read with the same team filter, in its query. When the copy cannot be read, `GET /traces/{trace_id}` and `GET /requests/{id}/trace` answer `503 analytics_store_unavailable` rather than saying the spans are gone (an analytics store user without `ALTER ADD COLUMN` on an older span table makes every such read fail this way). With `engine: database`, `GET /traces/{trace_id}/spans/{span_id}` reads the database only; with `engine: analytics_store` every read answers from the analytics store. Fields follow the request log's flags: tags with `usage_tags`, session with `session_tracking`, end user with `end_user_tracking`, and cost with `usage_valuation` plus `analytics:read`. Every answer is `Cache-Control: private, no-store`. A fallback request, read by a reader who may see cost: ```json { "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "summary": {"spans": 4, "requests": 1, "llm_calls": 2, "errors": 1, "fell_back": true, "cost_state": "partial", "cost_usd": "0.00002", "root_request_id": "req-1", "models": ["chat-flaky"], "origin": "app"}, "spans": [ {"span_id": "b7ad6b7169203331", "parent_span_id": "00f067aa0ba902b7", "trace_source": "caller", "kind": "request", "subkind": "chat", "name": "POST /v1/chat/completions", "origin": "app", "request_id": "req-1", "duration_us": 912410, "status": "ok", "http_status": 200, "model": "chat-flaky", "cost_state": "partial", "cost_usd": "0.00002", "attributes": {"attempts": 2, "fell_back": true, "route": "POST /v1/chat/completions", "status": 200}}, {"span_id": "0b7d1c9f3a5e2a10", "parent_span_id": "b7ad6b7169203331", "kind": "routing", "name": "route chat-flaky", "duration_us": 41, "status": "ok", "cost_state": "none", "attributes": {"candidates": 2, "chosen_target": "primary", "strategy": "ordered"}}, {"span_id": "5c1f7e0a9d3b4c21", "parent_span_id": "b7ad6b7169203331", "kind": "provider_attempt", "attempt": 1, "name": "provider.attempt primary model-a", "duration_us": 301877, "status": "error", "http_status": 500, "provider": "primary", "cost_state": "unknown", "attributes": {"attempt": 1, "final": false, "outcome": "provider_error", "sent": true}}, {"span_id": "9e4a2b6c8d0f1e32", "parent_span_id": "b7ad6b7169203331", "kind": "provider_attempt", "attempt": 2, "name": "provider.attempt backup model-b", "duration_us": 598210, "status": "ok", "http_status": 200, "provider": "backup", "input_tokens": 10, "output_tokens": 5, "cost_state": "known", "cost_usd": "0.00002", "attributes": {"attempt": 2, "final": true, "outcome": "answered", "sent": true}} ], "truncated": false, "retained": false, "valuation_shown": true, "links": {} } ``` ## In the console - **Request details** (from a request log row) shows **Open trace** only when the request's spans can be read, and otherwise says why (expired, sampled out, not stored); each request log row has a trace button while `span_store` is on. - The **request journey** shows **Open trace** when the request has stored spans, and then no longer lists the gaps spans cover (stage timing, per-attempt detail and timing, guardrails that passed, spans only in a tracing backend). Without them it offers no trace and its gap says why. The journey API returns `stored_trace` with the trace and span ID and its `source`, and `span_state`. - The **trace drawer** names the trace type (*Single request*, *Request chain* for requests sharing a caller's trace, *Agent run*, *Judge trace*, *Application trace*) with a legend of the span kinds present, then the summary (duration, spans, requests, LLM calls, errors, fallback, cache hits, guardrail flags, cost with *partial* when a step is unpriced, tokens), then a tree of spans: kind, name, a duration bar placed on the trace's time line, status and cost. Selecting a span shows its timing, status, model and provider, tokens, cost, attributes and events. With [evaluation results](/docs/features/evaluation-results/) on, a span that was judged shows an eval count in the tree and lists its results in its panel. **Open in logs** and **Open in APM** appear when their templates are set. On a phone (below 768 px) the span panel stacks under the tree. - With `trace_explorer` on, the **Traces** screen lists traces and spans over one query bar, and a trace opens everywhere in the fuller trace detail (tree, time-ruled waterfall, agent graph, and the span tabs Span, Evaluations, Feedback, Logs and Annotations) instead of this drawer: see [Trace explorer](/docs/features/trace-explorer/). - The **Span store** panel on the **Logs** page (`config:read`) shows the writer's counters and the partitions, the retention kept and where it comes from, and edits the runtime policy (`features:manage`); every setting shows its source (`default`, `YAML` or `console`), and the writer's settings are shown read-only, each with its source, and a restart note. ## Metrics With [`metrics_endpoint`](/docs/features/observability/#metrics-prometheus), `/metrics` (and the [OTLP metrics](/docs/features/observability/#otlp-metrics) push) carries the writer's series, per replica: | Series | Type | Labels | Measured | | --- | --- | --- | --- | | `gateway_span_store_spans_total` | counter | `kind` (`request`, `routing`, `provider_attempt`, `cache`, `guardrail`, `tool`, and `judge` once [evaluation tracing](/docs/features/evaluation-tracing/) stored a judge span), `result` | Spans by what became of them: `written`, `sampled_out`, `dropped_queue_full`, `dropped_write_failed`, `dropped_trace_limit` | | `gateway_span_store_queued_requests_total` | counter | — | Requests whose spans entered the queue | | `gateway_span_store_queue_depth` | gauge | — | Requests waiting in the queue | | `gateway_span_store_batches_total` | counter | `result` (`ok`, `failed`) | Batch writes | | `gateway_span_store_ledger_reads_total` | counter | — | Requests whose costs the writer read back from the ledger because the request did not carry them (its usage write failed or was a repeat); near zero in normal operation | | `gateway_span_store_write_seconds` | histogram | — | One batch write: partitions, ledger costs, `COPY` and summaries | Alert on `rate(gateway_span_store_spans_total{result=~"dropped_.*"}[5m]) > 0`: spans are being lost (a full queue or a failing database), never requests. ## Analytics store copy With `analytics_store_spans` and the [`analytics_store`](/docs/features/analytics-store/) block, the spans are copied to the analytics store's `gateway_spans_v1` table by the same copy as the usage events: a cursor over a copy sequence, gap ranges for identifiers committed out of order, and a change log for updates while the copy is on; a completed end-user erasure is applied to the copy directly, so it also reaches spans past the database's retention. The table is ordered by team, start time, trace and span, and keeps spans for `analytics_store.spans_retention_days` (default 90) as a table TTL, longer than the database's `spans.retention_days` if you choose. A dropped database partition is not a change: the copy keeps its spans. Single-trace reads answer from PostgreSQL, and from the copy only once the database no longer holds the trace (see [When a request has no spans](#when-a-request-has-no-spans)). The copy state is in `GET /api/v1/admin/span-store` (`analytics_copy`). The copied table carries the organization, the caller's parent span, the events and the links too. ## Upgrade and downgrade - Migration 197 adds `gateway_spans` (partitioned, no partition yet), `gateway_spans_retained`, the two summary tables, the settings override and the span copy state. Migration 198 adds the `organization_id` column to the request log rows and the spans; older rows keep none. Nothing is backfilled. An existing analytics store span table gets its new columns (`organization_id`, `caller_parent_span_id`, `events`, `links`) when the copy starts, which needs `ALTER ADD COLUMN` on the database ([analytics store](/docs/features/analytics-store/)). - Rolling upgrade: replicas of the older release ignore the new tables. Turn the flag on once every replica runs this release. - Downgrade: turn `span_store` off first. The older binary refuses a database migrated by a newer release; restore the backup taken before the upgrade, as for any release. ## See also - [Trace explorer](/docs/features/trace-explorer/): the Traces screen, the query, facets and the trace detail. - [Agent runs](/docs/features/agent-recognition/): coding-agent runs recognized from the requests, whose steps are these spans; a recognized request span carries a `run` attribute block. - [Observability](/docs/features/observability/): logs, OTLP traces, request journey and metrics. - [Evaluation results](/docs/features/evaluation-results/): results attached to spans, as span events and over OTLP. - [Judge calls as linked, labelled traffic](/docs/features/evaluation-tracing/): judge runs as their own traces with a `judge` span, linked both ways to the judged span. - [Usage valuation](/docs/features/usage-valuation/): where span costs come from. - [Analytics store](/docs/features/analytics-store/) and [metadata retention](/docs/features/metadata-retention/). ## Application spans With `otlp_ingest` an application sends its own OpenTelemetry spans to `POST /v1/traces`, and they join the gateway's spans of the same trace as spans of kind `app`: the gateway's request appears under the application's model call. See [application spans over OTLP](/docs/features/otlp-ingest/). Keys read traces with the [public trace API](/docs/features/public-trace-api/). # Trace explorer **Last updated:** 2026-11-26T08:30:56-03:00 (UTC-3) The **Traces** screen answers two questions about the traffic the gateway serves: *which* requests behaved a certain way, and *what happened inside* one of them. It lists the traces and spans the [span store](/docs/features/traces/) keeps, over one query bar, and opens any of them as a tree, a time-ruled waterfall and an agent graph, with the evaluation results, the feedback, the gateway's own records and the captured content of each step next to it. Two more scopes, **Sessions** and **Users**, group the same traces by conversation and by end user: see [sessions and end users](/docs/features/sessions-and-users/). It reads what the gateway already stores. It adds no table, no exporter and no ID of its own: a trace here is the same `trace_id` your tracing backend receives over OTLP, a request is the same `request_id` the request log shows, and a result is the same [evaluation result](/docs/features/evaluation-results/). ## Turn it on ```yaml features: usage_analytics: true span_store: true trace_explorer: true ``` | Flag | Default | What it turns on | | --- | --- | --- | | `request_replay` | `false` | [Replay](#replay-a-request): an operator sends a captured request again as a new request of their own. Requires `content_capture`, `span_store` and `evaluation_tracing`. A tenant action: with `feature_plan_entitlements` the plan of the request's team decides. It resends captured content and it spends, so it is a flag of its own: a team can have the explorer without it. Changeable at runtime from **Settings → Features** or `PUT /api/v1/admin/features/request_replay` | | `trace_explorer` | `false` | The Traces screen, the trace detail with its three views and five tabs, and the routes below. Requires `span_store`. A tenant read: with `feature_plan_entitlements` a team's plan decides whether its readers have it. Changeable at runtime from **Settings → Features** or `PUT /api/v1/admin/features/trace_explorer` | Do it in this order: 1. Turn on `span_store` first and let it collect for a while (see [Traces and the span store](/docs/features/traces/)); the explorer lists nothing that was served before spans were stored. 2. Turn on `trace_explorer`. The **Traces** entry appears under **Observability** for every role with `logs:read`. 3. Optional, each with its own flag: [`evaluation_results`](/docs/features/evaluation-results/) for the evaluation badge, lenses and facets; [`evaluation_tracing`](/docs/features/evaluation-tracing/) for judge traces linked both ways; [`content_capture`](/docs/features/content-capture/) for input and output in the detail, and `content_capture_media` for images and audio. With the flag off the routes answer `404 feature_disabled`, the menu entry is hidden, and a trace still opens in the earlier, simpler trace drawer of the span store. With `request_replay` off the **Replay** action is hidden and its route answers `404 feature_disabled`. ### Who reads what | Reader | What they see | | --- | --- | | A gateway-wide role with `logs:read` (administrator, viewer, operator) | Every team's traces and spans | | A team role (team administrator, team viewer, user) | Only the traces and spans of their teams. An organization admin is a team administrator of every team of the organization, and never leaves it | | Any reader | Cost only with `usage_valuation` and `analytics:read`; sessions with `session_tracking`; end users with `end_user_tracking`; tags with `usage_tags`; evaluation results with `evaluation_results` and `evals:read` | The team filter runs in the query, before any count, facet or page. A trace that crosses teams (a caller's W3C trace used by two teams) is one row per team, each with only that team's spans and figures. Naming another team's trace, request or team in the query finds nothing, and its records answer `404` like a trace that does not exist. A field a reader may not see on a row cannot be used as a filter either, so a filter never answers what a column would not. ## The list The screen has a **scope** switch, a **lens** strip, a time range, the query bar, a facet rail and the list. - **Traces** (the default) lists one row per trace: time, the root span's name, status, duration, cost (marked **partial** when some provider attempt has no known price), tokens, models, span and call counts, session, and a badge of its evaluation results. **Spans** lists every span, so a provider attempt, a guardrail or a tool call can be found on its own. Switching keeps the query. - **Lenses** change what the list is about. **Overview** is the list above. **Evaluations** puts a card per evaluator over the list (pass rate, a pass and fail bar, counts) and one column per evaluator. **Feedback** does the same for end-user feedback and human labels. - **Time range**: the past 15 minutes to 30 days, or a custom range of at most 92 days. Time is never part of the query. The list can refresh itself every 10, 30 or 60 seconds. - **Pages**: the list loads 50 rows and **Load more** fetches the next page with a cursor, so a row is never repeated or skipped while new traffic arrives. The total above the list is exact and comes from the facets read. - **Chart** shows the count over time for the current query, errors in their own colour. - **Internal calls** is off by default: the gateway's own calls, its LLM judges (`origin:evaluation`) and its helper calls (topic and comparison summaries, prompt suggestions; `origin:helper`), stay out of the list, the facets, the chart and the exports, so the list shows what the applications did. Tick it to list them too (the address keeps `internal=1`). A query that names `origin` (for example `origin:evaluation` to see only the judges) decides on its own and the box is disabled. The setting is a separate filter, `internal=false` on `GET /api/v1/admin/traces`, `/traces/facets` and `/traces/chart`, ANDed with your query: the query is parsed, bounded and saved exactly as you wrote it, never rewritten. A saved view keeps the box. **Create alert rule** and **Automate this query** take your query as written; add `-origin:evaluation -origin:helper` there when the rule should leave the gateway's calls out. An empty list says when internal calls are hidden. - **Content** (offered to readers with `content_sent:read`) shows the first input and the answer of each listed request. It is off by default: every preview is an audited read of a captured record, so the page is limited to 50 rows and auto-refresh is suspended while it is on. - **Columns** chooses the columns, listed by group (core, cost and tokens, gateway facts, identity, evaluations), and **Compact** the row height; both are remembered in the browser. *Gateway facts* shows on each trace whether it fell back, hit a cache or had a guardrail flag. - Selecting rows opens a bar with **Add to dataset** (from the requests' captured content), **Add to review queue** (both need `evals:manage`) and **Export**. **Export CSV**, **Export JSON** and **Export JSONL** (one object per line) export the selection or, with none, every row of the query: the pages not yet listed are read first, up to 5,000 rows, and a notice says when the query has more. - A row opens the trace detail as a drawer; `j` and `k` move through the list. On a session's page, `j` and `k` open the next and previous session of the list. Below 720 px the facets move behind **Filters (n)**, a sheet that closes on **Apply**, and rows become cards with time, status, name, model, duration, cost and the evaluation badge. ### The query Terms are joined by AND; the word `AND` is optional. That is the whole query while `trace_query` is off. With [`trace_query`](/docs/features/query-language/) on, the bar reads the gateway's whole query language: `OR`, `NOT`, parentheses, value lists, ranges, the gateway's own facts on any span of a trace (`canary.side:canary`, `customer.org:acme`, `child.span.kind:tool child.span.status:error`), text search over captured content for content readers, a facet of any field, and saved views. [Query language and saved views](/docs/features/query-language/) is its reference; the table below is the part that works either way. | Form | Meaning | | --- | --- | | `field:value` | Equal. Quote a value with spaces: `name:"POST /v1/chat/completions"` | | `field:prefix*` | Starts with (text fields; a trailing `*` only) | | `field:*` | Has a value | | `-field:value` | Not | | `field>n`, `field>=n`, `field` | spans | A request tag; needs `usage_tags` | | `evaluation..assessment` | both | `pass`, `fail`, `none`: the traces with such a result of that evaluator or label. `evaluation.any.assessment` reads every name | | `evaluation..value`, `feedback..value` | both | The numeric value of a result, compared with a number | | `evaluation.:*`, `feedback.:*` | both | The traces that evaluator judged, or that carry that feedback label | | `trace.failed_evaluations` | both | The number of failed results in the trace, compared with a count | Examples: `status:error`; `fell_back:true -cache:hit`; `model:chat* duration>2s`; `trace.errors>=1 origin:app`; `evaluation.helpfulness.assessment:fail -evaluation.groundedness.assessment:fail`; `feedback.thumbs.value<1 session:*`. Evaluation and feedback terms are answered from the evaluation results first and then applied to the spans, because results live with their team's telemetry. A term reads the results on a span or a trace written from the start of the time range to a day after its end (a judge finishes after the request it judged) and matches at most the 2,000 most recently judged traces; when it matched more, the answer has `evaluation_filter_truncated: true` and the screen says to shorten the range. ### Figures and chart Above the list, the **figures** of the query's rows: the median and 95th-percentile duration, the rows in error, the tokens in and out and, for a reader who sees cost, the cost. They follow the query, the scope and the time range, like the count. **Chart** draws the query over time. Three choices beside it, remembered in your browser: | Choice | Values | | --- | --- | | Metric | **Count**, **Errors**, **Mean duration**, **Tokens** (input plus output), **Cost** (only for a reader who sees cost) | | Breakdown | **No breakdown**, **Status**, **Origin**, **Team**, **Model** | | Form | **Over time** (one stacked bar per interval; a mean shows the largest group of each interval) or **Top list** (one bar per group with its total) | The five largest groups have a color each and the rest are **other**; a group's name is a button that adds it to the query (`model:chat-default`), so a spike is one click away from its traces. The plain count over time needs no extra read: it is the strip the facets read already carries. A row whose request has **comments** shows their count beside its name (for readers of evaluations); the comments themselves are on the detail's Annotations tab. ### Facets The rail counts the rows of the current query by status, origin, model, team, fallback, cache and guardrail flag (and, for spans, by kind and provider); a click adds or removes the term. For traces it also offers **Span errors in trace** (1, 2 or 5 or more) and **Failed evaluations in trace**. With evaluation results it lists **one facet per evaluator and per feedback label**, with its pass and fail counts; a click filters to the traces with that verdict. Evaluator counts are the results written in the time range in your teams; the other terms of the query do not narrow them. Each facet lists its 50 most frequent values. ## The detail A row opens the trace as a drawer; **Full page** opens it at `#/traces/?span=&view=&tab=`. The address follows the selection, so **Copy link** gives a link to exactly this span, view and tab. The header shows the root span's name, the kind of trace (single request, request chain, agent run, judge trace, application trace), chips for the session and the end user (a click lists their traces), the origin and the models, then the counters: evaluations **failed · passed · neutral · pending**, errors, duration, cost, tokens, spans, model calls and tool calls. A cost with an unpriced attempt is marked **partial cost**, and its tooltip names the attempt. With `evals:manage`, **Add to dataset** and **Review** send the trace's request to a dataset (from its captured content) or to a review queue. **Open in logs** and **Open in APM** appear when `spans.log_link_template` and `spans.apm_link_template` are set (see [Traces and the span store](/docs/features/traces/#settings)). Opened from a list, the arrows go to the previous and next row. With `evaluators`, the Evaluations tab also lists the evaluator runs the trace still waits for as **Pending · up to N min**: a [trace evaluator](/docs/features/evaluators/#scopes-and-when-a-run-happens) judges a trace once it stayed idle for its window (`pending_evaluations` on `GET /api/v1/admin/traces/{trace_id}`). The chips also name the **review queues** the trace's requests are in (for readers of evaluations; a click opens Evaluations) and, with `request_replay`, the **replays**: *Replayed: * on the original, *Replay of * on the replay, each a link to the other trace. Three views of the same spans: - **Tree**: one row per span under its parent, with its kind, name, a bar on the trace's time line and a metric (duration, tokens or cost). An error marks its span **Error** and every ancestor with **!**, so a failure deep in an agent run is visible from the root. A judged span carries a badge of its results. Rows collapse and expand (**Expand all**, **Collapse all**, or the left and right arrows). - **Waterfall**: a time ruler with round ticks that adapt from seconds down to microseconds and never run past the end of the trace; one bar per span by its start offset and width, coloured by kind, with its name, duration and metric on or beside it; parallel calls overlap in time on their own rows, so concurrency is visible. **Zoom** in and out (up to 64×) and **Fit**; the strip above the ruler is the whole trace, with the visible part outlined, and a click on it moves the view. **Show evaluation runs** adds a lane with a marker on each judged span. - **Graph**: the steps of an agent run (requests, tool calls, judge and application spans) as cards with their duration and cost, inside one box per agent; a box collapses and expands. A **solid** arrow is a link the gateway **observed** (a parent span or a span link); a **dashed** arrow is one the client only **asserted** through its agent, turn or parent-session headers (two consecutive calls of one agent, a child session). The agent a step belongs to is always asserted. A single request has no graph, and the view says so. In every view, **Find in trace** filters by name, kind, model, provider, span ID or request ID (keeping the ancestors of what matches), **Model calls only** and **Errors only** narrow the rows, **Guardrails** hides or shows guardrail spans (a guardrail's row carries its outcome), **Evaluation badges** and **Models** choose what a row shows, and the **error navigator** steps through the spans in error (also the `e` key). The up and down arrows (or `j` and `k`) move the selection and `a` opens the Annotations tab. The metric and these display options are remembered in the browser. Only the rows on screen are drawn, so a trace at the 2,000-span bound opens in well under a second. Below 900 px the selected span opens as a full-screen sheet with its tabs as a scrolling strip; below 720 px the graph asks for a larger screen, the tree stays complete and the waterfall pans sideways under a pinned ruler. ### The span's tabs | Tab | What it shows | | --- | --- | | **Span** | Status, timing, model and provider, tokens and cost; the agent the client declared, marked *asserted*; on a request span, with `evals:manage`, links to add its request to a dataset or a review queue; for a provider attempt its charge line; the attributes; the events (failure causes, retries, fallbacks, refusals), with an error block for a span in error; the links to judge or evaluated traces; and, on a request span, **Input and output** (below) | | **Evaluations (n)** | The results of evaluators (LLM judges, code, the API) on this span: the verdict, the value, the reasoning for readers of the sent view, the evaluator version, a pending, skipped or error state with its reason, **View judge trace**, and how the evaluator did over the past 7 days ("78% of 40 results passed") with **View evaluated traces**. On a judge run's own trace the header says what it judged, with **View evaluated trace** | | **Feedback (n)** | End-user feedback sent with `POST /v1/scores` and `source: feedback` | | **Logs (n)** | The gateway's own records, below, with a **Span \| Trace** switch | | **Annotations (n)** | Human results and the comments on the span's request. With `evals:manage` you can add a result (pass or fail, a score, a label or a text, with a rationale) on the selected span and a comment that may mention a console user | ### Logs: the gateway's own records The gateway does not store your application's log lines. It stores its own records of each request, which is what you look for when one misbehaves. The Logs tab lists them for the selected span or for the whole trace, each with its time, its kind and a link to the screen that holds it: | Kind | Record | Shown to | | --- | --- | --- | | `request_log` | The request log row; opens the request and its journey | Every reader of the trace | | `charge_line` | One provider send with its outcome and cost state (`attempt_charge_lines`) | Readers who see cost | | `delivery_receipt` | The durable usage receipt (`durable_usage`) | `analytics:read` | | `quota_reservation` | The quota reservation and its settlement | `quotas:read` | | `guardrail` | A guardrail's outcome and number of findings | Every reader | | `span_event` | A failure cause, a retry, a fallback, a refusal | Every reader | | `content_capture` | The captured record's metadata (never its content) | `content_structure:read` of the team | | `evaluation` | An evaluation result of the trace | `evals:read` | | `alert` | An alert whose detail names the trace or one of its requests (`alert_rules`) | `alert_rules:read` | | `audit` | An admin audit entry carrying one of the trace's request IDs | `audit:read`, gateway-wide roles | A span's records are those that name the span, plus, for a request span, the records of its request (and for a provider attempt, its request's charge lines). The switch shows both counts at once, and they differ: a trace has more records than any one of its spans. Each kind lists at most 200 records. **Open in logs** is your own log backend, through `spans.log_link_template`; the gateway's stdout and OTLP log lines carry the same `trace_id` and `span_id`. ### Input and output, images and audio A span never holds content. On a request span the detail shows what [content capture](/docs/features/content-capture/) kept for that request, and only what your role may read. Every read goes through the same two content routes as the rest of the console (`POST /api/v1/admin/content-captures/{id}/reveal` and `.../media/{media}`), which decide by the [content permissions](/docs/features/content-capture/#who-reads-what) of the record's team, are answered with `no-store` and are written to the audit log. Nothing is read until you press **Show input and output**. | You hold, for the request's team | You see | | --- | --- | | Nothing | A note that content is shown to readers with a content permission | | `content_structure:read` | That a record exists, with what it kept and until when; the content is not yours to read | | `content_sent:read` | The conversation as it was sent to the model (after the input guardrails) and the answer, as text. Images, audio and reasoning are replaced by a mark that says what was there | | plus `content_reasoning:read` | The model's reasoning, in its own collapsible block | | plus `content_media:read` | **Images and audio inline**: an image is drawn in the message that carried it and audio gets a player, each fetched from the media read route. An attachment over a capture bound shows why it has no bytes | | `content_received:read` (named users only) | **Raw JSON**: the request exactly as the client sent it, beside the sent view and the response | The conversation is drawn as a chat with tool calls as their own blocks; **Raw JSON** shows the exchanged bodies for readers who hold them. Media types the gateway serves inline are PNG, JPEG, GIF and WebP images and common audio types; anything else is offered as a file. Media needs `content_capture_media`; reasoning as its own part needs `content_capture_reasoning`. ## Configuration at the time A stored trace says which configuration served it. With `trace_explorer` on, every request span carries: | Attribute | What it is | | --- | --- | | `config_fingerprint` | 16 hexadecimal characters over the hash of every section of the configuration the request was served with. It is computed once when a configuration is loaded, never per request, so every replica shows the new fingerprint from the first request after a change | | `config_version` | The control version of that configuration (the number a configuration write advances) | | `policy_revisions` | The revisions of the policies the request read: its team's policy (`team_policies[]`), its model (`models[]`) and its provider (`providers[]`). With `team_policy_enforcement` the team's revision is taken from the policy in force when the request was admitted, so a policy changed from the console or the API (stored outside the configuration file) shows as changed too | | `translation_lossy` | What a translation between APIs approximated or left out for this request (for example `cache_control,service_tier`), the same list as the `X-Gateway-Translation-Lossy` response header | The gateway keeps, by fingerprint, one hash per section (`models[chat-default]`, `team_policies[platform]`, `features.usage_valuation`, `guardrails[pii-in]`…): hashes only, never a value of the configuration. On the **Span** tab of a request span, **Configuration at the time** shows the fingerprint and version then, whether the same configuration is in force now, and for each policy the request read whether it is **unchanged**, **changed since**, **added since** or **removed since**. A gateway-wide reader of the configuration (`config:read`) also sees **Sections that differ**: the names of every section changed, added or removed between then and now. A team role sees the state of its own request's policies, not the other sections. Two requests on either side of a configuration change show different fingerprints, and the later one's comparison with the earlier names the changed sections; that is how you tell "the model was repointed" from "the provider was slow". ## Replay a request With `request_replay` on, an operator can send a stored request again. **Replay** is on the trace detail's header and on a request's details in the request log, for a session that holds `requests:replay` and `content_sent:read` of the request's team. 1. **Replay** asks for confirmation and says what it does: the captured content is sent again, as you, on your limits, and it spends. 2. The gateway reads the record's **sent view** (the request after the input guardrails, as the [capture policy](/docs/features/content-capture/) kept it), clears `stream`, and sends it as a **new request** to the same API. 3. The answer shows the new request ID, its HTTP status and the answer's text, with **Open the replay's trace**. | What | How a replay behaves | | --- | --- | | Identity | The operator's own: key ID `replay::`, the console user as principal and key owner, in the request's team. Never the original caller's key, IDs or budget | | Limits and policy | Everything a request of that team goes through: team policy, plan, rate limits, quotas, budgets, guardrails, capture, the ledger and cost | | How it is recorded | Origin **replay** on the request log row and the span (`origin:replay` in the explorer and in Usage and Cost by origin), `parent_request_id` the original, `replay_of` on the replay's request span, and a link both ways on the two traces | | Audit | The read of the captured content (`content_capture.read`, `view:replay`) before anything is decrypted, and the replay itself (`request.replay`, with the original and the new request) | | What it covers | Chat Completions, Messages and Responses requests | A replay is refused with the reason, and nothing is sent, when: | Answer | Why | | --- | --- | | `409 content_not_captured` | No captured record of this request among the teams you read. The gateway never replays invented input | | `409 content_not_replayable` | The record keeps no sent view (the policy keeps the received view only), was cut at the policy's `max_bytes`, holds images or audio kept apart from the body, or is another kind of request. The message says which | | `409 replay_team_required` | Two teams you read have a request with this ID: name the team (`team_id`) | | `403 role_forbidden`, `content_read_forbidden`, `team_forbidden` | No `requests:replay`, no `content_sent:read` of the team, or a session that may not run calls as that team (a reader of a team's content through a `content:read` grant who is not a member of it, or a global role narrowed by a custom role: the button shows by permission, the server decides by team). The shared API token and scoped credentials never replay | | `404 feature_disabled` | `request_replay`, `content_capture` or `evaluation_tracing` is off, or the team's plan does not include replay | A replay that was sent and then refused by a guardrail, a limit or the provider is a replay like any other: `200` with the new request's own `status` and error. | Role | `requests:replay` | | --- | --- | | Administrator | Yes, any team | | Organization admin | Yes, inside its organization | | Team administrator | Yes, on administered teams | | Operator, viewer, team viewer, user | No | A [custom role ceiling](/docs/features/custom-roles/) can withhold `requests:replay` and never grants it beyond the base role. ## Links both ways | From | To | | --- | --- | | A request log row, the request details, the request journey | **Open trace**: the trace detail on that request's span | | A span | Its request log entry and journey (the request ID on the Span tab, or the `request_log` record) | | An evaluation result, anywhere it is shown | The span it judged, and **View judge trace** | | A judge trace | **View evaluated trace**, on the judged span; **View evaluator** | | A judge's own request in the request log | *Judge of* the request it judged | | A session or end-user chip, an evaluator's context line | The explorer, filtered to that session, end user or evaluator | | **Usage**: a row of a breakdown, its error count, or the whole selection | **View traces**: the explorer on the same slice (`model:`, `team:`, `origin:`, `end_user:`; a provider, key or principal moves it to request spans) and the same time window; the error count adds `status:error` | | A group of the explorer's chart | The explorer, filtered to that group | | A queue chip, a replay chip | Evaluations; the original or the replay's trace | ## API The explorer's routes need `trace_explorer`, `span_store`, `usage_analytics` and `logs:read`, are filtered by the reader's teams in the query (and, for each team, to what it recorded in its [current organization](/docs/features/evals/#targets-after-a-team-moves)), and answer `Cache-Control: private, no-store`. Replay has its own flag and permission. | Route | What it returns | | --- | --- | | `GET /api/v1/admin/traces` | The list. Parameters: `scope` (`traces`, the default, or `spans`), `q`, `from` and `to` (RFC 3339; default the past 24 hours, at most 92 days apart), `lens` (`overview`, `evaluations`, `feedback`), `limit` (1 to 200, default 50), `cursor` (the previous answer's `next_cursor`), `content=true` (previews, at most 50 rows) | | `GET /api/v1/admin/traces/facets` | The exact `total` and the facet counts of the same `scope`, `q`, `from` and `to`. `field` limits it to one facet (or `evaluation`); `histogram=true` adds the count over time in at most 60 buckets; `stats=true` adds `stats`: `rows`, `duration_p50_us`, `duration_p95_us`, `duration_avg_us`, `input_tokens`, `output_tokens`, `errors` and, for a reader who sees cost, `cost_usd` | | `GET /api/v1/admin/traces/chart` | One metric by one breakdown for the same `scope`, `q`, `from` and `to`: `metric` (`count`, `errors`, `duration`, `tokens`, `cost`), `by` (`none`, `status`, `origin`, `team`, `model`). `series` has at most the eight largest groups and `other`, each with its `total` and one point per interval of `step_seconds` | | `GET /api/v1/admin/traces/{trace_id}/configuration?span_id=` | [Configuration at the time](#configuration-at-the-time) of a request span against now | | `POST /api/v1/admin/requests/{id}/replay` | [Replay](#replay-a-request). Optional JSON body: `team_id` (when two teams you read have a request with this ID) and `capture_id` (the record, when one team used the ID more than once; the console sends the one the trace names). Needs `request_replay`, `requests:replay`, `content_sent:read` and the CSRF token | | `GET /api/v1/admin/traces/fields` | The fields you may use, with their type, values, scopes and a line of help; the syntax, examples and limits | | `GET /api/v1/admin/traces/{trace_id}/records` | The Logs tab: `scope=trace`, or `scope=span` with `span_id`; `records`, `counts` for both scopes, `truncated` and `log_link` | ```bash curl -s -b cookies.txt "https://gateway.example.com/api/v1/admin/traces?q=status:error%20model:chat*&from=2026-11-24T00:00:00Z&to=2026-11-25T00:00:00Z&limit=2" ``` ```json { "scope": "traces", "lens": "overview", "engine": "database", "from": "2026-11-24T00:00:00Z", "to": "2026-11-25T00:00:00Z", "query": "status:error model:chat*", "data": [ {"team_id": "platform", "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "first_at": "2026-11-24T15:02:11.482113Z", "last_at": "2026-11-24T15:02:12.394523Z", "duration_us": 912410, "root_span_id": "b7ad6b7169203331", "root_request_id": "req-1", "root_name": "POST /v1/chat/completions", "origin": "app", "spans": 4, "requests": 1, "llm_calls": 2, "tool_calls": 0, "errors": 1, "fell_back": true, "cache_hits": 0, "guardrail_flags": 0, "cost_state": "partial", "cost_usd": "0.00002", "input_tokens": 10, "output_tokens": 5, "models": ["chat-flaky"], "session_id": "sess-9", "evaluations": {"failed": 1, "passed": 1, "neutral": 0, "pending": 0, "errors": 0, "results": [{"id": "score_1", "name": "helpfulness", "source": "llm", "scope": "span", "span_id": "b7ad6b7169203331", "assessment": "fail", "status": "ok", "metric_type": "boolean", "value": 0}]}} ], "has_more": true, "next_cursor": "eyJ2IjoxLCJ0IjoiMjAyNi0xMS0yNFQxNTowMjoxMS40ODIxMTNaIiwiaWQiOiI0YmY5…", "valuation_shown": true, "evaluations_shown": true, "evaluation_filter_truncated": false, "content_shown": false } ``` A span row has the span's own columns (`span_id`, `kind`, `name`, `started_at`, `duration_us`, `status`, `model`, `provider`, tokens, cost) without its attributes and events, which are in the detail. With `lens=evaluations` or `lens=feedback` the answer has `cards`: per name, `pass`, `fail`, `none`, `total`, the `mean` of numeric values and up to 12 `labels`. A row's `evaluations.results` lists its first 24 results and `more` counts the rest; one page reads at most 1,000 results for its rows (the newest), and says `evaluations_truncated: true` when it reached that. With `content=true`, a row's `content` is `{"state": "shown", "input": "…", "output": "…"}` (240 characters each, text only), `withheld` when a record exists that you may not read, or `not_captured`; it is absent when you hold no content permission for the team. ```json { "scope": "traces", "total": 1840, "facets": { "status": [{"value": "ok", "count": 1786}, {"value": "error", "count": 54}], "model": [{"value": "chat-default", "count": 1502}, {"value": "chat-flaky", "count": 338}], "fell_back": [{"value": "false", "count": 1750}, {"value": "true", "count": 90}] }, "max": {"trace.errors": 3, "trace.spans": 41}, "evaluators": [{"name": "helpfulness", "source": "llm", "pass": 1310, "fail": 212, "none": 4, "total": 1526}] } ``` ```json { "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "scope": "span", "span_id": "b7ad6b7169203331", "counts": {"trace": 9, "span": 6}, "truncated": false, "records": [ {"time": "2026-11-24T15:02:11.482Z", "kind": "request_log", "title": "Request log: chat chat-flaky", "detail": "HTTP 200, 912 ms, backup", "request_id": "req-1", "status": "ok", "link": "request", "link_id": "req-1"}, {"time": "2026-11-24T15:02:11.482Z", "kind": "charge_line", "title": "Charge line: attempt 1, primary model-a", "detail": "provider_error, cost unknown, HTTP 500", "request_id": "req-1", "status": "error", "link": "request", "link_id": "req-1"}, {"time": "2026-11-24T15:02:11.784Z", "kind": "span_event", "title": "Span event: attempt_failed", "detail": "http_status: 500, outcome: provider_error", "request_id": "req-1", "span_id": "5c1f7e0a9d3b4c21", "status": "error"} ] } ``` ```bash curl -s -b cookies.txt "https://gateway.example.com/api/v1/admin/traces/chart?q=status:error&metric=count&by=model&from=2026-11-24T00:00:00Z&to=2026-11-25T00:00:00Z" ``` ```json { "scope": "traces", "metric": "count", "by": "model", "unit": "rows", "step_seconds": 1800, "series": [ {"key": "chat-flaky", "total": 41, "points": [{"at": "2026-11-24T15:00:00Z", "value": 38}, {"at": "2026-11-24T15:30:00Z", "value": 3}]}, {"key": "chat-default", "total": 13, "points": [{"at": "2026-11-24T09:30:00Z", "value": 13}]} ], "metrics": ["count", "errors", "duration", "tokens", "cost"], "groups": ["none", "status", "origin", "team", "model"] } ``` ```bash curl -s -b cookies.txt "https://gateway.example.com/api/v1/admin/traces/4bf92f3577b34da6a3ce929d0e0e4736/configuration?span_id=b7ad6b7169203331" ``` ```json { "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "span_id": "b7ad6b7169203331", "recorded": true, "fingerprint": "5779307cefd254ce", "version": 41, "current": {"fingerprint": "70b2aef6ad7de9dd", "version": 42}, "same": false, "policies": [{"section": "team_policies[platform]", "state": "unchanged"}, {"section": "models[chat-flaky]", "state": "changed"}, {"section": "providers[primary]", "state": "unchanged"}], "changes_shown": true, "known": true, "changed": ["models[chat-flaky]"], "added": [], "removed": [], "first_seen": "2026-11-20T11:03:27Z" } ``` ```bash curl -s -b cookies.txt -H "X-CSRF-Token: $CSRF" -X POST "https://gateway.example.com/api/v1/admin/requests/req-1/replay" ``` ```json { "replay_of": {"request_id": "req-1", "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "team_id": "platform"}, "request_id": "7cfb0e0110144f171bca45dfb030e95d", "trace_id": "062799751bf78956133ccf0bf47c0af5", "status": 200, "origin": "replay", "output": "Lisbon." } ``` Errors: `400 invalid_query` (the message names the problem and the fields), `400 invalid_range`, `400 invalid_request`, `404 feature_disabled`, `404 trace_not_found` or `span_not_found` for the records of a trace or span you cannot see, `503 query_timeout` when a read takes more than 10 seconds (shorten the range or add a filter), `503 analytics_store_unavailable` and `503 storage_unavailable`. The trace itself is still read with `GET /api/v1/admin/traces/{trace_id}` ([Traces and the span store](/docs/features/traces/#read-traces)); with the explorer it also answers `team_id`, the team of the spans when one team owns them all. The reveal route answers, to readers of the sent view with reasoning and media, the same exchange as a list of messages (`conversation`) and the answer's text (`answer`), beside the exchanged bodies. ## The two span engines The explorer reads whichever engine holds the spans (`spans.engine`, see [where spans are stored](/docs/features/traces/#where-spans-are-stored)), with the same answers: - With `engine: database`, the list reads the trace summaries and the span partitions of PostgreSQL. - With `engine: analytics_store`, it reads the analytics store. A trace's figures there are the sum of the rows each write added; the list picks its page from them and then reads the page's own rows by key, so a row and its detail always show the same numbers. Both were measured with the same data; the figures and how to choose are in [Trace explorer reads](/docs/performance/trace-explorer/). In short: lists of traces and opening a trace are fastest on PostgreSQL (1 to 5 ms a page at a million traces, because a page reads the newest hour first); the facet rail, the exact total and the count over time are fastest on the analytics store (25 to 100 ms whatever the range, against 0.4 to 1.6 s on PostgreSQL once a range holds a million rows). The database is enough while the ranges your readers open hold up to a few hundred thousand spans; use the analytics store engine when they hold millions and the facets matter. ## Limits - The lists read live spans. A trace kept past retention because it was annotated still opens by its ID or from its request, and is not listed. - After switching `spans.engine`, the lists show what was written to the engine in use; traces written before the switch still open by ID. - With `engine: analytics_store`, a trace is listed by the time of its first span, as on the database. To find it, the list reads the rows written from a day before the range to a day after it: a trace that has been receiving spans for more than a day before the range starts, or still receives them more than a day after it ends, is filtered on the part inside those bounds. - Evaluation and feedback terms match at most 2,000 traces each (above). Evaluator facets and lens cards count results in the time range plus the day after it, since a judge finishes after the request it judged. - A facet lists 50 values; the detail shows the first 2,000 spans of a trace; the Logs tab lists 200 records of each kind. - The chart draws the five largest groups of a breakdown and sums the rest; the route answers eight and marks the series that sums the others (`folded`). A trace that used several models counts once under each of them in the model breakdown, as in the model facet. The percentiles are discrete and the same on both span engines. - A span stored before `trace_explorer` was on has no fingerprint, and a fingerprint from before the gateway kept section lists compares as changed without naming sections. - Replay covers Chat Completions, Messages and Responses requests whose sent view was captured whole and holds no image or audio; a replay is answered in one piece even when the original streamed. - `OR`, `NOT`, parentheses, lists, ranges, span fields on a trace, text search over captured content and saved views need [`trace_query`](/docs/features/query-language/). Sessions and users as scopes are not part of this screen yet. ## Upgrade Migration 210 adds two small tables, `gateway_request_replays` (one row per replay: the two request IDs, the two trace IDs, the team, the operator and the status) and `gateway_config_fingerprints` (one row per configuration the gateway ran with: a hash per section), and lets a stored span carry the origin `replay`, on the live table and on the copy kept past retention. It reads no existing row and takes no long lock. With `trace_explorer` on, a request span gains the attributes above: three map lookups per request, plus, with `team_policy_enforcement`, a 64-bit hash of the team policy's models and scopes; the fingerprint itself is computed when a configuration is published, never per request, and the gateway keeps the prints of the four newest configurations in memory. Turning the flags off hides the screen, the routes and the Replay action; nothing is deleted. ## See also - [Agent runs](/docs/features/agent-recognition/): the runs of coding agents, recognized from the requests alone, as a list and a thread - [Traces and the span store](/docs/features/traces/): what a span holds, the settings, retention and the two engines. - [Evaluation results](/docs/features/evaluation-results/) and [judge calls as linked, labelled traffic](/docs/features/evaluation-tracing/). - [Content capture](/docs/features/content-capture/): the capture policy, the content permissions and the media store. - [Access control](/docs/features/access-control/): which built-in role holds which permission. # Sessions and end users **Last updated:** 2026-11-26T09:05:04-03:00 (UTC-3) Two more scopes of the **Traces** screen group the traffic the way people think about a product: by **conversation** and by **customer**. **Sessions** lists the traces that share a session ID and opens one as a conversation, turn by turn, with its own evaluation results and the results of its traces. **Users** lists the end users your application named and opens one with everything they did in a time range. Both read what the [span store](/docs/features/traces/) already keeps. A session is the same `session_id` the request log and the trace explorer show; an end user is the same `end_user`; a result is the same [evaluation result](/docs/features/evaluation-results/). Nothing here is a second store or a second ID. ## Turn it on ```yaml features: span_store: true # the gateway stores its own spans trace_explorer: true # the Traces screen session_tracking: true # X-Gateway-Session-Id is read and recorded end_user_tracking: true # X-Gateway-End-User is read and recorded session_explorer: true # Traces -> Sessions (this page) end_user_pages: true # Traces -> Users (this page) ``` | Flag | Default | Kind | Requires | What it turns on | |---|---|---|---|---| | `session_explorer` | `false` | tenant read | `trace_explorer`, `session_tracking` | The Sessions scope, the session page and `POST /v1/sessions/{id}/close` (the latter also needs `evaluators`) | | `end_user_pages` | `false` | tenant read | `trace_explorer`, `end_user_tracking` | The Users scope, the end user page and `end_user` on `GET /evaluations` | Both are tenant reads: with `feature_plan_entitlements` a team's plan must include them. Readers need `logs:read`, as for the trace explorer; cost columns need `analytics:read` with `usage_valuation`; results need `evals:read` with `evaluation_results`; the conversation needs `content_sent:read` of the team (below). The flags can be overridden at runtime under **Settings → Features** or `PUT /api/v1/admin/features/{flag}`. ## What your application sends A session is whatever your application calls one: a chat thread, a support ticket, an agent run. Send the same value on every request of it: ```http POST /v1/chat/completions Authorization: Bearer X-Gateway-Session-Id: support-4812 X-Gateway-End-User: customer-77 ``` | Header | Bounds | Meaning | |---|---|---| | `X-Gateway-Session-Id` | one value, 1–128 printable characters | The session. A session belongs to the key's team: two teams that use the same ID have two sessions. | | `X-Gateway-End-User` | one value, 1–128 printable characters | The end user, as your application names them. The gateway does not authenticate it: the console marks it **client-declared**. | | `X-Gateway-Parent-Session-Id` | as above; needs `agent_sessions` | The session this one was started from (a subagent's run): it appears as a **child session** of the parent. | | `X-Gateway-Agent-Id` | as above; needs `agent_sessions` | The agent that made the request: the session lists its agents. | Reusing a session ID later extends the same session: its duration then runs from its first trace to its last. Judge calls, experiments and other calls the gateway makes for itself never carry your session ID, so evaluation traffic never appears inside your sessions. ## Sessions **Traces → Sessions** lists the sessions **active** in the time range (their last trace ends after its start and their first trace begins before its end), the most recently active first. Each row shows the last activity, the session ID, its traces and requests, its duration, its cost (`≥` when some request could not be valued; *Unknown* when none could, never zero), its tokens, the end user, the agents, a badge of every result of the session and its traces, and one column per **session evaluator** found on the page (the mean of its values, or passed/total). **First input** shows each session's first user message for readers of the sent view. The footer counts every matching session and its traces. The query bar takes the [query language](/docs/features/query-language/) in the **sessions** scope: | Field | Type | Example | |---|---|---| | `session` | text | `session:support-*` | | `end_user` | text | `end_user:customer-77` | | `team` | text | `team:support` | | `agent` | text (any of the session's agents) | `agent:researcher` | | `parent_session` | text | `parent_session:run-42` | | `duration` | duration | `duration>5m` | | `cost` | money | `cost>0.05` | | `valuation` | known, partial, unknown, none | `valuation:partial` | | `tokens.total` | number | `tokens.total>10000` | | `session.traces` | number | `session.traces>=3` | | `session.requests` | number | `session.requests>10` | | `session.failed_evaluations` | count of failed results | `session.failed_evaluations>=1` | | `evaluation..assessment`, `evaluation..value`, `feedback..value` | as in the traces scope | `evaluation.helpfulness.value<3` | An evaluation term selects the sessions with such a result, on the session itself or on any of its traces. Text search and topic terms are not read in this scope: search the text in the traces scope, then open the session from a trace. ### The session page Opening a session shows: - **The header:** team, traces and requests, duration (first trace's start to last trace's end), cost, tokens, end user (a link to the end user page), agents, the session it was started from, and the failed and passed results of its traces. Previous and next (or the `k` and `j` keys) move along the list you came from. - **Actions:** *Open its traces* (the traces scope with `session:`), *Add to review queue* (the session as a queue item, with `review_multi_annotator`) and *Evaluate* (an on-demand run of a session evaluator, with `evaluators` and `evals:manage`). - **Session results:** every result on the session itself, from a session-scope evaluator, a human or `POST /v1/scores` with a `session_id`, with the judge's reasoning for readers of the sent view and a link to the judge's trace. A result sent through the API appears at once, whether or not a session evaluator exists. - **Child sessions:** the sessions started from this one, at most 200. - **Transcript:** one turn per trace, the oldest first, the 20 most recent turns with *Load earlier turns* for the rest. Each turn shows its time, duration, model, model and tool calls, cost, tokens, the badge of its results (failed in red) and a link to the trace. For a reader with `content_sent:read` of the team, it also shows the **user's last message** in the request as it was sent on (after the input guardrails) and the **answer**, each cut at 4,000 characters, text only; an answer that only calls tools shows its calls, one `tool call: name(arguments)` line each. Where the session may record results for the turn's team (the server checks it as it checks the write: `evaluation_results`, `evals:manage`, a team the session administers, the team's plan; the transcript says so with `can_annotate`), each turn has **thumbs up**, **thumbs down** and an optional **comment**: a reviewer's boolean result named `thumbs` on the turn's trace (source `human`, pass or fail), recorded through `POST /api/v1/admin/evaluations` with that route's team checks, audited (`eval.result_create`, then `eval.result_edit` when the other thumb or a comment changes it), and counted wherever results are (the Feedback lens, the badge, Quality). The server keeps one vote per reviewer and turn: a second vote, from any page or two clicks at once, updates the first and is audited as an edit. The page reads the reviewer's own votes back (`GET /api/v1/admin/evaluations?mine=true`) to show them; on a turn of a team it may not write for, it shows that vote read-only and offers no button. A vote recorded before this rule keeps its ID and is the one updated; a vote change keeps the comment the vote already had. The reviewer is the console identity that signed in (a named user, or a console credential), and a vote an administrator withdrew stays withdrawn when the reviewer votes again. A turn's badge names failed results first, then passed, then neutral or skipped ones (a result skipped because its content was not captured), never "0 passed". Each turn shown is one audited read of the captured record. A reader who may only see that records exist sees each turn as *withheld*; anyone else sees *N turns, content not shown*. Content appears only when the team's [capture policy](/docs/features/content-capture/) keeps the sent view (the `evaluation` purpose, or `views: [sent]`). ### Session evaluators and the idle window A session-scope [evaluator](/docs/features/evaluators/) judges a session once it has been idle for `evaluation.session_idle` (or the evaluator's own `session_idle_seconds`), and every later request of the session pushes the run back. Until then the session shows no result and the evaluator lists the run as pending. When your application knows the conversation is over, it can say so: ```http POST /v1/sessions/support-4812/close Authorization: Bearer ``` ```json {"session_id": "support-4812", "runs_due": 1} ``` The session's waiting session-scope runs of the key's team become due now; a later request of the same session pushes them back by the idle window as before. A session with no waiting run answers `runs_due: 0`. It needs `session_explorer` and `evaluators` (both in the team's plan) and returns `404 feature_disabled` otherwise. ## End users **Traces → Users** lists the end users of the time range, one row per team (an end user is named by a team's application), the most recently seen first: last and first seen, team, sessions (the sessions the end user owns, the session's first-written end user, active in the range; per team and organization, so a session of a team that moved counts once per part), traces begun in the range, traces in error, cost, tokens and the badge of their results. The figures equal the sum of the trace summaries of the range. The **users** scope of the query language takes `end_user`, `team`, `cost`, `valuation`, `tokens.total`, `user.traces`, `user.sessions`, `user.requests`, `user.errors`, `user.failed_evaluations` and the evaluation terms, matched against the end user's results. The end user page shows those totals over the range and three tabs: **Traces** (the traces scope with `end_user:`), **Sessions** (the sessions scope with the same term) and **Evaluations** (`GET /evaluations?end_user=`: the results of the end user's requests and the results recorded on the sessions the end user owns, the session's first-written end user as its row shows; an erasure clears the session's end user, so its results leave the tab with it). *Open in Traces* and *Open in Sessions* take the term to the full screen. ### Erasure An [end-user erasure](/docs/features/data-governance/) clears the end user from every stored span and summary and deletes their rows of the hourly rollup in the same transaction, so an erased end user disappears from the list, the page and its Evaluations tab as soon as the erasure completes, and their sessions show no end user: another end user who wrote to the same session does not take their place, so the session's results leave the Evaluations tab rather than move to someone else's. On the analytics store engine (`spans.engine: analytics_store`) the spans and summaries there are cleared by a pass that applies completed erasures every 30 seconds, so the pages follow within that pass. With the analytics store span engine the erasure reaches the store on the gateway's next maintenance pass. ## API All admin routes also answer under `/api/admin`; they take a console session and the reader's team scope; a team-scoped reader reads only what its teams recorded in their current organization, and naming another team returns nothing. | Route | Purpose | Main parameters | |---|---|---| | `GET /api/v1/admin/sessions` | The sessions list | `q` (sessions scope), `from`, `to` (default the last 24 hours, at most 92 days), `cursor` (the `next_cursor` of the previous page), `limit` (1–200, default 50), `content=true` (first input; caps the page at 50), `totals=true` (count every match) | | `GET /api/v1/admin/sessions/{id}/overview` | The session page | `team` (the team to read, when several of your teams hold the ID) | | `GET /api/v1/admin/sessions/{id}/transcript` | The turns | `team` (409 `team_required` when several teams hold it), `cursor` (earlier turns), `limit` (1–50, default 20), `content=false` (skip the content reads) | | `GET /api/v1/admin/end-users` | The end users list | `q` (users scope), `from`, `to` (default the last 24 hours, at most 92 days), `cursor` (the `next_cursor` of the previous page), `limit` (1–200, default 50), `totals=true` | | `GET /api/v1/admin/end-users/{end_user}` | The end user page | `team` (one team), `from`, `to` (the range the totals cover) | | `GET /api/v1/admin/evaluations?end_user=` | An end user's results | `end_user`, with the evaluations list's parameters | | `POST /v1/sessions/{id}/close` | End a session's idle wait | key with `scores:write` | Example: ```bash curl -s -b cookies.txt \ "https://gateway.example.com/api/v1/admin/sessions?totals=true&q=session.traces%3E%3D3%20session.failed_evaluations%3E%3D1" ``` ```json { "scope": "sessions", "data": [ { "team_id": "support", "session_id": "support-4812", "first_at": "2026-11-26T10:00:00Z", "last_at": "2026-11-26T10:03:18Z", "duration_us": 198000000, "traces": 4, "requests": 4, "cost_state": "known", "cost_usd": "0.000052", "tokens": 315, "end_user": "customer-77", "agents": [], "evaluations": {"failed": 1, "passed": 2, "neutral": 0, "pending": 0, "errors": 0, "results": []}, "scores": [{"name": "csat", "count": 1, "failed": 0, "mean": 4}] } ], "session_evaluators": ["csat"], "totals": {"rows": 1, "traces": 4, "cost_state": "known", "cost_usd": "0.000052", "tokens": 315}, "has_more": false, "engine": "database" } ``` The full schemas are in the [API reference](/docs/api/). ## Both span engines With `spans.engine: database` sessions are read from the session summaries the span writer keeps in PostgreSQL; with `spans.engine: analytics_store` they are grouped from the trace summary rows in the analytics store, and a page's sessions are then folded exactly from their own rows, so both engines show the same figures. End users: the database engine keeps an hourly rollup of the trace summaries by team, organization and end user, written in the same transaction as each batch of spans; a read takes the whole hours of its range from the rollup and the partial hours at its two ends from the trace summaries, so its figures are exact, and a 30-day first page answers in about 76 ms at a million traces instead of 2 s ([measured](/docs/performance/sessions-and-users/)). The analytics store sums its trace rows on read, fast enough at that size. Session lists bound the time range by activity; end user lists by the traces' start. ## Limits - A list page holds at most 200 rows; results counted per page at most 1,000 (`evaluations_truncated`); an evaluation term matches at most 2,000 sessions or end users (`evaluation_filter_truncated`). - A transcript page holds at most 50 turns and reads one captured record per turn; each side of a turn is cut at 4,000 characters; images, audio and reasoning are never part of a transcript (open the trace for them). - A session lists at most 16 agents and 200 child sessions. - An end user is one team's: the same name in two teams is two rows. - Session summaries follow the span store's retention (`spans.retention_days`): a session older than that is no longer listed. ## Upgrading Migration 280 recorded the organization of every session summary; migration 281 moves the summaries to a table keyed by team, organization and session, filled from the old one, with the same indexes. From this release on a team that moves keeps each organization's part of a session apart on both span engines: readers of the former organization keep its part, readers of the new organization see only theirs, and a gateway-wide administrator sees one row per part (the session page and the transcript ask which with `organization`). Migration 282 adds the end user rollup (`gateway_end_user_hours`) and fills it from the trace summaries. Migrations 281 and 282 hold their tables while they copy them, so span writes wait during the migration (seconds per million traces) instead of being missed. **Rolling upgrade.** Upgrade replicas one at a time as usual; nothing has to be switched by hand. While replicas of the previous release still run, they write the old table; a trigger the migration installs copies each of their changes into the new table (the difference for the organization the row names, a whole row the previous release restarted for a moved team to the new organization), so the new table stays exact whichever replica wrote a batch, and an erasure those replicas run clears the label in both tables. The end user rollup follows every change to the trace summaries that this release's span writer does not make itself (retention, the summary rebuild, an erasure, a replica of the previous release) through a row trigger, so it is exact too. Two things to avoid until every replica runs this release: a summary rebuild on a replica of the previous release (its session rows would be copied a second time), and reading sessions from those replicas, which read the old table. Once the upgrade ends nothing writes the old table; it follows the span retention and a later release drops it with the trigger. # Agent usage **Last updated:** 2026-11-26T04:25:35-03:00 (UTC-3) The **Agent usage** page shows the agents that call models through the gateway: how much each is used, how fast it answers, what it costs and how often it fails, and how its versions differ. It reads the request spans the [span store](/docs/features/traces/) already keeps; there is no agent SDK to install. ## Turn it on ```yaml features: span_store: true trace_explorer: true agent_sessions: true # reads X-Gateway-Agent-Id and X-Gateway-Agent-Version session_tracking: true # agent_sessions needs it agent_insights: true # this page ``` | Flag | Default | Kind | Requires | |---|---|---|---| | `agent_insights` | `false` | tenant read | `trace_explorer` | Readers need `logs:read`; costs need `analytics:read` with `usage_valuation`; tool names need `content_structure:read` of the team and instructions text `content_sent:read`, as everywhere in the [content ladder](/docs/features/access-control/). With `feature_plan_entitlements` the team's plan must include `agent_insights`. ## Which requests count as an agent A request belongs to an agent when the client names it, or when the gateway recognizes the run: ```http POST /v1/chat/completions X-Gateway-Session-Id: run-42 X-Gateway-Agent-Id: planner X-Gateway-Agent-Version: 2026-11-26.1 ``` | Header | Bounds | Meaning | |---|---|---| | `X-Gateway-Agent-Id` | 1–128 printable characters; needs `agent_sessions` | The agent. A [recognized coding-agent run](/docs/features/agent-recognition/) names its agent too. | | `X-Gateway-Agent-Version` | 1–64 characters kept; needs `agent_sessions` | Optional. The version the client gives its agent. | Without a declared version the gateway gives each version a fingerprint (`v-` and eight hex digits) of what the request was made of: its instructions (chat system and developer messages, the Messages `system`, the Responses `instructions`), the names of the tools it offered and the model alias. A change to any of them is a new version. The request span records the version and keyed digests (HMAC, keyed from the provider encryption key, else the session signing key) of the instructions and of the tool names, never their text, so a reader without the sent view cannot test a guessed prompt against them; without either key each replica keys its own digests and fingerprints differ between replicas; a small catalogue keeps, per version, the models, the hashes, the tool names and a recent request to read the instructions from. ## The page - **Agent usage**: requests per step of the time range for the eight most used agents, the rest as *other agents*. - **Recent agents**: one row per team and agent, most recently seen first: last seen, versions, p95 latency of its requests, tokens, cost (`≥` when some request could not be valued, *Unknown* when none could, never zero), spans of its traces and error rate. - **Most expensive agents** and **Highest latency agents**: the ten first by cost and by p95 latency. - **The agent panel**: its versions with the same figures, declared or fingerprinted, the models and the tools, and links to the agent's spans (*View spans*) and sessions (*View sessions*). - **Compare two versions**: whether the model, the tools and the instructions changed; the tools added and removed for readers of the records' structure; the two versions' instructions side by side for readers of the sent view (each read is an audited read of a captured record; a version whose requests were not captured shows *Not captured*). ## API All routes also answer under `/api/admin`, with a console session and the reader's team scope. | Route | Purpose | Parameters | |---|---|---| | `GET /api/v1/admin/agent-usage` | Agents, series and rankings | `from`, `to` (default the last 24 hours, at most 92 days), `team` (one team) | | `GET /api/v1/admin/agent-usage/{agent}` | One agent's versions | `team` (one team's agent), `from`, `to` | | `GET /api/v1/admin/agent-usage/{agent}/compare` | Two versions side by side | `team` (required), `a` and `b` (the two versions), `from`, `to` | ```json { "agents": [ {"team_id": "support", "agent": "planner", "requests": 312, "errors": 4, "spans": 1288, "versions": 2, "p95_duration_us": 2140000, "tokens": 410233, "cost_state": "known", "cost_usd": "0.412", "first_at": "2026-11-25T10:00:00Z", "last_at": "2026-11-26T09:58:12Z"} ], "series": [{"team_id": "support", "agent": "planner", "points": [{"at": "2026-11-26T09:00:00Z", "requests": 14, "errors": 0}]}], "highest_latency": [], "most_expensive": [], "valuation_shown": true, "step_seconds": 3600 } ``` The schemas are in the [API reference](/docs/api/). ## Limits and engines - Figures are read from the spans of the engine in use (`spans.engine`), the catalogue from the database on both engines. - A version's catalogue keeps at most 8 models and digests and 64 tool names (each cut to 64 bytes on a character boundary); a list holds at most 500 agents. - p95 latency is the continuous 95th percentile of the requests' durations, as on the Usage page, on both engines. - An agent is one team's: the same name in two teams is two rows. Agents and versions are what the client declared or the gateway derived; they are not authenticated. ## Upgrading Migration 283 adds the version catalogue (`gateway_agent_versions`). Requests written before the flag was on have no version: their agent appears with no versions until it sends new traffic. # Query language and saved views **Last updated:** 2026-11-27T07:51:36-03:00 (UTC-3) The gateway has one query language. You write the same string in the **Traces** screen, in the **Request logs** screen, in the filter of an evaluator rule and in an alert rule, and you can keep it as a saved view. It reads the gateway's own facts about a request (did it fall back, which arm of a canary served it, did a cache answer, what did each guardrail decide, which customer and team it belongs to, which prompt revision it used, how it was judged) next to the usual ones (status, model, duration, tokens, cost). This page is the reference of the language and of saved views. Start with [the trace explorer](/docs/features/trace-explorer/) if you have not used the Traces screen yet. ## Turn it on ```yaml features: usage_analytics: true request_logs: true trace_query: true # the query language and saved views (off by default) span_store: true # needed for traces, spans and span fields on the request log trace_explorer: true # the Traces screen ``` `trace_query` needs `request_logs`. It is a tenant feature: with team plans, a team role uses it only for teams whose plan includes it. You can also turn it on from **Settings → Features** or with `PUT /api/v1/admin/features/trace_query`. With `trace_query` off nothing here is available, with one exception that keeps the Traces screen as it was: its query bar still reads terms joined by AND (`status:error model:chat* duration>2s`, a leading `-` to negate), and refuses everything else with a message that names the feature. ## Write a query A query is a list of terms. Terms written side by side must all hold. | You write | It means | |---|---| | `status:error` | the field equals the value | | `model:chat*` | the value starts with `chat` (a trailing `*` is the only wildcard) | | `session:*` | the field has a value | | `-session:*` | the field has no value | | `name:"POST /v1/chat/completions"` | a value with spaces, in double quotes (a quoted value is never a wildcard) | | `name:"POST /v1/chat"*` | a prefix with spaces: the `*` goes after the closing quote | | `duration>2s`, `cost<=0.05`, `tokens.input>=1000` | a comparison on a number, a duration (`250ms`, `2s`, `1m`, `1h`; a bare number is milliseconds) or a cost in US dollars | | `duration:[1s TO 5s]`, `http_status:[500 TO *]` | a range, both ends included; `*` leaves a side open | | `model:(chat OR fast*)` | any of up to 32 values | | `a b`, `a AND b` | both | | `a OR b` | either | | `-a`, `NOT a` | not | | `(a OR b) c` | parentheses group; without them AND binds tighter than OR, so `a b OR c` is `(a b) OR c` | | `refund`, `"charged twice"` | a word or a phrase in the captured content (see [text search](#search-the-captured-text)) | `AND`, `OR`, `NOT` and `TO` are read in any case. A value that is one of those words, or holds a space, a parenthesis or a bracket, goes in quotes: `model:"or"`. Time is never part of the query: every screen has its own time range, and every read is bounded by it. A term that compares a missing value is false, and its negation is true: `-cost>1` keeps the rows with a cost of at most 1 and the rows with no cost at all. ### Limits | Limit | Value | |---|---| | Length of a query | 4,096 bytes | | Terms (each value of a list counts) | 64 | | Nesting of parentheses and negations | 8 levels | | Values in a list | 32 | | Length of a value | 256 bytes | | Length of a text search phrase | 2 to 128 bytes | A query over any of them is refused before anything is read. A refusal always says what is wrong and lists the fields you may use; it never shows a statement. Whatever you write in a value is passed to the storage engine as a bound value, never as part of a statement. ## Scopes A query selects one kind of row. The fields you may write depend on it. | Scope | Selects | Where | |---|---|---| | `traces` | traces: one row per team's summary of a trace | Traces screen, **Traces** | | `spans` | spans | Traces screen, **Spans**; alert rules on the spans signal | | `logs` | request log rows | Request logs screen; alert rules on the requests signal | | `rules` | one request, as the gateway captures it | the filter of an evaluator rule | | `sessions` | sessions: one row per team's summary of a session | Traces screen, **Sessions** ([sessions and end users](/docs/features/sessions-and-users/)) | | `users` | end users: one row per team's end user over the time range | Traces screen, **Users** ([sessions and end users](/docs/features/sessions-and-users/)) | `GET /api/v1/admin/query/fields?scope=logs` lists the fields of a scope **for the session that asks**: a field your rows do not show is not listed and not accepted (see [who may filter on what](#who-may-filter-on-what)). ## Fields ### Fields of a request, a span or a trace | Field | Type | Scopes | What it is | |---|---|---|---| | `status` | `ok`, `error`, `unset` | traces, spans, logs | A trace is an error when one of its spans is. A request is an error when it answered 400 or more, or its answer was cut after it started | | `http_status` | number | spans, logs | The HTTP status | | `error_code` | text | spans, logs | The gateway's error code | | `origin` | text | traces, spans, logs | How the traffic entered: `app`, `evaluation`, `experiment`, `playground`, `helper`, `shadow`, `replay` | | `model` | text | all | The model alias (of a trace: any alias its requests used) | | `requested_model` | text | spans, logs | The model the client asked for, when the gateway served another | | `provider`, `provider_model` | text | spans (`provider` also logs) | The provider connection and its own model name | | `operation` | text | spans, logs | `chat`, `embeddings`, `responses`, ... | | `route` | text | spans | The API route of a request span | | `team` | text | traces, spans, logs | Team ID | | `organization` | text | traces, spans, logs | Organization ID, exact (`organization:org_a`; no wildcard): the rows recorded in the organization, and the rows that record none whose team is in it now. The same rule as the usage query's `organization` dimension. Needs the `organizations` feature; not available in an evaluator's filter, which matches spans as they are stored | | `key`, `principal` | text | spans, logs (`key` also rules) | The key and its principal | | `owner` | text | logs | The owner of the key: `user:` or `workload:` (needs `identity_ownership`) | | `end_user`, `session` | text | all | The end user and the session the client declared | | `parent_session`, `agent` | text | spans | The session a sub-session was started from, and the agent the client declared | | `tag.` | text | spans, logs, rules | A request tag: `tag.env:prod`, `tag.env:*` | | `request_id`, `trace_id`, `span_id` | text | as they apply | Identifiers | | `name` | text | traces, spans | The root span's name of a trace, or the span's name | | `duration`, `ttfb` | duration | `duration` all but rules; `ttfb` spans, logs | Total time, and time to the first byte (`ttfb` on logs needs `request_timing`) | | `cost` | money | traces, spans | Cost in US dollars | | `tokens.input`, `tokens.output`, `tokens.total` | number | traces, spans, logs | Input tokens, output tokens, and their sum | | `tokens.cached`, `tokens.reasoning` | number | spans | Cached input tokens and reasoning tokens | | `service_tier` | text | spans, logs | Service tier | | `helper`, `batch`, `parent_request` | text | logs | Helper sub-kind, batch ID, and the request a helper or judge call was made for | ### The gateway's own facts | Field | Type | Scopes | What it is | |---|---|---|---| | `fell_back` | `true`, `false` | traces, spans | A request moved to another target | | `attempts` | number | spans, logs | Provider sends the request made (on logs it needs `request_attempts`) | | `canary.side` | text | spans | The arm of a canary rollout: `stable` or `canary`; empty without a rollout | | `shadow` | `true`, `false` | traces, spans, logs | Shadow traffic | | `auto_route` | text | spans | The auto-routing alias that chose the model | | `cache` | `hit`, `none` | traces, spans | A cache answered | | `cache.kind` | text | spans | Which cache answered: `exact` or `semantic` | | `guardrail.flagged` | `true`, `false` | traces, spans | A guardrail flagged, masked or blocked | | `guardrail.blocked` | `true`, `false` | spans, logs | A guardrail blocked the request | | `guardrail..outcome` | text | spans | What one guardrail decided: `passed`, `blocked`, `masked`, `would_block`, `would_mask` | | `timeout` | text | spans, logs | The timeout that ended the request: `first_byte`, `idle`, `max_duration`, `client_stall`, `request`, `attempt` | | `valuation` | `known`, `partial`, `unknown`, `none` | traces, spans | Whether the cost is known | | `customer.org`, `customer.team`, `customer.member` | text | spans | The customer the request was made for | | `prompt.id`, `prompt.revision` | text, number | spans, logs | The registry prompt and the revision the request was built from: with [`prompt_tracking`](/docs/features/prompt-registry/#prompt-revision-on-traffic) the one it named (render token or declared headers) or else the [required system prompt](/docs/features/enforced-system-prompt/); without it, the required system prompt only, on request spans while `trace_query` is on. On the request log it needs `prompt_tracking` | | `prompt.source` | `rendered`, `system`, `declared` | spans, logs | How the gateway knows the prompt revision: `rendered` and `system` are observed by the gateway, `declared` is the client's claim. Needs `prompt_tracking` | | `prompt.label` | text | spans, logs | The [prompt label](/docs/features/prompt-registry/#labels-and-deploy-to) the render resolved (`production`, `staging`), when the prompt was rendered by label (`prompt_labels`) | | `capture` | `none`, `audit_only`, `evaluation` | spans | Whether the request's content was captured, and for what | | `span.kind` | `request`, `routing`, `provider_attempt`, `cache`, `guardrail`, `tool`, `judge`, `helper`, `app` | spans | Span kind | | `span.subkind`, `span.attempt`, `span.final` | text, number, `true`/`false` | spans | A request's operation, the provider attempt number, and the attempt that answered | | `trace.spans`, `trace.llm_calls`, `trace.tool_calls`, `trace.errors` | number | traces | Counts of a trace | | `trace.tokens` | number | traces | Input plus output tokens of the whole trace (a [monitor](/docs/features/evaluation-monitors/#count-traces-by-their-aggregates) counts traces by it) | | `tools.available` | number | spans | How many tools the request offered the model, on request spans. Recorded with `query_tool_fields` | | `issue` | text | spans | An instrumentation issue of an [ingested application span](/docs/features/otlp-ingest/#instrumentation-issues), by code: `issue:invalid_tokens`; `issue:*` for any | | `service` | text | spans | The `service.name` of the application that sent an ingested span | | `tools.called` | number | spans | How many tool calls the model's answer made, on request spans. Recorded with `query_tool_fields`; a streamed answer is counted with `stream_usage` on | | `review.queue` | text | traces, spans, logs | A [review queue](/docs/features/human-review/) the trace is an item of, by queue ID; `review.queue:*` is any queue you may read. Needs `query_review_queue` | `span.name` and `span.status` are other spellings of `name` and `status`; `trace.cost` and `trace.duration` of `cost` and `duration`. ### Tools a request offered, and review queues Two operator flags add facts that the gateway does not record by default. **`query_tool_fields`** makes the request span record two counts, never a tool's name, its arguments or its result: `tools_available`, the tools the request declared (`tools` of Chat Completions, Messages, Responses and Interactions; the `functionDeclarations` of each generateContent tool), and `tools_called`, the tool calls of the model's answer (a chat message's `tool_calls`, a Messages `tool_use` block, a Responses `function_call` or `custom_tool_call` item, a Gemini `functionCall` part). Ask for a request that offered tools and called none with: ```text tools.available>0 tools.called:0 ``` In the traces scope the same query keeps the traces with such a request. Counts start with the requests made after the flag is on. A streamed answer is counted by the stream observer, which reads every event only with `stream_usage` on; without it a streamed request records `tools.available` alone, and `tools.called:0` does not match it. A request the provider refused records no `tools.called`. **`query_review_queue`** adds `review.queue:`, which keeps the traces that are items of the queue: a trace or span item names its trace, a request item the request's trace, a session item the traces of the session in the time range. `review.queue:*` keeps the traces of any queue. Only the queues of your teams count, and only for a reader of evaluations (`evals` on, `evals:read`); a queue of another team matches nothing. The term names at most 2,000 traces, the newest items first, and says so when it names more (`evaluation_filter_truncated`). `NOT review.queue:` keeps the rest. An evaluator's filter does not take it: queue membership is read when a query runs, and a live filter matches a span as it is stored. ### Evaluation results and feedback For readers of evaluation results (`evaluation_results` on, `evals:read`), in every scope but `rules`: | Term | Keeps | |---|---| | `evaluation..assessment:fail` | what an evaluator judged `pass`, `fail` or `none`; `evaluation.any.assessment:fail` for any evaluator | | `evaluation..value>=0.5` | a numeric result compared with a number | | `evaluation..value:good` | a categorical result equal to a label | | `evaluation.:*` | what the evaluator judged at all | | `evaluation..source:human` | results by who made them: `llm`, `code`, `human`, `feedback`, `api` | | `evaluation..version:2` | results of one version of the evaluator | | `feedback..value<3`, `feedback..value:neutral`, `feedback.:*` | the same for human and end-user labels | | `feedback..submitter:alice` | feedback one submitter sent | | `trace.failed_evaluations>=2` | traces by their number of failed results | In the `sessions` and `users` scopes the same terms select the sessions or end users with such a result (on a session, on its traces, or on the end user's requests), counted per team, with `session.failed_evaluations` and `user.failed_evaluations` in place of `trace.failed_evaluations`; text search and topic terms are not read there. A result belongs to a trace, whichever of its spans was judged: `evaluation.groundedness.value<0.5` keeps the traces where any span got such a result, and `child.evaluation.groundedness.value<0.5` is the same term in the traces scope. On the request log, such a term keeps the requests of the traces it names. Results are read from the start of the time range to a day after its end, because a judge finishes after the request it judged. Each term names at most 2,000 traces; when more match, the newest are used and the answer says so (`evaluation_filter_truncated`, or the header `X-Query-Evaluation-Truncated` on the request log). ### Topics For readers of [Topics](/docs/features/topics/) (`topics` on, `topics:read`), in the `traces`, `spans` and `rules` scopes: | Term | Keeps | |---|---| | `topic.:""` | the units of the topic with that name, in the live maps the reader sees; the name is quoted, and `*` after the quotes matches the start of a name | | `topic.:outlier` | the units assigned to no topic of the facet | | `topic.:none` | the units with no assignment in the facet at all | | `topic.:*` | the units assigned to some topic of the facet | | `topic.id:` | the units of one topic by its ID, of a live map or a snapshot | A topic belongs to a whole trace, session or run, so a topic term takes no `child.` or `parent.` prefix; in the `spans` scope it keeps the spans of the topic's units. Each engine reads the term as a join on the topic assignments, so it is exact for a topic of any size. The request log and alert rules do not take topic terms. ### Spans of a trace, and spans of a request Some facts sit on one span of a request, not on the trace: the canary arm is on the routing step, a guardrail's outcome on the guardrail step, the provider on each attempt. - **In the traces scope**, write a span field as it is. `canary.side:canary` keeps the traces that have a span on the canary arm; `provider:openai http_status:500` keeps the traces that have a span of that provider and a span with that status (not necessarily the same one). - To ask for **one span that is several things**, use `child.`: `child.provider:openai child.http_status:500` keeps the traces where one attempt at that provider answered 500. The `child.` terms joined by AND in one group name the same span. - **In the spans scope**, `child.field` is about a direct child of the span and `parent.field` about its parent: `span.kind:tool parent.span.kind:request`, `child.status:error`. - **In the logs scope**, a span field keeps the requests that have such a span: `canary.side:canary status:error`, `cache.kind:semantic customer.org:acme`. It needs `span_store`, and each such term names at most 2,000 requests (`X-Query-Span-Truncated` otherwise). `child.` and `parent.` are not read there. Related spans are read within the time range and one day around it, and only among the spans your teams may read. ### What is not a field A field exists when the gateway records the fact on a span or on a request. These are asked another way: | Looking for | Write | Why there is no field | | --- | --- | --- | | An environment (production, staging) | `tag.env:prod`, with `env` in the [tag taxonomy](/docs/features/usage-tags/) | An environment is a request tag here, not an object of its own: the tag is already filtered, counted as a facet (`tag.env`), read by evaluator rules and by alert rules | | A tool that was called | `child.span.kind:tool`, `child.span.name:`, `trace.tool_calls>0` | A tool call is a span | | Traces with comments | the comment count on the row, and the Annotations tab | Comments are text written by people and are not searched by the language | | The requests of an experiment run | `origin:experiment`, and `run_id` on `GET /api/v1/admin/evaluations` | A run is read from its own screen and API | ## Search the captured text A bare word or a quoted phrase searches the text of [captured content](/docs/features/content-capture/): the sent view of the request (the messages after the input guardrails) and the answer. It is case-insensitive and matches anywhere in the text. ```text refund status:error "charged twice" OR "double charge" -refund model:chat* ``` Three rules bound it: 1. **Only content readers.** It takes `content_sent:read` of the team, the permission that shows the same text in the trace detail ([who reads captured content](/docs/features/content-capture/)). In the built-in roles that is the administrator, the organization admin and the team administrator, each within its teams. Anyone else gets a refusal, nothing is read and nothing is audited. Media and reasoning are never searched, and the received view (the request before the guardrails masked it) is not searched either: a secret a guardrail masked is not found. 2. **Bounded.** One search reads the newest `trace_query.text_search_max_records` captured records of the time range (default 500), and the first `trace_query.text_search_max_record_bytes` bytes of each side of each record (default 65,536). When older records were left unread the answer says so (`text_search.truncated`; the Traces screen shows a note): shorten the time range to search them. Content is encrypted at rest, so there is no index: the gateway decrypts and scans, which is why the bound exists. 3. **Audited.** Each search writes one audit row, `content_capture.search`, with who searched, which teams and how many records were read. The phrase is never stored or logged. The reads one question makes (the list, its facets, its chart) share one search for 30 seconds; a query searches at most 8 distinct words or phrases; and the Traces screen suspends auto-refresh while the query searches text, so a timer never writes audit rows. Text search needs `content_capture`. Set `text_search_max_records` to `0` to turn it off while keeping the rest of the language. Rules and alert rules never read content: a text term there is refused. ## Who may filter on what A filter never answers what a column would not show. | You do not see | So you cannot filter on | |---|---| | tags (`usage_tags` off) | `tag.` | | sessions (`session_tracking` off) | `session`, `parent_session` | | end users (`end_user_tracking` off) | `end_user`, `customer.member` | | cost (`usage_valuation` off, or no `analytics:read`) | `cost`, `valuation` | | evaluation results | the `evaluation.`, `feedback.` and `trace.failed_evaluations` terms | | captured content | text search | | a request log column behind a feature that is off | `owner`, `ttfb`, `attempts`, `http_status` (`request_log_status_code`) on logs | | tool counts (`query_tool_fields` off) | `tools.available`, `tools.called` | | review queues (`query_review_queue` or `evals` off, or no `evals:read`) | `review.queue` | A refused field is reported as unknown, and is absent from `/query/fields` and from the completion. Every read filters by your teams before anything is counted or paged, and of each team only what it recorded in its current organization. A term cannot widen that: `team:other-team` matches nothing for a reader who is not in it. ## In the Traces screen The query bar completes field names as you type, proposes the values of a field after its colon, and proposes `OR`, `NOT` and `AND` (type them in capitals to get them before a field of the same letters). After a short pause it asks the gateway whether the draft would be read and shows the refusal under the bar, before you run it. **Run** or Enter runs it. The parts joined by AND at the top of the query are shown as chips, each with a remove button; a group in parentheses is one chip. With the bar empty and focused, it offers terms taken from the rows on screen: a frequent value of a facet, the slowest twentieth (`duration>=` the p95), an evaluator with failed results, and a tag in use. Each is a valid term; click one to add it. **Add a facet** in the facet rail counts the rows by any text, enum or boolean field of the scope (`valuation`, `key`, `shadow`, ...), beside the default facets. In the spans scope, **Count by a tag** counts a tag's values (`tag.env`); the API also counts `guardrail..outcome`, and `field=tag` lists the tag names in use. **Create alert rule**, in the spans scope with a query, opens a new scheduled [alert rule](#in-an-alert-rule) on the spans the query matches, for a session that may manage alert rules. `GET /api/v1/admin/traces?fields=` chooses what each row carries beside its core: `core`, `cost`, `evaluations`, `content`. Without it a row has cost and evaluations; `fields=core` is the lightest page and reads no evaluation results. A facet shows the 50 most frequent values; rows without a value are not counted. Clicking a value adds the term. ## In the Request logs screen A query bar sits above the filter form. Both narrow the same rows, and each form filter is the same thing as a term: | Form filter (API parameter) | Term | |---|---| | Model (`model`) | `model:` | | Status errors / successes (`status`) | `status:error` / `status:ok` | | HTTP status (`status_code`) | `http_status:` | | Key (`key_id`) | `key:` | | Principal, team, provider, operation, request ID, trace ID | the field of the same name | | End user (`end_user`), session (`session_id`) | `end_user:`, `session:` | | Owner (`owner`) | `owner::` | | Origin (`origin`) | `origin:` | The screen shows the form filters that are set as terms, and **Move into the query** writes them into the query and clears the form. The older parameters stay accepted by the API for good, so links and scripts keep working: `?model=a` and `?q=model:a` return the same page. **Count these rows by** shows the values of one field, or of one tag in use, for the rows on screen (`GET /api/v1/admin/logs/facets`); a value adds its term. The CSV export takes the same `q`. **Create alert rule** opens a new scheduled alert rule on the requests the query matches. A team role reads the log of one team at a time, as before. ## In an evaluator An [evaluator](/docs/features/evaluators/#the-filter-and-sampling)'s filter is one query of the spans scope (a span evaluator) or of the traces scope (a trace or session evaluator), matched in memory when a span is stored; evaluation results and text search are not available in it. A query of the Traces screen also chooses the targets of a [run on chosen traffic](/docs/features/evaluators/#run-on-chosen-traffic). ## In an alert rule A scheduled [alert rule](/docs/features/alert-rules/) may carry a `query` beside its filters: ```yaml alerting: rules: items: - id: canary-errors name: Errors on the canary arm scope: global mode: scheduled signal: requests query: "canary.side:canary status:error -origin:evaluation" metric: count operator: gte threshold: 5 window: 10m ``` `signal: requests` reads the logs scope, `signal: spans` the spans scope. Span fields and evaluation terms work on the requests signal as on the request log; a span rule counts spans by their own fields (`child.` and `parent.` are refused). A rule has no reader, so it never searches captured content. **Preview** shows what the query matches before you save. When a span field or an evaluation term of the query names more than 2,000 requests or traces in the rule's window, the scan fails with `query_truncated` instead of counting a part of them: narrow the term or shorten the window. If `trace_query` is turned off while such a rule exists, the rule is not scanned (its state shows `query_disabled`) rather than run without its query. ## Saved views A saved view keeps what a screen shows: the query, the scope, the time range, the lens, the columns, the sort, the added facets and, on the request log, the form filters. Open **Views** on the Traces or the Request logs screen to open, save, update or remove one. - **Built-in** views are ready-made questions that write their query into the bar: errors, slow (at or above the p95 of the rows on screen), costly, fell back, guardrail flagged and failed evaluations on Traces; errors, slow, rate limited, timeouts, guardrail blocked and failed evaluations on Request logs. - The **star** makes a view your default: the view the screen opens with when you arrive without a question in the address. - The **people** button, for whoever manages a team's or an organization's views, makes a shared view the **team's or organization's default** (`shared_default`): its members' screens open with it unless they chose a default of their own. A team or an organization has one per screen; setting another replaces it. - The **link** button copies an address that opens the view (`#/traces?view=sv_...`, `#/logs?view=sv_...`). It works for whoever may see the view; anyone else is told the view is not shared with them. A view holds no data. Opening one runs its query **as you**, so a shared view never shows anyone more than the screen would; if it uses a field you may not filter on, you get the refusal. A view is yours alone, a team's or an organization's: | Visibility | Who sees it | Who edits and removes it | |---|---|---| | `private` | its owner | its owner | | `team` | the members of the team | whoever may share with that team; its author may still remove it | | `organization` | the members of the organization's teams | whoever may share with that organization; its author may still remove it | A shared view belongs to the team or the organization, not to the person who made it. ### Permissions | Permission | Lets you | Built-in roles | |---|---|---| | `saved_views:read` | see the views of your teams and organizations, and your own | administrator, viewer, team administrator, team viewer, member | | `saved_views:save` | keep, update and remove your own views, and choose your default | the same; not the shared viewer token and not a scoped credential, which name nobody | | `saved_views:share` | share a view with a team you administer, and manage that team's views; an organization admin, with its organization; the administrator, with any | administrator, organization admin, team administrator | The operator role reads no request data and holds none of them. A [custom role](/docs/features/custom-roles/) is a ceiling: it keeps or withholds each of the three, and never adds one its base role lacks. ### Organizations The organization is the tenant. A team's view records the organization the team was in when the view was shared. If the team later moves to another organization, its members no longer see that view; the view is not deleted. An organization's view is never visible outside it. With `organizations` off, views are private or a team's. A view keeps a query, never rows, and who may read a row is decided when the query runs. An organization administrator can therefore save a view over what a team recorded in its organization before the team left: on **Logs** with that team chosen in the form (the view is applied to the team the form names), or with `team:` in the query over the whole organization (`?organization=`). The request log's `q`, its facets, and the evaluation, span and text terms inside them all read the rows the list itself shows for that reader ([when a team moves](/docs/features/organizations/#when-a-team-moves)). In the console, a team role and an organization administrator always read one team, so **Move into the query** leaves the form's team where it is. ### Limits Each person keeps at most `trace_query.saved_views_per_owner` views (default 50) and the gateway `trace_query.saved_views_total` (default 10,000); the total is one bound for the whole gateway, not per organization. A definition is at most 16 KiB, with at most 40 columns, 12 facets and 16 filters. ## Configuration The `trace_query` block of the configuration file bounds text search and saved views. It is read when the gateway starts; the API (`GET /api/v1/admin/query/settings`) and the query bar's help show the effective values and where each comes from, and do not change them. ```yaml trace_query: text_search_max_records: 500 # 0 to 5000; 0 turns text search off text_search_max_record_bytes: 65536 # 1024 to 1048576 saved_views_per_owner: 50 # 1 to 500 saved_views_total: 10000 # 1 to 100000, at least saved_views_per_owner ``` | Parameter | Default | Bounds | What it does | |---|---|---|---| | `text_search_max_records` | 500 | 0 to 5,000 | Captured records one text search reads, newest first. Raise it to search further back at the cost of a slower search; `0` turns text search off | | `text_search_max_record_bytes` | 65,536 | 1,024 to 1,048,576 | Text read of each side (sent view, answer) of one record | | `saved_views_per_owner` | 50 | 1 to 500 | Saved views one person keeps | | `saved_views_total` | 10,000 | 1 to 100,000 | Saved views the gateway keeps | ## API Every endpoint takes a console session. Reads need `logs:read`; saved views their own permissions. | Endpoint | What it does | |---|---| | `GET /api/v1/admin/query/fields?scope=` | The fields of a scope (`traces`, `spans`, `logs`, `rules`, `sessions`, `users`; default `traces`) this session may use, with the syntax, examples, limits and whether text search is available | | `POST /api/v1/admin/query/validate` | Body `{"scope": "logs", "q": "..."}`. Answers `valid` with the canonical `query`, or the refusal in `error`. Reads no data | | `GET /api/v1/admin/query/settings` | The effective `trace_query` block with the source of each value | | `GET /api/v1/admin/traces?scope=&q=&from=&to=` | The trace explorer's list ([trace explorer](/docs/features/trace-explorer/#api)) | | `GET /api/v1/admin/traces/facets?field=` | Facets; `field` may be any countable field of the scope | | `GET /api/v1/admin/logs?q=`, `GET /api/v1/admin/logs/export?q=` | The request log and its CSV export | | `GET /api/v1/admin/logs/facets?field=&q=&from=&to=&team=&status=` | The values of one field for a request log filter. `field` is required; `q`, `from`, `to`, `team` and `status` are the request log's own | | `GET /api/v1/admin/views?surface=` | The views this session sees (`surface`: `traces` or `logs`), with what it may do (`access`) | | `POST /api/v1/admin/views` | Keep what a screen shows as a view: private, or for a team or an organization you may share with | | `GET`, `PUT /api/v1/admin/views/{id}` | Read a view; replace it at its `version` | | `DELETE /api/v1/admin/views/{id}?version=` | Remove a view at its `version` | | `PUT /api/v1/admin/views/default` | Body `{"surface": "traces", "id": "sv_..."}`; `"id": null` clears the default | Keep a view for a team: ```bash curl -sS -X POST "$GATEWAY/api/v1/admin/views" \ -b cookies.txt -H "X-CSRF-Token: $CSRF" -H "Content-Type: application/json" \ -d '{"name": "Canary errors", "visibility": "team", "team": "team_a", "definition": {"schema": 1, "scope": "traces", "range": "24h", "lens": "overview", "query": "canary.side:canary status:error", "columns": ["first_at", "root_name", "duration", "cost"]}}' ``` ```json {"id": "sv_3f6c0d9a41b27e85c0d1a2b3", "surface": "traces", "name": "Canary errors", "visibility": "team", "team": "team_a", "organization": "org_acme", "owner": "usr_...", "own": true, "version": 1, "default": false, "can_edit": true, "can_delete": true, "definition": {"schema": 1, "scope": "traces", "query": "canary.side:canary status:error", "range": "24h", "lens": "overview", "columns": ["first_at", "root_name", "duration", "cost"]}} ``` `range` is `15m`, `1h`, `6h`, `24h`, `7d`, `30d` or `custom` with `from` and `to`. Answers: `403 role_forbidden` (no permission for that team or organization), `404 view_not_found` (a view you do not see), `409 version_conflict`, `409 view_capacity`, `422 invalid_view_definition` (with the reason: an unknown field, a bad range). A validation: ```bash curl -sS -X POST "$GATEWAY/api/v1/admin/query/validate" -b cookies.txt -H "X-CSRF-Token: $CSRF" \ -H "Content-Type: application/json" -d '{"scope": "traces", "q": "status:error AND (model:a or model:b)"}' ``` ```json {"valid": true, "scope": "traces", "query": "status:error model:(a OR b)", "fields": ["model", "status"], "uses": {"evaluation": false, "text": false, "spans": false}} ``` ## Both storage engines The language reads the same on PostgreSQL and on the analytics store. One compiler turns a parsed query into a statement for either, from the same table of fields, and a suite of over 200 queries checks that both answer exactly what a reference matcher in the gateway answers, for an administrator and for readers of each of two organizations. What to expect of cost: a term on a trace or a span reads the same tables the list reads. A span field in the traces scope, and `child.` and `parent.`, add one lookup of the spans of the time range per term; narrow the time range first when the range is wide. Reads that take more than 10 seconds answer `503 query_timeout` and ask for a shorter range or one more filter. See [query language reads](/docs/performance/query-language/) for the measured cost of each form on both engines, and [trace explorer performance](/docs/performance/trace-explorer/) for the explorer's own reads. ## Upgrade `trace_query` adds two tables for saved views (`gateway_saved_views`, `gateway_saved_view_defaults`) in the migration that ships with it; nothing else changes shape. The request log's older parameters are unchanged. Queries the trace explorer already ran (terms joined by AND) mean the same with the feature on or off. The Usage screen has its own [saved analytics views](/docs/features/analytics-saved-views/) (dashboards of widgets); they are a different thing and stay as they are. # Application spans over OTLP **Last updated:** 2026-11-26T05:17:10-03:00 (UTC-3) [Observability](/docs/features/observability/) · [Traces and the span store](/docs/features/traces/) · [Trace explorer](/docs/features/trace-explorer/) · [Public trace API](/docs/features/public-trace-api/) · [Content capture](/docs/features/content-capture/) The gateway already records its own spans for every request: routing, provider attempts, cache, guardrails, tools. Your application knows the rest of the story: which agent ran, which tool it called, which model call the answer came from. With `otlp_ingest` your application sends its own OpenTelemetry spans to the gateway, and both halves become **one trace**: the agent at the top, its tools and model calls under it, and under each model call that went through the gateway, the gateway's request with its routing decision and provider attempts. Nothing gateway-specific is installed in the application. Any OpenTelemetry SDK exports to the gateway with the standard OTLP/HTTP exporter and a gateway key. ## Turn it on 1. Turn on the span store and the ingest (operator controls, off by default): ```yaml features: span_store: true # the gateway's own spans; required otlp_ingest: true # POST /v1/traces accepts application spans ``` Both can also be switched in **Settings → Features** or with `PUT /api/v1/admin/features/otlp_ingest`, with no restart. 2. Create a key for the application's exporter with **only** the scope `traces:write`, on the team the application belongs to (`scopes` on `POST /api/v1/admin/keys`, or the key form in the console). A key without a team is refused: spans always belong to a team, and the gateway never creates one. 3. Point the exporter at the gateway: ```bash export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://gateway.example.com/v1/traces export OTEL_EXPORTER_OTLP_TRACES_HEADERS="Authorization=Bearer " export OTEL_EXPORTER_OTLP_TRACES_PROTOCOL=http/protobuf # or http/json ``` 4. Call the gateway from inside the span that makes the model call, so the request carries the `traceparent` of that span. Most HTTP instrumentation does this already; with `spans.caller_trace: join` (the default) the gateway continues the application's trace. No other header is needed. The endpoint is the standard OTLP path, so `OTEL_EXPORTER_OTLP_ENDPOINT=https://gateway.example.com` also works. ### A complete example (Python, standard OpenTelemetry SDK) ```python from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter from opentelemetry.propagate import inject import requests provider = TracerProvider() provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter())) # reads the OTEL_* variables above trace.set_tracer_provider(provider) tracer = trace.get_tracer("support-agent") with tracer.start_as_current_span("agent.run", attributes={"gen_ai.operation.name": "invoke_agent", "gen_ai.agent.name": "support", "gen_ai.conversation.id": "c-1042"}): with tracer.start_as_current_span("lookup_order", attributes={"gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": "lookup_order", "gen_ai.tool.call.id": "call_1"}): pass # your tool with tracer.start_as_current_span("chat support-model", attributes={"gen_ai.operation.name": "chat", "gen_ai.request.model": "support-model"}) as span: headers = {"Authorization": "Bearer "} inject(headers) # traceparent of the chat span r = requests.post("https://gateway.example.com/v1/chat/completions", headers=headers, json={"model": "support-model", "messages": [{"role": "user", "content": "Where is my order?"}]}) usage = r.json()["usage"] span.set_attribute("gen_ai.usage.input_tokens", usage["prompt_tokens"]) span.set_attribute("gen_ai.usage.output_tokens", usage["completion_tokens"]) provider.shutdown() ``` The trace view then shows `agent.run` → `lookup_order` and `chat support-model`, and under the chat span the gateway's `POST /v1/chat/completions` request with its routing and provider attempt spans. The same works with the Node.js SDK (`@opentelemetry/exporter-trace-otlp-proto`), with any framework that emits OpenTelemetry GenAI or OpenInference spans, and with another gateway or proxy in front of this one, as long as it continues `traceparent`. ### Send spans with curl ```bash curl -sS https://gateway.example.com/v1/traces \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{"resourceSpans":[{"resource":{"attributes":[{"key":"service.name","value":{"stringValue":"shop"}}]}, "scopeSpans":[{"scope":{"name":"shop-agent"},"spans":[{ "traceId":"4bf92f3577b34da6a3ce929d0e0e4736","spanId":"00f067aa0ba902b9","name":"chat gpt-4o-mini", "startTimeUnixNano":"1795615331000000000","endTimeUnixNano":"1795615332400000000", "attributes":[{"key":"gen_ai.operation.name","value":{"stringValue":"chat"}}, {"key":"gen_ai.request.model","value":{"stringValue":"gpt-4o-mini"}}, {"key":"gen_ai.usage.input_tokens","value":{"intValue":"120"}}, {"key":"gen_ai.usage.output_tokens","value":{"intValue":"30"}}]}]}]}]}' ``` The answer is OTLP's own, in the encoding of the upload: `{}` (JSON) or an empty body (protobuf) when every span was stored, otherwise a partial success that counts the spans left out and says why: ```json {"partialSuccess": {"rejectedSpans": "2", "errorMessage": "Spans not stored: 1 invalid_id (unusable trace or span IDs); 1 non_genai (no GenAI attributes and no GenAI span below them)"}} ``` The write is synchronous: a `200` means the spans are stored and readable at once, without waiting for the span writer's flush. ## Formats | What | Accepted | | --- | --- | | Encoding | `application/x-protobuf` (an OTLP `ExportTraceServiceRequest`) or `application/json` (OTLP/HTTP JSON) | | Compression | `Content-Encoding: gzip`, or none | | IDs in JSON | Hex, as the OTLP JSON rule says, or base64, as a generic protobuf-to-JSON encoder writes them. Both are stored as the same lowercase hex. | | Enums in JSON | Numbers or names (`SPAN_KIND_CLIENT`, `STATUS_CODE_ERROR`) | | Signals | Traces only. `POST /v1/logs` and `POST /v1/metrics` answer `404`: the gateway does not store application logs or metrics. Link your log backend from the trace view with `spans.log_link_template`. | ## What is kept **Dialects.** The gateway maps two attribute dialects in full: the OpenTelemetry GenAI semantic conventions (1.37 and later; `gen_ai.*`) and OpenInference (`openinference.span.kind`, `llm.*`). A span typed only by another SDK's type attribute (a key ending in `.observation.type`, `.span.kind`, `.span.type`, `.span_type` or `.spantype`) is typed by that attribute's value, from a fixed table, and the attribute is kept as `dialect_type`: | Value | Sub-kind | | --- | --- | | `generation`, `llm` | `llm` | | `embedding` | `embedding` | | `agent` | `agent` | | `tool` | `tool` | | `chain`, `workflow` | `workflow` | | `retriever` | `retrieval` | | `guardrail` | `guardrail` | | `evaluator` | `evaluator` | | `task`, `span`, `event` | `task` | Any other value keeps the span as sub-kind `untyped`, with the issue `unsupported_dialect`; it is never typed by a guess. **Sub-kinds.** Every stored application span has kind `app` (filter with `span.kind:app`) and one of these sub-kinds (`span.subkind`): | Sub-kind | From `gen_ai.operation.name` | From `openinference.span.kind` | | --- | --- | --- | | `agent` | `invoke_agent`, `create_agent` | `AGENT` | | `workflow` | `invoke_workflow`, `rerank` | `CHAIN`, `RERANKER` | | `llm` | `chat`, `text_completion`, `generate_content` | `LLM` | | `embedding` | `embeddings` | `EMBEDDING` | | `tool` | `execute_tool` | `TOOL` | | `retrieval` | `retrieval` | `RETRIEVER` | | `guardrail` | — | `GUARDRAIL` | | `evaluator` | — | `EVALUATOR` | | `task` | any other operation (issue `unknown_operation`), or `gen_ai.*` attributes without an operation | any other kind | | `untyped` | — | — (a span typed only by another dialect, with a value outside the table above) | | `connector` | a span with no GenAI attributes that connects GenAI spans (below) | | **Connectors.** With `otlp_ingest.keep: genai_and_ancestors` (the default) a span without GenAI attributes is kept when a GenAI span of the same upload is below it, or when a gateway span already stored names it as its parent, or when it is an outgoing call (span kind `client`, such as the HTTP call an agent framework makes) below a GenAI span of the same upload: the gateway writes its own request span on its own clock, often after the application exported, and that span names the call as its parent. So the tree keeps its root (an `http.request` span above two parallel chat calls stays one trace with one root). It is stored as sub-kind `connector` with its name, times and status and no attributes. Any other non-GenAI span is left out and counted as `non_genai` in the partial success. With `keep: genai` only GenAI spans are kept. **Columns and attributes.** Read from a span, by the first attribute present: | Stored as | Read from | | --- | --- | | Trace, span and parent IDs | the span's own (W3C hex) | | Name, times (µs), status | the span's name (printable, at most 200 bytes), start and end, status code (`error` for `STATUS_CODE_ERROR`); `http.response.status_code` as the HTTP status | | Model | `gen_ai.response.model`, else `gen_ai.request.model`, `llm.model_name`, `embedding.model_name` (identifiers only); both are also kept as `response_model` and `request_model` | | Provider | `gen_ai.provider.name`, else `gen_ai.system`, `llm.provider`, `llm.system` | | Tokens | `gen_ai.usage.input_tokens` / `output_tokens` (also `prompt_tokens` / `completion_tokens`, `llm.token_count.prompt` / `completion`), cache read and creation, reasoning. Integers only: anything else is stored as unknown, never zero, with the issue `invalid_tokens` | | Session | `gen_ai.conversation.id`, else `session.id`, on the span or its nearest ancestor in the upload (an exporter that sets it on the root only still puts every span in the session). Marked `session_declared`: the application asserted it | | End user | `user.id`, else `enduser.id`, inherited the same way | | Agent | `gen_ai.agent.name` (and `agent_id`) | | Tool | `gen_ai.tool.name` and `gen_ai.tool.call.id`, kept as the attributes `tool` and `call_id`: structure, shown only to readers with `content_structure:read`. A tool span is named `execute_tool`, whatever the application named it, since the conventional name carries the tool's name | | Error | `error.type` as the error code; an `exception` event keeps its `exception.type`, never its message or stack | | Prompt | `gateway.prompt.id` and `gateway.prompt.version`, as `prompt_id` and `prompt_revision` with `prompt_source: declared` (filter with `prompt.id:`) | | Tags | `gateway.tags`, else another SDK's tags (a key `.tags` or `.trace.tags`, the first by name): a map of string values, or an array of names (stored as `true`), sent as the OTLP value or written as a JSON string. Anything else: issue `tags_malformed`, naming the key | | Retrieval documents | `retrieval.documents..document.id` and `.score`, at most 16, never the document text | | Request parameters | `gen_ai.request.temperature`, `top_p`, `max_tokens`, `frequency_penalty`, `presence_penalty`, `seed`, `choice.count` | | Where it came from | `service` (`service.name`), `service_version`, `scope` and `scope_version` (instrumentation scope), `sdk` (`telemetry.sdk.*`), and the key that sent it | | Events, links | at most 16 events (name and time) and 8 links | Any other `gen_ai.*` attribute is kept under `extra` when its value is a number, a boolean or an identifier (letters, digits and `_ - . : /`), cut to 64 characters with a `…[truncated]` mark, and its name does not suggest written text (`message`, `prompt`, `completion`, `content`, `explanation`, `description`, `instruction`, `input`, `output`, `argument`, `result`, `text`, `document`, `query`, `tool`, `reason`, `name`, `system`); at most 16. Any other attribute is not stored: it is counted in `dropped_attributes` and the first eight names are listed in the issue `attributes_dropped`. The attributes fit `spans.max_attribute_bytes` (2 KiB by default); what does not fit is dropped in a fixed order and marked `attributes_truncated`. Issues are kept whole beside them. ## Content Message content never becomes an attribute. `gen_ai.input.messages`, `gen_ai.output.messages`, `gen_ai.system_instructions`, tool arguments and results, `input.value` / `output.value` and the OpenInference message and document attributes are: - **stored, encrypted**, in the content store when the team's [content capture policy](/docs/features/content-capture/) has the purpose `app_spans` (with `content_capture` and `content_capture_evaluation` on and a content encryption key). The policy's `keys`, `models`, `capture` (request, response or both) and `sample_rate` apply as they do to requests; the record is written once the span is stored, under an ID derived from the team, trace and span. A policy with `app_spans` alone captures no inference request. The messages are normalized to `{"messages":[{"role","content"}]}`: the GenAI parts form (`{role, parts:[{type:"text", content}]}`) becomes text, other parts keep their type. The record is named `otlp..`, has the operation `app_span` and the purpose `app_spans`, and follows the policy's retention and reader grants; the span says `content: captured` and names it; - **discarded** otherwise: the span says `content: not_captured` and carries the issue `content_not_captured`. ```yaml content_capture: policies: - team: support purposes: [audit, app_spans] # app_spans: keep ingested application messages retention_days: 14 ``` **Judges.** A judge or code evaluator reads an application span's content only when the team's policy has **both** `app_spans` and `evaluation` (the policy's `evaluation` limits, models, operation `app_span` and rate, apply too). The record then also keeps a **sent view**: the normalized messages and the answer's text, every string they carry masked (a text part beside an image, a tool call's arguments included) by the local guardrails in effect for the team, key and model (every mask or block guardrail without a provider, at any stage; a monitor never changes text). Judges read that view only, never the messages as received; the received view keeps the messages as sent (`raw`, by attribute) beside the normalized ones, for readers with the content capture reveal grant, when both fit `max_bytes` (otherwise the normalized messages alone, whole). A span whose input or answer is missing or longer than `max_bytes` is not judgeable. | Policy purposes | Span-scope judge | Trace-scope judge (no gateway request in the trace) | | --- | --- | --- | | no `app_spans` | `content_not_captured` | `content_not_captured` | | `app_spans` only | `content_not_captured` (not kept for evaluation) | same | | `app_spans` and `evaluation` | the span's masked messages and answer | the first captured `llm` or `agent` span's messages, the last one's answer | A judge reads only its own team's records, as for gateway requests. When a trace holds a gateway request, a trace-scope judge reads the gateway's captured requests, as before. ```yaml content_capture: policies: - team: support purposes: [app_spans, evaluation] # judges may read the masked sent view guardrails: - id: mask-mail mode: mask detectors: [email] # masks addresses in what judges read ``` ## Cost An application model span (`llm` or `embedding`) carries its own cost, with `cost_source` saying where it came from: - `declared`: a cost the application sent (`gen_ai.usage.cost`, `gen_ai.usage.cost.amount` or `llm.cost.total`, in US dollars), also kept as `declared_cost_usd`; - `price_book_estimate`: without one, the gateway's price book applied to its tokens, by its model as a gateway alias, else by a price book entry with that model ID; also kept as `estimated_cost_usd`. Every token count the price applies to must be known (input and output for a model call, input for embeddings); - `unknown`: neither, or no price (issue `model_not_priced`). Never zero. **Counted once.** A model call that went through the gateway is also the gateway's request span, which the ledger already valued. So an application model span's cost enters trace and session totals only when no gateway request span served that call, that is, when no request span of the same team and trace names it as its parent, directly or through `connector` spans (the HTTP call an agent framework makes between its model span and the gateway). When one does, the ledger's cost counts: the span's cost column reads `none`, so no span list, chart or total adds the call twice, and the span shows both values in its attributes: `declared_cost_usd` or `estimated_cost_usd`, `cost_counted: ledger`, `served_by_request`, `ledger_cost_usd` and `cost_note`. A declared cost that disagrees with the ledger loses: the ledger is what the provider billed through the gateway. An unserved span says `cost_counted: span`. | Case | Span shows | Totals count | | --- | --- | --- | | The application called a model directly, declared US$ 0.50 | `cost_source: declared`, US$ 0.50 | US$ 0.50 | | The application called the gateway; its request cost US$ 0.001 | the span's own cost and `ledger_cost_usd: 0.001` | US$ 0.001, once | | Same, but the application declared US$ 0.50 | both values, with `cost_note` | US$ 0.001 (the ledger wins) | **Whatever the arrival order.** An application span stored after its gateway request is matched as it is uploaded. A gateway request stored after its application span (the usual order: the gateway writes its spans on its own clock) takes that span's call, cost and tokens out of the trace summary as it is written, in the same transaction, on both span engines, and marks the span served. Uploads and the gateway's writes of the same trace hold one lock per trace, so neither misses the other. A second request under the same span takes nothing out again. The call leaves the trace's call count only against a model attempt the request made (a cache hit or a refusal makes none). When an upload holds a trace past the 5-second lock timeout, the gateway writes its batch anyway, corrected from what is committed, and logs `span_store_trace_lock_timeout`; a summary rebuild (`POST /api/v1/admin/traces/summaries/rebuild`) always counts exactly once. When the application's cost was known and the gateway's ledger has none (an unpriced model), the summary keeps cost state `partial`. The trace read returns `app_totals`: the tokens and cost (`cost_usd`, `cost_state`) of the application's model spans that the gateway did **not** serve, and how many it did serve. An embeddings span with 8 input tokens and no output reads input 8, output unknown, total 8. ## Instrumentation issues A problem with a span never drops the span: it is stored with its issues, each with the attribute, what it costs and how to fix it. The span panel of the trace view lists them, with a copyable prompt for a coding agent; filter with `issue:` (`issue:*` for any). The same table is returned by `GET /api/v1/admin/otlp-ingest/settings` (`issue_codes`), and a test keeps this page equal to it. | Code | Attribute | Effect | Fix | | --- | --- | --- | --- | | `missing_model` | `gen_ai.request.model` | The span has no model: its cost cannot be estimated and model facets leave it out | Set `gen_ai.request.model` (and `gen_ai.response.model`) on model and embedding spans | | `invalid_tokens` | `gen_ai.usage.input_tokens` | The token count is stored as unknown, never as zero, and the cost is unknown | Send token counts as non-negative integers (`intValue`), not strings | | `model_not_priced` | `gen_ai.response.model` | No price of the gateway's price book matches the model: the cost is unknown | Use a model alias of the gateway, or price the model in the price book | | `input_malformed` | `gen_ai.input.messages` | The input messages are not a JSON array of messages: nothing is stored or shown as a chat, and evaluators that read structured input skip the span | Send a JSON array of `{role, parts}` or `{role, content}` objects | | `output_malformed` | `gen_ai.output.messages` | The output messages are not a JSON array of messages | As above | | `tags_malformed` | `gateway.tags` | The tags were not read | Send a map of string values or an array of strings, as the OTLP value or as a JSON string | | `invalid_session` | `gen_ai.conversation.id` | The session ID is not usable: the span is in no session | Send 1 to 128 printable characters | | `unknown_operation` | `gen_ai.operation.name` | The operation is not one the gateway maps: the span is typed `task` | Use one of the operations in the table above | | `unsupported_dialect` | — | The span is typed by another dialect's attribute with a value outside the gateway's table | Add `gen_ai.operation.name` or `openinference.span.kind` | | `attributes_dropped` | — | Attributes outside the allowlist were not stored | Nothing to fix unless you need one: `gen_ai.*` attributes are kept | | `content_not_captured` | — | The span carried content and the team's policy has no `app_spans` purpose: it was discarded | Add the `app_spans` purpose to the team's policy | The attribute column names the attribute the issue is about; `invalid_tokens` names the token attribute that was wrong. ## Settings The `otlp_ingest` block is the base of a runtime policy. The **OTLP ingest** panel on the **Logs** page of the console (beside the **Span store** panel, `config:read`), or `PUT /api/v1/admin/otlp-ingest/settings`, replaces it as a whole (audited as `otlp_ingest.set`); `DELETE /api/v1/admin/otlp-ingest/settings` with the version returns to the YAML (audited as `otlp_ingest.revert`). `GET /api/v1/admin/otlp-ingest/settings` shows the policy in force, the source of each value and the issue codes. It applies from the next upload. ```yaml otlp_ingest: max_request_bytes: 4194304 # 1024-33554432; also what a gzip body expands to max_spans_per_request: 1000 # 1-10000 max_traces_per_request: 64 # 1-1000 max_concurrent_uploads: 8 # 1-256, per replica keep: genai_and_ancestors # genai | genai_and_ancestors ``` | Setting | Default | Bounds | Past it | | --- | --- | --- | --- | | `max_request_bytes` | `4194304` (4 MiB) | 1024 to 33554432 | `413 request_too_large`, nothing stored | | `max_spans_per_request` | `1000` | 1 to 10000 | `413 too_many_spans`, nothing stored. Counted while the body is decoded, so a body full of empty spans stops at the bound | | `max_traces_per_request` | `64` | 1 to 1000 | `413 too_many_traces`, nothing stored | | `max_concurrent_uploads` | `8` | 1 to 256 | `503 ingest_busy` with `Retry-After: 1`; OTLP exporters retry it | | `keep` | `genai_and_ancestors` | `genai`, `genai_and_ancestors` | — | Other bounds that apply, while the body is decoded: at most 128 attributes, 32 events and 16 links per span and 64 items per array or map value (the rest is skipped), nesting four levels deep, and 256 values per span on average for the whole upload (past it `413 too_many_values`, nothing stored). After decoding: a span must start within `spans.retention_days` and at most 5 minutes ahead (`out_of_window`); its duration is capped at 24 hours; a trace holds at most `spans.max_spans_per_trace` spans (`trace_full`). With `rate_limits` on, every upload counts as one request in the key's, team's, organization's and end user's requests-per-minute policies, the same counters as inference; past one it answers `429 rate_limit_exceeded` with `Retry-After` before the body is read. Recommended: keep the defaults, and set the exporter's batch size (`OTEL_BSP_MAX_EXPORT_BATCH_SIZE`, 512 by default) below `max_spans_per_request`. The measured cost of an upload on each span engine is in [performance](/docs/performance/otlp-ingest/). ## Answers In the order they are checked: `401` without a valid key; `403 scope_forbidden` without `traces:write`; `404 feature_disabled` without `span_store` (only to a key that holds the scope); `403 team_required` for a key without a team; `429` past a rate policy; `503 ingest_busy`; `415` for another media type or encoding; `413` past a bound; `400 invalid_request` for a body that is not an OTLP trace export; `503 storage_unavailable` when the spans could not be stored (nothing was; send them again). ## Joining the gateway's trace - **`spans.caller_trace: join`** (default): the gateway continues the application's trace ID, and its request span's parent is the application span that made the call. Late spans merge: an application exports its root after its children, and a batch sent minutes later lands under the right parent. A judge run is never mixed in: it lives in its own trace, linked to the trace it judged, so a late judge span does not stretch the application's totals. - **`spans.caller_trace: link`**: the gateway mints its own trace ID and keeps the application's apart (`caller_trace_id`) with a `caller` link. The application's spans stay in the application's trace; the gateway's request trace links to it, and the application trace is found by its own ID. ## Security and isolation - **Identity comes from the key.** Team, organization, key and principal are the authenticated key's. Nothing in the upload names a team; a key without one is refused. - **Teams never see each other's spans.** Every read filters by team (and by the team's current organization) before it builds a tree, counts or pages. A key of another team that uploads spans under your trace ID adds spans only its own team sees; yours are untouched. - **An ingest key cannot read.** `traces:write` writes only: every read of traces, results and evaluators answers `403` to it. Give it only to exporters. - **No content in attributes**, no names copied into anything but the span name, identifiers checked before they become columns. - A span sent twice (an exporter's retry) is stored once. ## Agent transcripts The same route also serves the [agent transcript ingest](/docs/features/agent-recognition/#transcript-ingest). With `otlp_ingest` off it is the only ingest, as before. With `otlp_ingest` on, an upload is a transcript when it carries the header `X-Gateway-Ingest: transcript`; set it in the transcript plugin's exporter headers when you turn `otlp_ingest` on. ## Upgrade notes Migrations 295 to 297 add the policy override and the result retention state, let a content record have the `app_spans` purpose (a constraint replaced without scanning existing rows), and key the retained copy of annotated traces by team as well (two teams may now hold the same trace and span ID). On the analytics store the retained copy moves to `gateway_spans_retained_v2`, filled once from `_v1`. With `otlp_ingest` off nothing changes. Spans are stored in the engine `spans.engine` selects, PostgreSQL or the analytics store; issues live in the span's attributes, so neither engine's span table changes. # Public trace, evaluation and evaluator API **Last updated:** 2026-11-27T14:39:27-03:00 (UTC-3) [Application spans over OTLP](/docs/features/otlp-ingest/) · [Traces and the span store](/docs/features/traces/) · [Query language](/docs/features/query-language/) · [Evaluation results](/docs/features/evaluation-results/) · [Prompt clients](/docs/features/prompt-registry/) The console reads traces, results and evaluators with a session. Code outside the console (a CI job, an external evaluator, a notebook) reads them with a **key of a team**. With `public_trace_api` a key reads its team's traces and spans, its evaluation results and its evaluators, and keeps evaluators as code from CI. The key never names a team: it reaches its own team only, and every read filters by that team (and its current organization) before it counts, pages or builds a tree. ## Turn it on ```yaml features: span_store: true # required public_trace_api: true # tenant flag; under plan entitlements the team's plan must include it evaluation_results: true # for GET /v1/evaluations ``` Then create keys with the scopes each job needs, on the team it works for: | Scope | Allows | Endpoints | | --- | --- | --- | | `traces:read` | Read traces and spans | `GET /v1/traces`, `GET /v1/traces/{trace_id}` | | `evaluations:read` | Read evaluation results, also attached to traces (`fields=evaluations`) | `GET /v1/evaluations` | | `evaluators:read` | Read evaluators | `GET /v1/evaluators`, `GET /v1/evaluators/{name}` | | `evaluators:write` | Save and publish evaluators (also reads them) | `POST /v1/evaluators`, `PUT /v1/evaluators/{name}`, `POST /v1/evaluators/{name}/publish` | | `reviews:read` | Read the team's review queues, their items and comment threads | `GET /v1/review-queues`, `GET /v1/review-queues/{id}`, `GET /v1/review-queues/{id}/items`, `GET /v1/comments` | | `reviews:write` | Add items, review them as one more annotator, comment (also reads) | `POST /v1/review-queues/{id}/items`, `POST /v1/review-queues/{id}/next`, `POST /v1/review-queues/{id}/annotations`, `POST /v1/comments` | | `scores:write` | Write results (already available) | `POST /v1/scores` | | `traces:write` | Send application spans, and nothing else | `POST /v1/traces` ([OTLP ingest](/docs/features/otlp-ingest/)) | Keep reading and writing apart: an exporter's `traces:write` key gets `403` on every read here, and a reader cannot ingest. Every call counts in the key's requests-per-minute policies. A key is never a content reader: no message content, judge reasoning, tool names, price entries or console identities leave through this API. ## Read traces ```bash # The last 15 minutes of provider attempts, cursor by cursor curl -sS "https://gateway.example.com/v1/traces?scope=spans&from=-15m&q=span.kind:provider_attempt&limit=100" \ -H "Authorization: Bearer " ``` `GET /v1/traces` takes: | Parameter | Default | Meaning | | --- | --- | --- | | `scope` | `traces` | `traces` (one row per trace) or `spans` | | `q` | none | A query of the [query language](/docs/features/query-language/): `span.kind:app issue:invalid_tokens`, `origin:app model:gpt-4o-mini`, `session:c-1042`. Evaluation terms need `evaluations:read`; full-text terms are not available to keys | | `from`, `to` | the last 24 hours | RFC 3339 times; `from` also takes a negative duration (`-15m`, `-2h`). At most 92 days apart | | `limit` | `50` | 1 to 200 | | `cursor` | none | `next_cursor` of the previous page | | `fields` | `core,cost` | `core` (always), `cost` (with `usage_valuation`), `evaluations` (needs `evaluations:read`), `attributes` (spans only) | The answer has `data`, `has_more` and `next_cursor`. A read of 100,000 spans is 500 pages of 200; each page is one indexed query, so it never times out. `GET /v1/traces/{trace_id}` returns the team's spans of one trace (at most 2,000, `truncated` says when there are more), the trace summary and `app_totals` (the application's own model spans the gateway did not serve, see [cost](/docs/features/otlp-ingest/#cost)). `fields`: `core`, `cost` and `attributes` by default; `evaluations` adds the trace's results, each also on the span it judged. `fields=core,cost` returns no attributes. ## Read results ```bash curl -sS "https://gateway.example.com/v1/evaluations?q=name:helpfulness%20assessment:fail&limit=50" \ -H "Authorization: Bearer " ``` `q` takes space-separated `key:value` terms, and the same keys as parameters: `name`, `source`, `assessment`, `status`, `evaluator` (ID), `metric_type`, `trace_id`, `span_id`, `request_id`, `session`, `run`. `from` and `to` bound the time a result was written. Results come newest first with a cursor. A result carries its value, assessment, status, target, evaluator and version, and the judge's trace and cost; never the judge's reasoning (`reasoning_state: withheld` says one exists), the console user who wrote it, or a comment. ## Evaluators as code Keep evaluator definitions in your repository and apply them from CI with a key that holds `evaluators:write`: ```bash curl -sS -X PUT https://gateway.example.com/v1/evaluators/helpfulness \ -H "Authorization: Bearer " -H "Content-Type: application/json" \ -d '{"judge_model":"judge","prompt":"Rate how helpful the answer {{output}} is to {{input}}.","output":{"data_type":"numeric","min":0,"max":1,"pass":{"op":"gte","value":0.7}}, "scope":"span","filter":"span.kind:request model:support-model","sample_rate":0.1}' curl -sS -X POST https://gateway.example.com/v1/evaluators/helpfulness/publish -H "Authorization: Bearer " ``` - `PUT /v1/evaluators/{name}` saves the definition as a **new draft version** of the team's evaluator with that name, or creates it (`201`). Live traffic keeps running the published version until you publish. The body is the same definition the console saves (type, prompt and route, rule or code, output and pass criteria, scope, filter, sample rate, runs on, daily ceiling, idle windows), validated the same way. - `POST /v1/evaluators/{name}/publish` publishes the latest version, or `{"version": n}`. The same checks as the console: a judge that calls a model needs a filter, a daily ceiling needs a priced route, a template placeholder must be filled. - `GET /v1/evaluators` lists every type, decision models and code evaluators included; `GET /v1/evaluators/{name}` returns one with its definition, version, published version and `updated_by`. - Every write is audited in the evaluator's history with `key:` as the actor. An evaluator declared in the gateway YAML (`managed_by: yaml`) is refused with `409`. ## Client helpers The [prompt clients](/docs/features/prompt-registry/) in `clients/` (Python, TypeScript and Go, dependency-free, server-side) carry the same calls, with the same transport rules: HTTPS unless loopback, no ambient proxy, no redirects, bounded answers, and errors that keep only the status, the gateway's error code and the request ID. ```python from m7gtw_prompts.observability import ObservabilityClient gw = ObservabilityClient("https://gateway.example.com", key) trace = gw.get_trace(trace_id, fields=["core", "evaluations"]) for span in gw.iter_spans(q="origin:app span.kind:request", start="-1h"): verdict = my_evaluator(span) # your own evaluation gw.submit_score("groundedness", value=verdict, trace_id=span["trace_id"], span_id=span["span_id"]) gw.put_evaluator("helpfulness", definition) # a new draft version gw.publish_evaluator("helpfulness") gw.ingest_spans(otlp_export_dict) # or protobuf bytes ``` ```ts import { ObservabilityClient } from "m7gtw-prompts"; const gw = new ObservabilityClient("https://gateway.example.com", key); for await (const span of gw.iterSpans({ q: "span.kind:app", from: "-1h" })) { /* ... */ } await gw.submitScore("helpfulness", { value: 0.9, traceId, spanId }); ``` ```go c, _ := prompts.New("https://gateway.example.com", key) var trace map[string]any err := c.GetTrace(ctx, traceID, []string{"core", "evaluations"}, &trace) err = c.PutEvaluator(ctx, "helpfulness", definition, nil) ``` ### Run an experiment from code `run_experiment` (Python) runs your application on every item of a dataset, links each output to one new run (`POST /v1/dataset-run-items`, with the gateway request it made when your task returns `request_id`), and posts each of your evaluators' verdicts as a result on the run item. The run and its results appear in **Evals → Runs** beside the gateway's own evaluators. Read a run back with `GET /v1/datasets/{name}/runs/{run}?fields=evaluations,cost,trace`: each item with its results, its ledger cost and its trace ID. The key needs `evals:read`, `evals:write` and `scores:write`. ```python def task(item_input): r = call_my_app(item_input) # through the gateway return {"output": r.text, "request_id": r.headers["X-Request-Id"]} run = gw.run_experiment("support-questions", "nightly-2026-11-26", task, {"exact_match": lambda item, out: out == item.get("expected_output")}) ``` ### Agent evaluations from code `create_agent_eval`, `record_agent_results` and `get_agent_eval` (Python) call the [agent evaluation](/docs/features/agent-evaluations/) API; the runner `m7gtw_prompts.agent_eval` drives them: tasks × targets × trials run on your machine, each trial one trace, and the scorecard read back from the gateway. ### Results from other evaluation libraries Any library that produces a score per example can write it to the span, trace or run item it judged with `POST /v1/scores` (or `submit_score`), with `source: api` and the evaluator's name. For example, with DeepEval, NeMo Evaluator or Pydantic Evals, run the metric in your CI and post each result: ```python # DeepEval: one metric per traced request metric.measure(test_case) gw.submit_score("answer_relevancy", value=metric.score, trace_id=tid, span_id=sid, metric_type="score", assessment="pass" if metric.is_successful() else "fail") # NeMo Evaluator or Pydantic Evals: one row per example of a report for row in report_rows: # each with the run item it scored gw.submit_score(row["metric"], value=row["score"], run_item=row["score_target"]) ``` The results are stored like any other: on the span, filterable with `evaluation.`, in the Quality view and in monitors. ## Review queues and comments A review job outside the console (a labelling tool, a CI step, an external annotator) works the team's [review queues](/docs/features/human-review/) with a key of `reviews:write`. The key reviews as **one more annotator**, `key:`, under exactly the queue's rules: one seat per reviewer, held for the queue's `lock_timeout_seconds`; at most `annotators_per_item` reviewers on an item; the item completes with the last review, and its final values and `disagreement` are computed as for the console. A console reviewer and a key on the same item are two annotators. ```bash KEY="Authorization: Bearer " # Queue the team's request, take a seat, annotate curl -sS -X POST https://gateway.example.com/v1/review-queues/queue_1/items -H "$KEY" -H "Content-Type: application/json" \ -d '{"targets":[{"type":"request","id":"req_123"}]}' curl -sS -X POST https://gateway.example.com/v1/review-queues/queue_1/next -H "$KEY" curl -sS -X POST https://gateway.example.com/v1/review-queues/queue_1/annotations -H "$KEY" -H "Content-Type: application/json" \ -d '{"target_type":"request","target_id":"req_123","scores":[{"name":"helpful","value":1}]}' # Comment on it curl -sS -X POST https://gateway.example.com/v1/comments -H "$KEY" -H "Content-Type: application/json" \ -d '{"target_type":"request","target_id":"req_123","content":"Checked by CI"}' ``` What a key may do is what a console credential session may do: | Rule | Why | | --- | --- | | A key reviews only queues and items assigned to nobody (`403 not_assigned` otherwise); it may still add items to an assigned queue, for its people to review | Assignees are named people; a key is never one | | A key never takes an item another reviewer holds (`409 item_locked`) | It has no `reviews:assign` | | A key reads its own review whole; another reviewer's shows its status only, never who; the finals are not shown, `disagreement` is, as to a console reviewer | Console identities, others' answers and finals are for the people who calibrate | | A key reads no target content here: a `trace` or `span` target is read with `GET /v1/traces` under `traces:read` | A key is never a content reader of captured requests | | A comment by a key names the key; a person's says `person`. A key mentions nobody; threads are on a request, a session or a run item | Mentions notify console users, whom a key does not know | Every write is the key's: results with `key:` as their author, items with `key:` as who added them, comments audited. The review routes need `public_trace_api` and `evals`, not `span_store`: a queue of requests, sessions or run items reads no span. ## Retention of results Evaluation results do not grow forever. With `evaluation_result_retention` (operator control, off by default) and [metadata retention](/docs/features/metadata-retention/) on with a window, a background pass removes in bounded batches the results and the dataset runs (with their items and item results) older than `metadata_retention.retain_days`. It keeps: - human annotations, and the results of a trace or request that has one; - the results of traces kept in the span store's retained copy (traces with an annotation, a review queue item or a dataset item); - datasets and their items: curated ground truth is never telemetry; - runs still running. It stops during a legal hold, like the metadata retention, and every pass that removed something is audited (`eval.result_retention.purge`). `GET /api/v1/admin/evaluations/retention` shows the window, the last pass and the totals. Spans follow `spans.retention_days` on their own. On the analytics store engine the automated results there are removed by the same rule. ## Answers `404 feature_disabled` when `public_trace_api` or `span_store` is off, to every caller before the key is read, as the other flagged public routes answer (datasets, prompts, vector stores, agents); `401` without a valid key; `403 scope_forbidden` without the scope (also `fields=evaluations` without `evaluations:read`); `404 feature_disabled` when, for results, evaluators and reviews, `evals`, `evaluation_results` or the evaluator flags are off; `403 team_required` for a key without a team; `429` past a rate policy; `400 invalid_query`, `invalid_range` or `invalid_request` for a malformed parameter; `404 trace_not_found` or `evaluator_not_found` for an object the team does not have, whoever else has one. # Agent runs recognized from traffic **Last updated:** 2026-11-27T11:37:35-03:00 (UTC-3) [Observability](/docs/features/observability/) · [Traces and the span store](/docs/features/traces/) · [Trace explorer](/docs/features/trace-explorer/) · [Content capture](/docs/features/content-capture/) A coding agent makes dozens of model calls for one thing its user asked. In the request log they are dozens of unrelated rows. With `agent_recognition` the gateway groups them into **runs**: which coding agent made the calls, which calls belong to the same run, how many turns it took, which tools the agent ran in between, which subagents it started and where it compacted its context. Nothing is installed or configured on the client. A coding agent sends its whole conversation with every model call, with headers of its own, and the gateway reads the run from that. It never changes a request and never refuses one because of what it read. What a run keeps is labels and counts: the agent's name, IDs, times, counters and a keyed hash of the task. Prompts, answers, tool arguments and tool results are not part of a run. The text the user typed to start the run is kept only when you turn on [task capture](#the-task), which is off by default. ## Turn it on ```yaml features: ui: true usage_analytics: true request_logs: true session_tracking: true agent_sessions: true span_store: true # the steps of a run are stored spans agent_recognition: true # default false; a tenant read agent_transcript_ingest: false # default false; operator control; see "Transcript ingest" # agent_recognition: # every field is optional; the defaults suit most installations # task_capture: "off" ``` Both flags can also be switched in **Settings → Features** or with `PUT /api/v1/admin/features/agent_recognition` and `PUT /api/v1/admin/features/agent_transcript_ingest`, with no restart. The `agent_recognition` block is set in the gateway YAML and read on every request. | Flag | Default | Class | Requires | What it turns on | | --- | --- | --- | --- | --- | | `agent_recognition` | `false` | tenant read | `agent_sessions` (which needs `session_tracking` and `request_logs`) and `span_store` (which needs `usage_analytics`) | Recognition on every inference request, the run registry, the **Agent runs** screen and the runs API | | `agent_transcript_ingest` | `false` | operator control | `agent_recognition` | `POST /v1/traces`, the [transcript ingest](#transcript-ingest) | With `feature_plan_entitlements`, a team reads runs and uploads transcripts only when its plan includes both `agent_sessions` and `agent_recognition` ([entitlements](/docs/features/entitlements/)). Recognition applies to requests made with a key on the Chat Completions, Messages, Responses and generateContent routes. Calls the gateway makes itself (judges, helper calls, replays) and Playground calls are not runs. A run belongs to a team: requests of a key without a team are labelled with the agent's name but are not listed as a run. Before relying on derived run IDs, check `digest_key` in the [effective settings](#see-the-effective-settings): it must not say `process`. ## What is recognized Each client is recognized by a **rule**: a list of the headers and fixed texts that client sends. The gateway ships rules for the clients below, and you can [add your own](#add-your-own-client-rule). The first rule that matches names the client; a request no rule matches is not recognized (unless `agent_recognition.unknown_client` says otherwise). Every fact in a shipped rule comes from the client's own documentation or source at a pinned version, and was then checked against the requests that version really sends. In the tables below: - **observed** means the signal was seen in requests of the named version, captured on 2026-11-25 by running the client against a local capture server (no provider call was made). The Grok CLI rule was observed on 2026-11-27 on real tasks through the gateway. - **read** means the client's documentation or source states it, and it was not reproduced in a captured request. The captured requests, cut down to what recognition reads, are the fixtures of the gateway's own tests (47 requests in `internal/gateway/testdata/agent_clients/`). ### Claude Code (rule `claude-code`) Source: the [LLM gateway protocol reference](https://code.claude.com/docs/en/llm-gateway-protocol) (sections "Request headers" and "Gateway hint headers"); requests of version 2.1.332. | Signal | What the gateway reads from it | Evidence | | --- | --- | --- | | `User-Agent: claude-cli/ (external, sdk-cli)` | The client | observed | | Header `X-Claude-Code-Session-Id`, sent by default; body `metadata.user_id`, a JSON string that holds `session_id` | The run ID. It stays the same across tool steps, a continued session, a compaction and subagent calls | observed | | Headers `x-claude-code-agent-id` and `x-claude-code-agent-type` | A subagent call and its type: the run `.` under the session's run | observed | | `cc_is_subagent=true` in the first system block | A subagent call, when no header says so | observed | | Header `x-claude-code-parent-agent-id` | The agent that spawned a nested subagent | read | | Header `x-claude-code-request-class`: `main`, `subagent`, `compaction` | The request class. Sent only when the client's gateway hint headers are on | observed | | The same header with `workflow` (read as `main`) or `auxiliary` | The request class | read | | Tool `Agent` (also `Task`) with input `prompt` | The task given to a subagent | observed | | User text blocks that start with ``, ``, ``, `` or `` | Context the client added. The typed text is the text block without such a wrapper | observed | | A last user text that starts with `CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.` | A compaction request | observed | | A conversation that starts with `This session is being continued from a previous conversation that ran out of context.` | A compacted context window of the same run (the session ID does not change) | observed | ### Codex CLI (rule `codex`) Source: [github.com/openai/codex](https://github.com/openai/codex) at tag `rust-v0.172.0` (`codex-rs/login/src/auth/default_client.rs`, `codex-api/src/requests/headers.rs`, `core/src/client.rs`, `protocol/src/protocol.rs`, `prompts/templates/compact/`); requests of version 0.172.0. | Signal | What the gateway reads from it | Evidence | | --- | --- | --- | | `User-Agent: codex_exec/ (...)` with header `originator: codex_exec` | The client | observed | | `User-Agent` prefix `codex_cli_rs/` (the default originator) | The client | read | | Headers `x-codex-turn-metadata`, `x-codex-window-id` | The client, when the User-Agent does not name it | observed | | Header `session-id`; body `client_metadata.session_id` and `prompt_cache_key` | The run ID, unchanged after a compaction | observed | | Header `thread-id` | The agent inside the run. A subagent has its own `thread-id` and its parent's `session-id`: the run `.` | observed | | Headers `x-openai-subagent: collab_spawn` and `x-codex-parent-thread-id` | A subagent call and the agent that spawned it | observed | | `x-openai-subagent` with `review` (a subagent), `compact` (a compaction) or `memory_consolidation` (a helper call) | The request class | read | | Tool `spawn_agent` with input `message` | The task given to a subagent | observed | | User items that start with `` or `# AGENTS.md instructions for ` | Context the client added | observed | | A last user text that starts with `You are performing a CONTEXT CHECKPOINT COMPACTION.` | A compaction request | observed | | A user item that starts with `Another language model started to solve this problem and produced a summary of its thinking process.` | A compacted context window of the same run | observed | ### Gemini CLI (rule `gemini-cli`) Source: [github.com/google-gemini/gemini-cli](https://github.com/google-gemini/gemini-cli) at tag `v0.71.1` (`packages/core/src/core/contentGenerator.ts`, `prompts/snippets.ts`); requests of version 0.71.1 in API key mode. | Signal | What the gateway reads from it | Evidence | | --- | --- | --- | | `User-Agent: GeminiCLI-tui// (...)` (the rule matches the prefixes `GeminiCLI-` and `GeminiCLI/`) | The client | observed for `GeminiCLI-tui/`; the prefix `GeminiCLI/` was not observed | | No run ID in any header or body field | The run ID is [derived](#a-derived-run-id) | observed | | A user part that starts with `` | Context the client added | observed | | A system prompt that contains `You are a sub-agent within a larger development system.` | A subagent call, a derived run of its own | observed | | A task wrapped in `…` | The subagent's task, without the tags | observed | | Tool `invoke_agent` with input `prompt` | The task given to a subagent | observed | | A system prompt that starts with `You are a specialized Task Routing AI.` | A helper call | observed | | A system prompt that starts with `You are a specialized system component responsible for distilling chat history` | A helper call (the client's summarization) | read | The client's Code Assist mode is not recognized specially. ### OpenCode (rule `opencode`) Source: the OpenCode source at tag `v1.19.6` (`packages/opencode/src/session/llm/request.ts`, `agent/prompt/compaction.txt`); requests of version 1.19.6. | Signal | What the gateway reads from it | Evidence | | --- | --- | --- | | `User-Agent: opencode/ …` | The client | observed | | Header `x-opencode-session-id`, one per agent | The run ID | observed | | Header `x-opencode-session`, sent to the vendor's own providers | The run ID | read | | Header `x-opencode-parent-session-id` | A subagent: it has a session of its own, and this header names the run that spawned it | observed | | Tool `task` with input `prompt` | The task given to a subagent | observed | | A system prompt that starts with `You are a title generator.` | A helper call | observed | | A system prompt that starts with `You are a context summarization agent.` | A helper call (the client's summarization) | read | ### pi (rule `pi`) Source: [github.com/badlogic/pi-mono](https://github.com/badlogic/pi-mono) at tag `v0.73.1` (`packages/ai/src/providers/openai-responses.ts`, `packages/coding-agent/src/core/messages.ts`); requests of version 0.73.1. | Signal | What the gateway reads from it | Evidence | | --- | --- | --- | | A system prompt that contains `operating inside pi, a coding agent harness` (the client sends no identifying header: its User-Agent is its SDK's default) | The client | observed | | On the Responses API only: header `session_id` and body `prompt_cache_key` | The run ID. On the other APIs the run ID is [derived](#a-derived-run-id) | observed | | A user text that starts with `The conversation history before this point was compacted into the following summary:` | A compacted context window | read | ### Grok CLI (rule `grok-cli`) Source: the Grok CLI [settings reference](https://docs.x.ai/build/settings/reference) (custom models in `~/.grok/config.toml` with a `base_url`, an `env_key` and an `api_backend` of `messages`, `responses` or `chat_completions`); requests of version 1.0.92 (`@xai-official/grok`) on the three backends, in headless mode. | Signal | What the gateway reads from it | Evidence | | --- | --- | --- | | `User-Agent: grok-shell/ (...)` | The client | observed | | Header `x-grok-client-identifier` (`grok-shell`) | The client, when the User-Agent does not name it | observed | | Header `x-grok-session-id` | The run ID, the same on the tool steps and on the turn summary of the run. The session title call sends it empty and is filed in no run | observed | | User texts that start with `` or `` | Context the client added | observed | | A task wrapped in `…` | The typed text, without the tags | observed | | A system prompt that starts with `You are tasked with generating the session title.` | A helper call | observed | | A system prompt that starts with `Write an ultra-short dashboard line that captures the AGENT'S REPLY` | A helper call (the turn summary) | observed | Not read: `x-grok-agent-id` stayed the same across separate sessions of one installation, so it does not name an agent inside a run; subagents and compaction were not reproduced, and the rule states nothing about them. The helper calls go to the client's own helper model name (`grok-4.6` in this version) on the same endpoint as the custom model; without an alias of that name they are refused and the task still runs. ### What the shipped rules do not recognize - **Cursor and Antigravity.** Cursor's editor calls the model from Cursor's own servers, and reaches a custom endpoint only on a paid Cursor plan (not measured); its command-line agent talks only to Cursor's API; Antigravity has no custom endpoint. None of their model calls reaches a gateway from the client, so there is nothing to observe and no rule is shipped. The evidence is in [coding agents under a budget](/docs/features/quota-protocols/#cursor-and-antigravity). - **Aider.** Its requests carry no identifying header and no run ID. You can add a rule of your own if your installation gives it something to match. - **Not reproduced when the rules were verified:** a client's interactive-mode User-Agent, an automatic (not user-requested) compaction, and nested subagents. The rules cover them as far as the documentation or source states (the *read* rows above). - **A new client version** may change a header or a fixed text. A rule that no longer matches recognizes nothing; it never mislabels a request. See [troubleshooting](#troubleshooting). ## How a run is identified A run ID comes from one of three places, tried in this order. The run records which one as its **basis**. | Basis | Where the ID comes from | | --- | --- | | `declared` | The `X-Gateway-Session-Id` header ([sessions](/docs/features/observability/#agent-session-graph)). The gateway's own header always wins: a client or a wrapper that sets it decides the run, and its `X-Gateway-Parent-Session-Id` the parent | | `client` | The client's own run ID, read from the header or body field its rule names | | `derived` | A keyed digest the gateway computes, for a recognized client that sent no run ID | A fourth basis, `transcript`, marks a run that only a [transcript upload](#transcript-ingest) named. The run ID becomes the request's session, and the client's name its agent, unless the request already declared them with `X-Gateway-Session-Id` or `X-Gateway-Agent-Id`. So the request log, the stored spans, the [agent session graph](/docs/features/observability/#agent-session-graph), the request event and the exported OTLP spans all carry the run with no setting of their own. ### A derived run ID Some clients send no run ID. Every call of a run still repeats the start of its conversation unchanged, so the gateway derives the ID from that: `derived-` followed by 32 hexadecimal characters of an HMAC-SHA-256 over - the caller's organization, team and key, - the client's name, - the system prompt (its first 64 KiB), and - the user messages up to and including the first one the user typed. #### Two runs that begin identically The same first message, under the same key, with the same system prompt, gives the same digest. Most clients write the date and the working directory in the system prompt, which already tells apart runs that start with the same words in different places or on different days. For two such runs in one directory on one day, the gateway uses what the traffic shows: **the request that begins a run looks like no later one**. It holds one typed message, that message is its last item, and nothing from the model is in it yet. - The first run of a digest has the ID `derived-`. - When a request that begins a run arrives and the newest run of that digest has already received an answer, a **new run** starts: `derived--g2`, then `-g3`, and so on (a *generation*). - Every other request (a tool step, a second prompt, a compaction) joins the **newest** run of its digest. - A beginning request that arrives while the newest run has no successful model call yet stays in that run: it is the first call sent again after a failure. The gateway decides this with one indexed read of the run table, made only for derived runs, on the request path, bounded to 150 ms. A new generation also writes its row at that moment, so the run's next call finds it on any replica. Clients that send a run ID, and requests with `X-Gateway-Session-Id`, cost nothing here. The read stays inside the key's team and organization. If the database does not answer in time, the request is served as usual under the plain `derived-` ID, and `agent_run_generation_failed` is logged. A generation whose beginning request was never recorded (its usage row could not be written) stays listed with no model call, and the next beginning request of that digest uses it. Two cases cannot be decided from the traffic, and the gateway does not guess: - **Two identical runs of one key going on at the same time.** While the first is still working, a second begins with the same bytes. The second starts its own generation, and from then on the later calls of *both* runs join that newest generation: the first run stops growing and the second counts the calls of both. If the first has no answer yet when the second begins, both are one run. - **A client that sends its first message again, unchanged, after it was answered.** That request is indistinguishable from the start of a new run, and starts a new generation. Give such clients a run ID (a rule with `run_headers`, or `X-Gateway-Session-Id`) when this matters. Other things to know before you rely on a derived ID: - **A change at the start of the conversation is a new run.** A client that rewrites its system prompt or its first message mid-run splits the run in two. - **The digest needs a stable secret.** The key comes from `storage.provider_encryption_key_env`, or from the console session signing key when there is no provider encryption key. Both are the same on every replica and after a restart. Without either, each process uses a random key (`digest_key: process` in the effective settings): every replica and every restart derives different IDs, and runs split. Configure one of the two secrets first. - **Rotating that secret** changes every derived ID once: runs in progress continue under a new ID. - **Helper calls get no derived ID**: a title or routing call does not begin like the run it serves. `agent_recognition.derive_run: false` turns derivation off: only runs a client identifies, or a caller declares, are recognized. ### Request classes Each recognized request has a class, read from the client's own header when its rule names one, otherwise from the fixed texts of its rule: | Class | Meaning | | --- | --- | | `main` | A call of the run's main agent | | `subagent` | A call of an agent the main agent started | | `compaction` | The client asks the model to summarize the conversation so far | | `auxiliary` | A helper call of the client that is not a step of the run: a session title, a routing decision | Compaction and helper calls are counted as model calls of the run. They start no turn, report no tool steps and never set the run's task. ### Turns A turn is one thing the user typed and the calls it causes. The gateway tells typed text from the context a client adds around it by the rule's `context_prefixes`. - Each model call records `turn`: how many typed messages the context window it sent holds. The number starts again after a compaction, because the window then holds a summary instead of the earlier messages. - The run's `turns` counter adds one for each call whose last message is typed text (`turn_start`), which is the first call after the user typed. - A request answered with status 400 or above adds an error to the run, and no turn and no tool steps. The client sends the same messages again, and the request that succeeds brings them. ### Tool steps A coding agent runs its tools itself (a shell command, a file edit), so the gateway never sees a tool run. It sees the result come back: the client's next request carries the tool results at the end of its conversation. Each result the run has not counted yet becomes a tool step of the run. Which results are new is decided in two steps: 1. **The request offers the results of its last block.** Reading the conversation back from its end, the block covers tool results and model messages that hold only tool calls. It ends at a model message with text, at a message the user typed, or after 256 results. This covers a client that writes each call next to its result (call, result, call, result, as some do on the Responses API) and a model that calls several tools in a row without writing anything. 2. **The run keeps the call IDs it already counted** (the latest 256), and a result whose call ID is among them is not counted again. So a step is counted once, whichever request brings it: two tools of one model answer both count, and a step that a later request, a retry or a compaction sends again adds nothing. A result with no usable call ID cannot be compared, so it counts only when it follows the model's last message. - A step records the **tool's name and the call ID**. Never the arguments, never the result. - **The name of a tool is structure.** The stored span of a step is named `client tool`; the tool's name and call ID are only in its attributes `tool` and `call_id`, which are returned to readers with `content_structure:read` of the run's team and withheld from everyone else ([who reads what](#who-reads-what)). - A step has **no duration**: its time is when the gateway learned of it. - A name is kept only when it is an identifier (letters, digits and a few separators, at most 64 bytes), a call ID only when it is at most 128 characters of letters, digits and `_ - . :`. - A result the client marks as an error (`is_error` on the Messages API) marks the step failed. - **A tool whose result never comes back is not seen**: the run ended, or the user interrupted it, before the next request. - At most `agent_recognition.max_tool_steps` new steps are recorded from one request; the rest are counted (`tool_steps_dropped` on the request span) and not offered again. - The tool steps of one request are stored as at most half of `spans.max_spans_per_request` spans. The run's counter and the `run` block on the request span count every step. - **Steps are recorded after the answer**, when the run is updated, and only for a request that is recorded in the run: answered with a status below 400, with its usage row written. A request answered with status 400 or above counts none and gets no tool span; the client sends it again, and the request that succeeds brings the same steps. The `tool_steps` number on a request span is what that request added, so a request that only repeats known steps shows none. - Two requests of one run answered at the same instant may each record a span for the same tool step; the run's `tool_steps` counter still counts it once. - If the gateway cannot read the run's counted call IDs, the request adds no step (`agent_run_counted_calls_failed` is logged); a later request offers them again only when the model's next message holds no text, so with a model message that carries text these steps are not recorded. ### Subagents A subagent is its own run, listed as a branch of the run that started it. The link has a basis too: | Parent basis | How the link is known | | --- | --- | | `client` | The client names it: an agent ID header next to the session's run ID (the subagent's run is `.`), or a header that names the parent run. An agent ID that contains `.` is not used to build a run ID (it could name the branch of another run): that call stays in the session's run | | `declared` | `X-Gateway-Parent-Session-Id` | | `inferred` | The parent's next request shows the tool call that started a subagent (the rule's `spawn_tools`), and the task in it hashes to the task a recent run began with | | `transcript` | A transcript upload placed the run under its parent | An inferred link is made only between runs of the **same key**, team and organization, for a run that has no parent yet, did not begin before the spawning run, is not that run's own parent, and was last active within `agent_recognition.link_window_minutes` (default 30) before the parent's request. It needs the subagent to have made a call already when the parent reports the spawn. **A subagent started asynchronously, whose first call comes later, is not linked by inference**: it is listed as a run of its own. A run is never listed as its own branch, whatever a client sends as its parent. ### Compaction When a conversation outgrows the model's context window, the client replaces it with a summary and goes on. - The call that asks for the summary has class `compaction`. - The calls after it start with the client's continuation text (the rule's `continuation_prefixes`). They form a new **context window** of the same run; the run's `compactions` counter adds one, and the thread shows a divider at that point. - **One compaction is counted and drawn once.** A compacted window is identified by the summary text (or texts) it began with, which the client repeats unchanged in every later call, so it stays the same window however far it grows. A window that was never compacted is identified by the user messages up to the first typed one; before anything is typed, by the first user message alone. - For a run with a client or declared ID, nothing else changes: the ID is the same before and after. - **For a derived run**, the start of the conversation changed, so the calls after a compaction derive a new ID and are a new run. The gateway names the run it continues (`continues_run_id`) only when exactly one other run of the same key and agent was active within `link_window_minutes`. With two candidates it names none rather than guess. - A client whose rule has no continuation text (see the tables above) shows no divider. ## The task The task is the first thing the user typed in the run, without the client's context blocks and without a wrapper the rule names (`task_wrappers`). By default the gateway keeps **only a keyed hash** of it (its first 64 KiB). The hash is never returned by the API. It links a subagent to the tool call that started it, and it lets two runs with the same task be recognized as such inside a team. It is computed per organization and team, so the same task under another team gives another hash. ### Task capture `agent_recognition.task_capture` keeps the text itself: | Value | Keeps | | --- | --- | | `off` (default) | The hash only | | `preview` | The first 200 characters | | `full` | The first 2,000 characters | The task text is captured content, and it follows the rules of [content capture](/docs/features/content-capture/). It is stored only when **all** of these hold; otherwise the run keeps the hash alone: 1. `agent_recognition.task_capture` is `preview` or `full`. The gateway refuses to load a configuration that sets either with `agent_recognition` on and `content_capture` off. 2. `features.content_capture` is on. 3. A content encryption key is configured (`storage.content_encryption_key_env`). 4. The run's team has an active [content capture policy](/docs/features/content-capture/#policy-fields) that keeps requests (`capture: request` or `both`, not `disabled`) and covers the call that begins the run: its key when the policy lists `keys`, its model when it lists `models`, its operation when it lists `operations`. 5. The policy's `sample_rate` draws the call. A team that keeps one request in a hundred keeps the task of about one run in a hundred. How it is kept: - **Sealed with the content key.** The text has its own random data key (AES-256-GCM), wrapped by the content key, and both seals are bound to the run's team, organization and run ID: a stored text cannot be moved to another run. - **Retention is the policy's.** The text expires after the team policy's `retention_days` (30 when the policy sets none). Past that it is unreadable for every reader and is removed within a minute; the run stays listed with the hash, and its task then reads `hash_only`. - **Kept from the call that begins a run**: the first call of its first turn. A later call stores the text only for a run that has recorded no task at all yet (recognition was turned on mid-run, or the first call could not be recorded). A run whose first call recorded its hash without text (it was sampled out, or task capture was off) keeps the hash alone. Turning task capture on does not add text to runs already listed. - **Erased with the content it belongs to.** An [end-user deletion](/docs/features/data-governance/#end-user-deletion) removes the task text of the runs whose first request is among the erased requests. Deleting a team's captured content (`POST /api/v1/admin/content-captures/delete` with the team, also with a `before` time) removes the task text of that team's runs, those that began before `before` when it is sent. A deletion narrowed to one request leaves it: a run is not a request. In every case the keyed hash stays. - **Shown only while content capture is on.** With `features.content_capture` turned off, the text already kept is shown to nobody (`withheld`); it still expires and can still be erased. - **Covered by content key rotation.** `gateway content-rewrap` moves the task texts with the captured records, the rotation counts them, and a replica refuses to retire a content key an unexpired task text still names ([rotating the content key](/docs/features/content-capture/#rotating-the-content-key)). Who reads it: a person with `content_sent:read` of the run's team. Each read is recorded in the control audit as `agent_run_task.read` (target `run: team: view:sent`) before the text is decrypted; a read that cannot be audited shows nothing. The API answers a `task` object with a state instead of leaving a reader to guess: | `task.state` | Meaning | | --- | --- | | `shown` | The text follows in `task.text` | | `withheld` | The text is kept, and you lack `content_sent:read` of the team, or `content_capture` is turned off, or the read could not be audited | | `hash_only` | No text is kept for this run: task capture kept none, or the text was erased, or it expired and was removed | | `expired` | The text passed its retention and is not removed yet (it is within a minute) | | `unreadable` | The content key that sealed it is not configured | | `none` | The run shows no task (it began with a compaction summary, or only helper calls were seen) | ## What is stored, and where | Where | What | | --- | --- | | Table `gateway_agent_runs` (PostgreSQL, migration 220) | One row per run: team, organization, run ID, key, principal, agent and agent type, the basis of the ID and of the parent link, the parent run, the run it continues, the task hash, first and last time, counters (model calls, tool steps, turns, compactions, errors), the call IDs of the latest 256 tool steps it counted, whether it was seen in traffic or in a transcript, the first request and trace ID. Under task capture also the sealed task text, its key reference and its expiry | | The request span of each model call ([span store](/docs/features/traces/), either engine) | An attribute block `run`: `client`, `client_basis` (`user_agent`, `header`, `system_prompt` or `user_agent_product`), `class`, `basis`, `turn`, `turn_start`, `compacted`, `window` (a keyed digest that names the context window), `agent_type`, `parent_basis`, `tool_steps`, `tool_steps_dropped` | | One span per new tool step | Kind `tool`, sub-kind `client_tool`, name `client tool`, attributes `tool` and `call_id` (withheld without `content_structure:read`), `reported_by: client`, `reported_error` and `agent`; zero duration | | The request log and the agent session graph | The run ID as the session, the client as the agent, the parent run as the parent session | | The control audit | One `agent_run_task.read` row per task text read | The steps of a run are spans: they are sampled, bounded and retained like every other span (`spans.sample_rate`, `spans.retention_days`). The money of a run stays in the usage ledger; a run row holds no cost. Exported OTLP spans (`otlp_traces`) carry the same run, in the OpenTelemetry GenAI conventions where one exists. The exported tool span keeps the convention's name, `execute_tool `, and the tool's name as `gen_ai.tool.name`: what your collector receives is yours to restrict. | Span | Attributes | | --- | --- | | The request (server) span | `gen_ai.agent.name` (the client), `gen_ai.conversation.id` (the run ID), `gateway.agent_run.class`, `gateway.agent_run.basis`, `gateway.agent_run.turn`, `gateway.agent_run.compacted`, `gateway.agent_run.tool_steps` | | One `execute_tool ` span per reported tool step, a child of the request span, with the same span ID as the stored one | `gen_ai.operation.name: execute_tool`, `gen_ai.tool.name`, `gen_ai.tool.type: function`, `gen_ai.tool.call.id`, `gen_ai.conversation.id`, `gateway.tool.reported_by: client`, and `gateway.tool.reported_error: true` when the client reported a failure | ### Retention - A run is listed for `agent_recognition.retention_days` (default 30) after its last request, then deleted. - Its spans follow `spans.retention_days`; a run older than its spans is still listed, and its thread says that no span is stored. - Task text follows the capture policy's `retention_days`. - The cleanup runs every minute on every replica, whatever the flag says: turning recognition off never keeps what it stored. ## The Agent runs screen **Observability → Agent runs** lists the runs of a time range, most recent first: the agent, the task (as far as you may read it), the key, principal and team that own it, its counters and its first and last time. Filters narrow the list by agent, team, key and the start of a run ID. The list holds the runs a user started; a subagent run appears inside the thread of the run that started it. A run opens as a **thread**: its model calls, tool steps and compaction dividers in time order, with the steps of its subagent branches, each marked with how the gateway knows it (*observed*, *reported* or *uploaded*). Each model call carries its request and trace ID; its trace is where captured content is shown, to readers the capture policy and their role allow. The same screen has a panel with the [effective settings](#see-the-effective-settings) and the rules in the order they are tried, each with its source. The screen is shown to roles with `logs:read` while `agent_recognition`, `agent_sessions`, `session_tracking`, `request_logs` and `usage_analytics` are on. The thread also needs `span_store`. ## API Every route needs a console session (or an admin Bearer token) and the permission named; the full contract is in the [API reference](/docs/api/). Answers carry `Cache-Control: private, no-store`. | Route | Permission | What it returns | | --- | --- | --- | | `GET /api/v1/admin/agent-runs` | `logs:read` | One page of the runs active in a range, most recent first, with the agent names seen in it | | `GET /api/v1/admin/agent-runs/{id}` | `logs:read` | One run as a thread: the run, its parent, its branches, the runs that continue it, and their steps | | `GET /api/v1/admin/agent-runs/settings` | `config:read` | The effective `agent_recognition` block and the rules | `GET /api/v1/admin/agent-runs` takes these query parameters: | Parameter | Default | Meaning | | --- | --- | --- | | `from`, `to` | the last 24 hours | The range, RFC 3339, at most 92 days. A run is listed when it was active inside it | | `team` | every team you may read | One team. A team outside your membership answers `403 team_forbidden` | | `agent` | all | The exact agent name, one of the `agents` the answer lists | | `key` | all | The exact key ID | | `principal` | all | The exact principal (user or service account) of the key | | `run` | all | The start of a run ID | | `scope` | `roots` | `roots` leaves out subagent runs; `all` lists every run | | `limit` | `50` | 1 to 200 runs per page | | `cursor` | none | The `next_cursor` of the page before | ```json { "runs": [ { "team_id": "platform", "organization_id": "acme", "run_id": "0f025c3f-1934-47ed-9a4e-5e16e68e1d95", "key_id": "key_7f3a", "principal": "ana", "agent": "claude-code", "run_basis": "client", "first_at": "2026-11-25T14:02:11Z", "last_at": "2026-11-25T14:09:47Z", "model_calls": 14, "tool_steps": 11, "turns": 2, "compactions": 0, "errors": 0, "from_traffic": true, "from_transcript": false, "first_request_id": "req-01", "first_trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "children": 1, "task": {"state": "hash_only"} } ], "next_cursor": "", "agents": ["claude-code", "codex"], "from": "2026-11-24T14:10:00Z", "to": "2026-11-25T14:11:00Z", "task_capture": "off", "tool_names_shown": true } ``` `GET /api/v1/admin/agent-runs/{id}` takes `team` when several of your teams use the same run ID (without it, the most recent is read). Its answer has `run`, `parent`, `branches` (at most 100 runs, four levels deep), `continuations`, and `steps`. Each step has a `kind` (`model_call`, `tool`, `turn`, `transcript_call`, `compaction`), a `source` (`traffic` or `transcript`) and a `basis`: | Step `basis` | Meaning | | --- | --- | | `observed` | A request the gateway served | | `reported` | A tool step the client's next request reported; the gateway did not see it run | | `uploaded` | From a transcript; not checked against the traffic | The answer also has `gaps`: plain statements of what the thread does not show (content is never part of a run; tool steps are reported, not observed; only the latest 1,000 spans of a run and the steps of its first 19 branches are read; a derived run is told from another that begins identically only by its beginning request; tool names withheld). A missing run, a run of another team or organization and a team outside your membership all answer the same `404 run_not_found`. ## Who reads what No new permission: a run is read with the permissions that already govern logs and content. | To read | Permission | Built-in roles that hold it | | --- | --- | --- | | The run list and a run's thread (agent, IDs, owners, counters, times, classes, turns) | `logs:read` | `admin`, `viewer`, `team_admin` (an organization admin included), `team_viewer`, `user` | | Tool names and call IDs, in a thread, a trace and a span | `content_structure:read` of the run's team | the same roles, and `operator` (which holds no `logs:read`, so it does not reach the thread) | | The task text | `content_sent:read` of the run's team | `admin`, the organization admin, `team_admin` | | Cost on a model call | `analytics:read`, with `usage_valuation` on | as for the request log | | The effective settings and the rules | `config:read` | every built-in role | Team roles read the runs of their own teams, an organization admin those of its organization, `admin` and `viewer` every team's. A [custom role](/docs/features/custom-roles/) ceiling can withhold any of these permissions and never adds one. Without `content_structure:read` a thread still lists its tool steps, without their names. The same rule holds outside the thread: the [trace view and the read of one span](/docs/features/traces/#read-traces) return a tool step's span without its `tool` and `call_id` attributes, and span lists (the trace explorer's included) never carry attributes. This covers the tool spans a client reported and those a transcript uploaded. ## Organizations and teams - **Identity comes from the key.** The team, organization, key and principal of a run are those of the key that made the request (or uploaded the transcript). Nothing a client sends changes them: a run ID or an agent name is a label of the caller's own traffic. - **Inside a team, the key that began a run owns its place.** Only that key sets the run's parent or moves its start time. Another key of the same team that sends the same run ID adds its steps and counters to the run, and can neither move it under another run nor make it look older. - **A run ID is unique inside a team and organization, not across them.** Two teams whose clients happen to send the same run ID have two runs, each read only by its own team. - **Derived IDs and task hashes differ per organization and team.** The same bytes sent under another organization or another team give another derived run ID and another task hash, so nothing can be correlated across them. - **The organization rule.** Every read returns only the rows recorded under the team's current organization, filtered in SQL before the page bound. A run of another organization answers like a run that does not exist. - **A team that moves** to another organization keeps its ID. The runs it recorded before stay with the organization that recorded them: neither the team's own roles nor the administrators of its new organization read them. The former organization's administrators do, as they read everything else the team recorded there: the runs are in their list, `team=` narrows to the team that left, and a run opens with its steps, branches and parent (see [when a team moves](/docs/features/organizations/#when-a-team-moves)). A run that goes on after the move becomes a second row under the new organization, which the former organization never reads. A gateway-wide administrator stands above organizations and reads both. ## Configuration reference All fields are optional. The block is read on every request, so a change applies to the next request with no restart. The gateway validates the whole block when it loads the configuration, with the flag on or off, so turning the flag on never applies a rule that cannot work. | Setting | Default | Accepted | Effect | | --- | --- | --- | --- | | `agent_recognition.builtin_clients` | `true` | boolean | `false` leaves only your own rules under `clients` | | `agent_recognition.unknown_client` | `none` | `none`, `user_agent_product` | What a request no rule matches is called. `none`: it is not recognized. `user_agent_product`: it is named by the product token of its User-Agent (lowercased, at most 64 characters), as a name only: no run is derived, no class, turn or tool step is read, and it joins a run only when the request declares `X-Gateway-Session-Id` | | `agent_recognition.derive_run` | `true` | boolean | `false` recognizes only runs the client identifies or the caller declares | | `agent_recognition.task_capture` | `off` | `off`, `preview`, `full` | Whether the typed task text is kept: [task capture](#task-capture). Quote `"off"` in YAML | | `agent_recognition.link_window_minutes` | `30` | 1 to 1440 | How far back a subagent's parent, or the run a compacted derived run continues, is looked for when the client names none | | `agent_recognition.max_tool_steps` | `32` | 1 to 256 | New tool steps recorded from one request; the rest are counted | | `agent_recognition.retention_days` | `30` | 1 to 3650 | Days a run stays listed after its last request | | `agent_recognition.transcript_ingest.max_request_bytes` | `4194304` (4 MiB) | 1024 to 33554432 (32 MiB) | Largest `POST /v1/traces` body, also after decompression | | `agent_recognition.transcript_ingest.max_spans` | `1000` | 1 to 10000 | Most spans in one upload | | `agent_recognition.clients` | empty | at most 32 rules | Your own client rules, tried before the shipped ones: [add your own client rule](#add-your-own-client-rule) | ### See the effective settings `GET /api/v1/admin/agent-runs/settings` returns the block as the gateway applies it, defaults filled in, and the rules in the order they are tried. It answers whatever the flags say, so you can see what turning them on would apply. ```json { "enabled": true, "transcript_ingest": false, "builtin_clients": true, "unknown_client": "none", "derive_run": true, "task_capture": "off", "task_capture_chars": 0, "task_capture_state": "off", "link_window_minutes": 30, "max_tool_steps": 32, "retention_days": 30, "transcript_ingest_limits": {"max_request_bytes": 4194304, "max_spans": 1000}, "clients": [{"name": "claude-code", "origin": "builtin", "user_agent_prefixes": ["claude-cli/"], "source": "..."}], "digest_key": "provider_encryption_key", "sources": {"task_capture": "default", "retention_days": "default"}, "restart_required": false } ``` - `enabled` is true when `agent_recognition`, `agent_sessions` and `session_tracking` are all on; `transcript_ingest` when also `agent_transcript_ingest` and `span_store` are. - `task_capture_state` says whether text can be kept: `off`, `ready`, `content_capture_off` or `content_key_missing`. `ready` still needs the team's capture policy. - `digest_key` is `provider_encryption_key`, `session_signing_key` or `process`. With `process`, derived run IDs and task hashes change at every restart and differ between replicas. - `sources` says, for each field, whether its value is from the `yaml` or the `default`. Each rule's `origin` is `yaml` or `builtin`. The **Agent runs** screen shows the same in its settings panel. ## Add your own client rule Use a rule for an in-house agent, a client the gateway does not ship a rule for, or to replace a shipped rule (your rules are tried first, and the first match wins). Read the facts from the client's documentation or from one of its real requests; do not guess a header. ```yaml agent_recognition: clients: - name: acme-agent user_agent_prefixes: ["acme-agent/"] run_headers: [x-acme-session-id] run_body_fields: ["metadata.session_id"] parent_run_headers: [x-acme-parent-session-id] class_header: x-acme-request-kind class_values: {worker: subagent, summarize: compaction, title: auxiliary} context_prefixes: [""] spawn_tools: [spawn_agent] spawn_prompt_fields: [prompt] compaction_request_prefixes: ["Summarize the conversation so far."] continuation_prefixes: ["Summary of the earlier conversation:"] source: "Acme Agent 2.3 request reference, section Headers" ``` A request with `User-Agent: acme-agent/2.3.0` is then recorded as agent `acme-agent`, in the run its `x-acme-session-id` names. A rule matches when **any** of its three identity fields matches; every other field applies only to a request the rule matched. | Field | Meaning | | --- | --- | | `agent_recognition.clients[].name` | Required. The agent name recorded: 1 to 64 lowercase letters, digits, dots, underscores or dashes; no two of your rules may share one | | `agent_recognition.clients[].user_agent_prefixes` | Identity: the request's User-Agent starts with one of these | | `agent_recognition.clients[].identity_headers` | Identity: the request carries one of these headers, with any value | | `agent_recognition.clients[].system_prompt_contains` | Identity: the system prompt (its first 64 KiB) contains one of these. Use it only for a client that sends nothing else, with a phrase no other prompt would hold | | `agent_recognition.clients[].run_headers` | Headers that carry the client's own run ID; the first one present wins. A value is used when it is 1 to 128 printable characters and the header is sent once | | `agent_recognition.clients[].run_body_fields` | Body fields tried after the headers, as dotted paths (`metadata.session_id`). `>` reads a string field as a JSON document and goes on inside it: `metadata.user_id>session_id` | | `agent_recognition.clients[].agent_headers` | Headers that carry the ID of the agent inside the run. A value equal to the run ID is the main agent; any other makes the request a subagent run `.`, unless it contains `.`, in which case it is not used | | `agent_recognition.clients[].parent_agent_headers` | Headers that name the agent that spawned that subagent (for nested subagents) | | `agent_recognition.clients[].agent_type_headers` | Headers that carry a subagent's declared type (the first 64 characters are kept) | | `agent_recognition.clients[].parent_run_headers` | Headers that name the run that spawned this one, for a client that gives every agent a run ID of its own | | `agent_recognition.clients[].class_header` | A header whose value classes the request | | `agent_recognition.clients[].class_values` | The values of that header, each mapped to `main`, `subagent`, `compaction` or `auxiliary`; at most 16. A value not listed leaves the class to the fixed texts | | `agent_recognition.clients[].subagent_system_contains` | System prompt text that marks a subagent's request, when no header does | | `agent_recognition.clients[].auxiliary_system_prefixes` | System prompt prefixes of a helper call that is not a step of the run | | `agent_recognition.clients[].context_prefixes` | A user text block that starts with one of these is context the client added, not what the user typed | | `agent_recognition.clients[].task_wrappers` | Tag names the client wraps a task in (`objective` for `…`); the tags are dropped from the task | | `agent_recognition.clients[].spawn_tools` | The tools the client starts a subagent with | | `agent_recognition.clients[].spawn_prompt_fields` | The input fields of a spawn tool that carry the subagent's task; the first one present is used | | `agent_recognition.clients[].compaction_request_prefixes` | The last user text of a request that asks the model for a summary starts with one of these | | `agent_recognition.clients[].continuation_prefixes` | After compacting, the conversation restarts with a user text that starts with one of these | | `agent_recognition.clients[].source` | Optional, at most 512 characters: where the rule's facts come from. Shown with the rule in the settings | Rules of the rules: - Every list holds at most 16 entries of 1 to 256 characters. Text is matched exactly, as a prefix or a substring, case-sensitive; there are no patterns. Header names are case-insensitive. - A rule needs at least one of `user_agent_prefixes`, `identity_headers` and `system_prompt_contains`. - **Credential headers are refused.** A run or agent ID is stored and shown, so a header whose value is a secret can never be read as one: `Authorization`, `Proxy-Authorization`, `Cookie`, `Set-Cookie`, `X-Api-Key`, `Api-Key` and `X-Goog-Api-Key` are refused in every header field, and the gateway does not load a configuration that names one. - A rule is a label, not a control: anyone who holds a key can send the headers a rule reads. Recognition never grants access, and what it records stays inside the key's own team and organization. ## Transcript ingest Traffic shows what passes through the gateway. A coding agent also keeps its own transcript of the session, which knows more: turns in which no model call reached this gateway, tools whose result never came back, which subagent a step belongs to, and the moment of a compaction. With `agent_transcript_ingest`, a client plugin uploads that transcript after each turn as OpenTelemetry spans, and the gateway files them under the same run. ### Send a transcript `POST /v1/traces` accepts an OTLP/HTTP trace export **as JSON**. With [`otlp_ingest`](/docs/features/otlp-ingest/) on, the same route takes application spans, and a transcript upload must carry the header `X-Gateway-Ingest: transcript` (add it to the plugin's exporter headers). - **Authentication:** a gateway key of a team with the scope `traces:write`. Add the scope when you create the key (`scopes` on `POST /api/v1/admin/keys`, or the key form in the console). - **Format:** `Content-Type: application/json`, optionally `Content-Encoding: gzip`. OTLP protobuf answers `415 unsupported_media_type`. - **Both span engines:** the spans are written to the engine `spans.engine` selects, like the gateway's own. ```bash curl -sS https://gateway.example.com/v1/traces \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "resourceSpans": [{ "resource": {"attributes": [{"key": "service.name", "value": {"stringValue": "acme-agent"}}]}, "scopeSpans": [{ "spans": [ { "traceId": "5b8efff798038103d269b633813fc60c", "spanId": "eee19b7ec3c1b174", "startTimeUnixNano": "1795615331000000000", "endTimeUnixNano": "1795615339000000000", "attributes": [ {"key": "gen_ai.operation.name", "value": {"stringValue": "invoke_agent"}}, {"key": "gen_ai.conversation.id", "value": {"stringValue": "session-42"}} ] }, { "traceId": "5b8efff798038103d269b633813fc60c", "spanId": "eee19b7ec3c1b175", "parentSpanId": "eee19b7ec3c1b174", "startTimeUnixNano": "1795615332000000000", "endTimeUnixNano": "1795615333000000000", "attributes": [ {"key": "gen_ai.operation.name", "value": {"stringValue": "execute_tool"}}, {"key": "gen_ai.conversation.id", "value": {"stringValue": "session-42"}}, {"key": "gen_ai.tool.name", "value": {"stringValue": "bash"}}, {"key": "gen_ai.tool.call.id", "value": {"stringValue": "call_1"}} ] } ] }] }] }' ``` The answer is OTLP's own: `{}` when every span was stored (or was stored already), otherwise a `partialSuccess`: ```json {"partialSuccess": {"rejectedSpans": "1", "errorMessage": "Spans without gen_ai.conversation.id, with an operation other than invoke_agent, chat, execute_tool or compaction, with unusable IDs or times, or past the per-trace bound were not stored"}} ``` The write is synchronous: a `200` means the spans are stored. **An upload counts as a request in the key's [request rate policies](/docs/features/rate-limits/).** With `rate_limits` on, each upload takes one slot in the requests-per-minute policies that an inference request of the same key counts in: the key's, its team's, its organization's and, with `end_user_rate_limits` and an `X-Gateway-End-User-Id` header, the end user's. They are the same counters, so uploads and model calls share one ceiling. Past it the upload answers `429 rate_limit_exceeded` with a `Retry-After` header, before its body is read, and nothing is stored; send it again after that time. Concurrency caps (`max_concurrent`), model policies and token limits do not apply to uploads. A caller without a valid key or without the scope is refused first and takes no slot. An upload is also bounded by its size and span limits ([limits of one upload](#limits-of-one-upload)) and by the key's scope, so give `traces:write` only to the keys that need it. ### Which spans are accepted A span is kept when all of this holds; any other span is counted in `rejectedSpans` and the rest of the upload is still stored. | Requirement | Detail | | --- | --- | | `gen_ai.operation.name` | `invoke_agent` (a turn), `chat` (a model call), `execute_tool` (a tool), or the gateway's own `compaction` (the client marks where it compacted) | | `gen_ai.conversation.id` | Required: the run, 1 to 128 printable characters. Use the session ID the client sends on its requests, so the transcript joins the run the traffic recognized | | `traceId`, `spanId` | W3C hexadecimal, 32 and 16 characters, not all zeros; `parentSpanId`, when sent, 16 | | `startTimeUnixNano`, `endTimeUnixNano` | Both present, the end not before the start. The start must be within `spans.retention_days` in the past and at most 5 minutes ahead. A duration is capped at 24 hours | What else is read: | Attribute | Used for | | --- | --- | | `gen_ai.agent.id` | When it differs from the conversation ID, the span belongs to a **subagent run** `.` under the conversation's run: the same ID the traffic gives a subagent whose client names its agents | | `gen_ai.agent.name` (on the span, or on the resource; `service.name` otherwise) | The agent's name, written as lowercase letters, digits, dots, underscores and dashes. On a subagent's span it is the subagent's type | | `gen_ai.request.model`, else `gen_ai.response.model` | The model of a `chat` span. It must be an identifier (letters, digits and `_ - . : / @`, at most 256 bytes); any other value leaves the model empty | | `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.usage.cache_read.input_tokens`, `gen_ai.usage.cache_creation.input_tokens` | The token counts of a `chat` span | | `gen_ai.tool.name`, `gen_ai.tool.call.id` | The tool of an `execute_tool` span, under the same rules as a [tool step](#tool-steps) | | `status.code` | `2` marks the span failed | String attributes longer than 256 bytes are ignored. The stored spans have kind `app` and the sub-kinds `transcript_turn`, `transcript_call`, `transcript_tool` and `transcript_compaction`. ### What is discarded, and why uploads are safe to repeat This endpoint is a write a client controls, so it trusts nothing in the upload: - **Identity is the key's.** Team, organization, key and principal come from the authenticated key. An upload cannot place a span in another team. - **All content is discarded unread:** `gen_ai.input.messages`, `gen_ai.output.messages`, `gen_ai.system_instructions`, `gen_ai.tool.call.arguments`, `gen_ai.tool.call.result`, `gen_ai.prompt` and `gen_ai.completion`. A span that carried any is marked `content: discarded`. Every attribute not listed above is ignored. - **Span names are not copied.** The stored name is rebuilt from the operation (`chat `, `transcript tool`, `invoke_agent `, `compaction`). The name of a tool is structure: it is kept in the span's attributes `tool` and `call_id`, withheld from readers without `content_structure:read`, never in the span's name. - **Stored IDs are keyed digests.** The stored trace and span IDs are digests of the uploaded ones within the team and organization. An upload can neither name nor overwrite a span the gateway stored, and the same IDs uploaded by another team are that team's own, separate spans. A parent span is kept only when the same upload carries it. - **A repeated upload writes each span once.** A plugin usually sends the whole session again after every turn; only the spans not stored yet are written, and only they are counted. - **A transcript does not double-count.** For a run the gateway also saw in traffic, the run's counters stay those of the traffic: the model calls a transcript names are the requests the gateway already served. A run only the transcript knows (basis `transcript`) takes its counters from the transcript. Uploaded steps appear in the thread with basis `uploaded`. They are not checked against the traffic. ### Limits of one upload | Limit | Value | Answer when exceeded | | --- | --- | --- | | Body size, before and after decompression | `agent_recognition.transcript_ingest.max_request_bytes` (default 4 MiB) | `413 request_too_large` | | Spans | `agent_recognition.transcript_ingest.max_spans` (default 1000) | `413 too_many_spans` | | Traces | 16 | `400 invalid_request` | | Spans of one trace | `spans.max_spans_per_trace` | the surplus is counted in `rejectedSpans`, and that upload adds nothing to the run's counters (the gateway cannot tell which spans were left out) | | Spans a trace already holds | 2,000, the most one trace read returns | `413 trace_too_large`: the trace takes no more. Start a new session, or upload less | Other answers, in the order they are checked: `401` without a valid key; `403 scope_forbidden` without `traces:write`; `404 feature_disabled` while a required flag is off; `403 team_required` for a key without a team; `429 rate_limit_exceeded` past a requests-per-minute policy. **The key is checked before the flags**: a caller without a key, or with a key that lacks the scope, gets the same `401` or `403` whether the ingest is on or off, and only a key that holds `traces:write` is told that it is off. Also `503 rate_limit_unavailable` when the rate counters cannot be read, and `503 storage_unavailable` when the spans could not be stored (nothing of the upload was kept; send it again). ## Troubleshooting | Symptom | Check | | --- | --- | | **A run is not recognized** | Is `enabled` true in the effective settings? Is the request made with a key, on a Chat Completions, Messages, Responses or generateContent route? Does a rule match what the client sends: compare the request's User-Agent and headers with the rule (the client may have changed them in a new version, or a proxy in front of the gateway may strip them). A key without a team is labelled but not listed | | **One run is listed as several** | For a derived run: `digest_key: process` (configure a provider encryption key or a session key), a client that changes its system prompt or first message mid-run, or a compaction (the continued run is named only with one candidate). For any run: the session crossed two keys of different teams | | **Two runs are listed as one** | A derived run: both began with the same first message under the same key and system prompt, and either ran at the same time or the database did not answer the generation read ([two runs that begin identically](#two-runs-that-begin-identically)). Have the client send a run ID (a rule with `run_headers`), or declare `X-Gateway-Session-Id` | | **A run ID ends in `-g2`, `-g3`, …** | A derived run that began like an earlier one of the same key: each is a run of its own ([two runs that begin identically](#two-runs-that-begin-identically)) | | **The task is not captured** (`task.state` is `hash_only`) | `task_capture_state` in the settings; then the team's content capture policy: it must exist, not be disabled, keep requests, and cover the run's first call (its key, model and operation, when the policy lists them). A policy with a `sample_rate` below 1 keeps the task of that share of the runs. Only the call that begins a run can keep the text, so runs recorded before task capture was on keep the hash. A text that expired or was erased also reads `hash_only` | | **The task is withheld** (`task.state` is `withheld`) | You need `content_sent:read` of the run's team. With `content_capture` turned off, kept text is withheld from everyone | | **Tool names are hidden** | You need `content_structure:read` of the run's team, in the thread and in the trace view alike. A name that is not an identifier is never recorded. A tool step's span is named `client tool` (or `transcript tool`) for every reader: search by the sub-kind, not by the tool's name | | **A run counts fewer turns or tool steps than the client made** | A request answered with status 400 or above adds an error only. A tool whose result never came back in a later request is not seen. More than `max_tool_steps` new steps in one request are counted but not drawn | | **`POST /v1/traces` answers 429** | The upload is past a requests-per-minute policy of its key, team, organization or end user, shared with the key's model calls. Wait for `Retry-After`, or raise the policy | | **`POST /v1/traces` answers `413 trace_too_large`** | The session's trace already holds 2,000 spans. Start a new session; the spans stored so far stay | | **A run has no steps** | The span store did not keep them: `span_store` was off, `spans.sample_rate` sampled the requests out, or they are older than `spans.retention_days`. The run's counters still come from the registry | | **A subagent is listed as a run of its own** | The client names no parent and inference did not apply: another key, a start later than the parent's report (an asynchronous spawn), or outside `link_window_minutes` | | **`POST /v1/traces` answers 404** | `agent_transcript_ingest`, `agent_recognition`, `agent_sessions`, `session_tracking` and `span_store` must all be on. Only a key that holds `traces:write` gets this answer | | **Every uploaded span is rejected** | Each span needs `gen_ai.conversation.id` and one of the four operations; IDs must be hexadecimal; times must be inside the span retention | ## Limits - **Recognition reads what the client sends.** Headers and fixed texts are the client's to change; a rule is verified for the version it names. - **Labels, not proof.** A run ID and an agent name are asserted by the caller. They never authenticate, authorize or bill; quotas and budgets ignore them. - **Tool steps are reported, never observed**, and only for tools whose result came back in a later request through this gateway. - **Derived runs can merge or split**, as described under [a derived run ID](#a-derived-run-id). Two runs that begin identically are told apart by the request that begins each; two such runs of one key going on at the same time, and a first message sent again unchanged after its answer, cannot be ([two runs that begin identically](#two-runs-that-begin-identically)). - **Inferred links need the same key and a synchronous spawn.** - **A tool step is counted once, by its call ID**, among the latest 256 the run counted. A request answered with status 400 or above adds an error and no turn or tool step. A result without a usable call ID counts only when it follows the model's last message. - **The task is fixed when the run is first recorded.** A run first seen through a compaction or a helper call gets its task hash from the first later call that shows one. The task text is kept only from the call that begins the run. - **A deletion of captured content narrowed to one request does not remove task text.** The team-wide deletion and an end-user deletion do ([task capture](#task-capture)). - **The run write happens after the answer**, off the request path, bounded to 1.5 seconds. A failed write is logged (`agent_run_record_failed`) and loses that request's contribution to the run's counters; the request and its span are not affected. The one read a derived run adds to the request path is described under [two runs that begin identically](#two-runs-that-begin-identically). - **A thread reads at most** the latest 1,000 spans of a run and the steps of the run plus its first 19 branches; open a branch to read its own. - **No migration of old traffic.** Requests served before the flag was on are not grouped into runs. ## Upgrade Migration 220 creates `gateway_agent_runs`. Both flags are off by default, and with them off nothing changes: no request is read, the run list, the thread and `POST /v1/traces` answer `404 feature_disabled`, and the `traces:write` scope does nothing. Turning `agent_recognition` off again stops recognition at the next request; the stored runs are kept until their retention. ## See also - [Observability](/docs/features/observability/): sessions, the agent session graph and the exported GenAI attributes - [Traces and the span store](/docs/features/traces/) and the [trace explorer](/docs/features/trace-explorer/) - [Content capture](/docs/features/content-capture/): the policy, the content key and who reads content - [Keys, teams and roles](/docs/features/access-control/): key scopes and the built-in roles # Request audit events **Last updated:** 2026-11-27T08:59:34-03:00 (UTC-3) An audit or billing pipeline needs one record per request, with a shape that does not change between releases: which key called which model, which provider answered, what it cost, how it ended. The `request` log line is meant for people searching logs: it carries few fields, and its shape follows the log. The usage history lives in PostgreSQL, behind the console and the admin API. Neither is a stable stream a collector such as [Vector](https://vector.dev/) can forward as is. With `logging.request_events: stdout` the gateway writes, for every finished inference request, one JSON line `{"event":"gateway.request","schema_version":1,...}` to its standard output, next to the normal log. The line holds **metadata only**: identifiers, timings, routing, token counts, cost and policy outcomes. It never contains a prompt, an answer, a provider's error message, a request header or a credential. ## How to enable it ```yaml logging: level: info request_events: stdout # default: off ``` | Field | Values | Default | Applied | | --- | --- | --- | --- | | `logging.request_events` | `off`, `stdout` | `off` | At startup; restart or roll out to change it | There is no environment override and no console editor. It is read once at startup because the writer and its queue are built then, and because a pipeline that depends on the stream must not lose it to a runtime edit. Any other value (including `true`, `false`, `Stdout` or `stderr`) stops the boot with `logging.request_events must be off or stdout`. **Settings & sources → Infrastructure → Request audit events** shows the destination, its source (Default or YAML) and whether this process has the writer. The same data is `infrastructure.logging.request_events` in `GET /api/v1/admin/config`: ```json "request_events": {"destination": "stdout", "source": "yaml", "default": "off", "restart_required": true, "active": true, "schema_version": 1, "queue_capacity": 4096} ``` `active` is whether this process attached the writer at startup. Neither field proves that a collector receives the lines; watch the metrics [below](#loss-and-back-pressure) for that. At startup, the gateway also logs `request_events_enabled` with `destination`, `source` and `schema_version`. ## Which requests produce an event Every request that reaches the usage registry: an authenticated call whose key is allowed on the route, on any inference operation (Chat Completions, Messages, Responses, GenerateContent, embeddings, moderations, rerank, images, audio, video, OCR, decisions, Realtime sessions, token counting, containers, vector stores, MCP tool calls and listings, and the other routes that record usage). Each produces exactly one line when it finishes, whatever the outcome: success, provider error, gateway refusal, guardrail block, rate limit, timeout or client disconnect. These produce none, because they end before the request has a key and an operation: requests without a valid key (401), a key lookup or a team policy or organization that cannot be read (503), an invalid `X-Gateway-End-User` or `X-Gateway-Session-Id` header (400), a key without the route's scope (403 `scope_forbidden`) or a feature its plan does not include; and health checks, `/metrics`, `/v1/models`, the console and the admin API. The `request` log line still records them. Requests the gateway makes to itself on behalf of a client (batch items, eval runs, the embedding of an auto-routed request, a moderation guardrail, the embeddings and OCR of vector store files) produce their own event with `"internal": true` and the derived request ID, such as `.route` or `.e0`. ## Schema version 1 Every member is always present. `null` means unknown or not applicable, never zero: a provider that does not report reasoning tokens gives `"reasoning": null`, and a request whose cost cannot be valued gives `"amount": null`, not `"0"`. | Member | Type | Meaning | | --- | --- | --- | | `event` | string | Always `gateway.request`. Use it to tell events from log records. | | `schema_version` | integer | `1`. A change that removes or renames a member, or changes its type or meaning, increases it. New members can be added within a version. | | `request_id` | string | The request ID (`X-Request-Id`, also `correlation_id` in logs). | | `trace_id`, `span_id` | string | The W3C trace and the request's server span, as in the logs and traces. | | `started_at`, `ended_at` | string | RFC 3339 in UTC, nanosecond precision. `ended_at` is when the answer was complete and its quota settled, before the usage record is written. | | `duration_ms` | integer | Same value as the usage record and the console's Request logs. | | `ttfb_ms` | integer or null | Time to the first body byte the gateway wrote (time to first token for streams); null when nothing was written. | | `method`, `route` | string | HTTP method and route pattern, such as `POST /v1/chat/completions`. | | `operation` | string | The route's operation: `chat`, `messages`, `responses`, `generate_content`, `embeddings`, `moderations`, `rerank`, `images`, `audio_speech`, `audio_transcriptions`, `video`, `ocr`, `realtime`, `mcp_tools_call`, `mcp_tools_list` and so on. | | `internal` | boolean | `true` for a call the gateway made to itself on behalf of a client. | | `requested_model` | string or null | The model name the client sent. Differs from `model` only when the client used a [model alias](/docs/features/model-aliases/). Null when the request was refused before its model was resolved. | | `model` | string or null | The canonical model that served the request. | | `auto_route` | string or null | The [auto-routing](/docs/features/auto-routing/) alias the client called, when one chose `model`. | | `auto_route_choice` | string or null | What that router served: a tier (`simple`, `medium`, `complex`, `reasoning`), a route name, or `default`. | | `auto_route_reason` | string or null | Why: for the trajectory strategy `signals`, `override`, `hold`, `judge`, `default`, `repeat` or `tier_not_permitted`; the other strategies report their own reasons (`matched`, `complexity`, `classifier` and so on). | | `auto_route_transition` | string or null | Trajectory strategy with a session: what the request did to the provider's prompt cache, `first`, `kept`, `switched` or `back`. | | `provider` | string or null | The provider connection ID recorded for the request, as in the usage history: on the routed operations, the target whose answer (success or error) reached the client; on single-connection operations (Realtime, video, token counting, containers, conversations, fine-tuning), the connection chosen before the send. Null when the routed request ended without passing on an answer (refused before dispatch, or the last target failed in transport). | | `provider_model` | string or null | The upstream model of that target, as configured (`targets[].model`). Null without a send to `provider`, such as a cache hit. | | `wire_api` | string or null | The OpenAI API `provider_model` was called with: `chat_completions` or `responses`. With [`api: auto`](/docs/features/protocol-translation/#api-auto-the-api-chosen-per-request) it says which one this request used. Set on Chat Completions, Responses, Messages and GenerateContent requests served by an `openai` target; null when `provider_model` is null, for a target of another protocol, and for the other operations (embeddings, images, audio, ...). Added within schema version 1. | | `attempts` | integer or null | Sends to providers, retries and fallbacks included. Null when nothing was sent: a cache hit, a refusal before dispatch, or an operation that does not count sends. | | `retries` | integer or null | Sends repeated on the same target ([inference retries](/docs/features/inference-retries/)). | | `fallbacks` | integer or null | Times the request moved to another target. | | `status` | integer | The HTTP status the client received; `499` when the client left. | | `result` | string | `success`, `client_error`, `rate_limited` (429), `blocked` (a guardrail refused the request or the answer), `timeout` (a deadline ended it: `timeout_kind` is set or the status is 504), `client_closed` (499, or a started answer the client stopped reading) or `server_error` (5xx, or a started answer the provider cut or the gateway aborted). | | `error_code` | string or null | The gateway's own error code when the gateway produced the error (`guardrail_blocked`, `model_forbidden`, `rate_limited`, `circuit_open`, ...). For an answer that had already started and was cut (`truncated` is `true`, `status` is the one the client received): `stream_interrupted` when the provider cut it and `stream_aborted` when the gateway ended it (`result: server_error`), `client_closed_stream` when the client stopped reading (`result: client_closed`). Null on success and when the error body came from the provider: the provider's message can quote the request, so it is never copied. | | `timeout_kind` | string or null | `first_byte`, `idle`, `max_duration`, `client_stall`, `request` or `attempt` ([timeout controls](/docs/features/stream-timeouts/)). | | `stream` | boolean | Whether the client asked for a streamed answer. | | `truncated` | boolean | `true` when an answer had already started (the status was sent) and ended without its end: a stream the provider cut, a client that stopped reading, an administrative stop or an aborted connection. `status` then stays the one the client received, usually `200`, and `result` is not `success`. | | `cache.hit` | boolean | Whether a gateway cache served the answer. | | `cache.kind` | string or null | `exact` or `semantic` ([exact cache](/docs/features/exact-cache/), [semantic cache](/docs/features/semantic-cache/)). | | `tokens.input`, `tokens.output` | integer or null | Tokens the provider reported. | | `tokens.cache_read` | integer or null | Prompt-cache reads the provider reported (OpenAI `cached_tokens`, Anthropic `cache_read_input_tokens`, Gemini `cachedContentTokenCount`). | | `tokens.cache_write` | integer or null | Prompt-cache writes: Anthropic `cache_creation_input_tokens`, the `prompt_tokens_details.cache_creation_tokens` of a translated Claude answer (Anthropic or Bedrock), or an OpenAI-compatible `cache_write_tokens`. | | `tokens.reasoning` | integer or null | Reasoning tokens (OpenAI `reasoning_tokens`, Gemini `thoughtsTokenCount`, the `output_tokens_details.thinking_tokens` of an Anthropic Messages answer), included in `output` by those providers. | | `cost.state` | string | `known`, `partial` or `unknown`, as in [usage valuation](/docs/features/usage-valuation/). | | `cost.amount` | string or null | Exact decimal amount when the state is `known`. A string, so no float rounding. | | `cost.currency` | string or null | `USD` when there is an amount. | | `cost.reason` | string or null | Why the cost is what it is: `text_token_estimate` for a known cost, otherwise the reason it is unknown (`valuation_disabled` without `usage_valuation`, `rate_unavailable`, `multiple_upstream_attempts`, `non_success_response`, ...). | | `key_id` | string | The key's ID, never its value. | | `principal` | string or null | The key's principal. | | `team` | string or null | The key's team. | | `organization` | string or null | The team's [organization](/docs/features/organizations/), when `organizations` is on and the PostgreSQL store read its ceiling for this request. | | `owner` | object or null | `{"kind", "id"}` of the key's [owner](/docs/features/identity-ownership/), under `identity_ownership`. | | `end_user` | string or null | The end user the client declared (`X-Gateway-End-User` or the body's `user`), under `end_user_tracking`. Caller-declared, not authenticated. | | `session_id` | string or null | `X-Gateway-Session-Id`, under `session_tracking`. | | `tags` | object | The request's [usage tags](/docs/features/usage-tags/); `{}` when none. At most eight pairs, the usage tag limit. | | `guardrails` | array | One entry per guardrail that ran: `{"id", "stage", "outcome", "findings"}`. `stage` is `input` or `output`; `outcome` is `passed`, `masked`, `blocked`, `incomplete` (another guardrail blocked the request first, so this one may not have seen all of the text), `unavailable` (a required check could not run) or `error_allowed` (it failed and its failure mode lets the request through); a `mode: monitor` guardrail (T128) also records `would_block` or `would_mask` (it found something and changed nothing), and has no entry on a request it did not sample ([monitor mode](/docs/features/guardrails/#monitor-mode-try-a-guardrail-before-enforcing-it)). These two values were added within `schema_version` 1: no existing value changed meaning, so a consumer that counts `blocked` stays right, but one that rejects unknown outcomes must accept them; `findings` is a count. Never the matched text. At most 32 entries. | | `gen_ai` | object | The model call mapped to the [OpenTelemetry GenAI semantic conventions](/docs/features/observability/#genai-semantic-conventions), added within schema version 1 (T052): `operation_name` (`chat`, `embeddings`, `text_completion`, `generate_content`, or the gateway operation where no well-known value applies), `provider_name` (well-known product, such as `openai`, `anthropic`, `aws.bedrock`, `gcp.gemini`, `gcp.vertex_ai`, `azure.ai.openai`), `request_model` (the upstream model of the latest send), `response_model` and `response_id` (only what the provider reported in an answer the gateway did not translate or serve from its cache), `finish_reasons` (array, at most 16, in the provider's order; translated answers carry the canonical reason; `[]` when none was seen; streamed answers need `stream_usage`), `server_address`/`server_port` (host and port of the latest send's connection, never its path or query), `error_type` (the HTTP status the client received as a string when it is 400 or more). Members are null for a request that was not a model call (files, batches, vector stores, containers, conversations, fine-tuning, token counting, stored-response lifecycle calls) or made no send; a cache hit has no `provider_name`, `response_model` or `response_id`. All of `operation_name` through `error_type` are always present. Lines recorded before this release do not have the member. | | `parameters` | object | What the [request parameter policy](/docs/features/request-parameter-policy/) did to the attempt that answered, by name only: `defaulted`, `overridden`, `capped`, `dropped`, `unsupported_dropped` and `not_applicable` (arrays, empty when nothing applied). Only plain field names (letters, digits, `_ . : -`, up to 64 characters) are listed, at most 32 per list. `unsupported_dropped` comes from the client's own body members, so it lists only known Chat Completions members (`logprobs`, `n`, `service_tier`, ...). `omitted` counts every name left out. | ### Examples A streamed chat through a model alias, measured against a real provider (one line, wrapped here): ```json {"event":"gateway.request","schema_version":1,"request_id":"t108-real-stream","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","span_id":"c8460d20618f472f", "started_at":"2026-11-08T08:17:14.402003Z","ended_at":"2026-11-08T08:17:15.767287Z","duration_ms":1365,"ttfb_ms":1330, "method":"POST","route":"POST /v1/chat/completions","operation":"chat","internal":false, "requested_model":"t108-legacy","model":"t108-chat","auto_route":null,"auto_route_choice":null,"auto_route_reason":null,"auto_route_transition":null,"provider":"openai-real","provider_model":"gpt-4o-mini", "attempts":1,"retries":0,"fallbacks":0,"status":200,"result":"success","error_code":null,"timeout_kind":null,"stream":true,"truncated":false, "cache":{"hit":false,"kind":null},"tokens":{"input":23,"output":2,"cache_read":0,"cache_write":null,"reasoning":0}, "cost":{"amount":"0.000004650000000000000000","currency":"USD","state":"known","reason":"text_token_estimate"}, "key_id":"t108-app","principal":"t108-service","team":"t108-team","organization":"t108-org","owner":null, "end_user":"end-user-t108","session_id":"session-t108","tags":{}, "guardrails":[{"id":"t108-secrets","stage":"input","outcome":"passed","findings":0}], "parameters":{"defaulted":[],"overridden":[],"capped":[],"dropped":[],"unsupported_dropped":[],"not_applicable":[],"omitted":0}} ``` A chat request with `reasoning_effort: max` on an [`api: auto`](/docs/features/protocol-translation/#api-auto-the-api-chosen-per-request) target, which the gateway sent to the Responses API, measured against a real provider (abridged): ```json {"event":"gateway.request","schema_version":1,"request_id":"93e80c107d93260a7a81a2d7b0b1a760","route":"POST /v1/chat/completions","operation":"chat", "model":"chat-default","provider":"openai","provider_model":"gpt-6-luna","wire_api":"responses","attempts":1,"status":200,"result":"success", "stream":false,"tokens":{"input":12,"output":5,"cache_read":null,"cache_write":null,"reasoning":null}} ``` A request an input guardrail blocked before any provider call (members that stay at their defaults are left out here; the real line has all of them): ```json {"event":"gateway.request","schema_version":1,"request_id":"t108-real-blocked","status":400,"result":"blocked","error_code":"guardrail_blocked", "model":"t108-chat","provider":null,"attempts":null,"tokens":{"input":null,"output":null,"cache_read":null,"cache_write":null,"reasoning":null}, "cost":{"amount":null,"currency":null,"state":"unknown","reason":"attempt_unobserved"}, "guardrails":[{"id":"t108-secrets","stage":"input","outcome":"blocked","findings":1}]} ``` The `gen_ai` member of a non-streamed chat answer whose provider asked for a tool, measured with the built gateway and a mock OpenAI-compatible provider (abridged): ```json {"event":"gateway.request","schema_version":1,"operation":"chat","model":"agent","provider":"mock","provider_model":"mock-model", "gen_ai":{"operation_name":"chat","provider_name":"openai","request_model":"mock-model","response_model":"mock-model-2026-01-01", "response_id":"chatcmpl-mock1","finish_reasons":["tool_calls"],"server_address":"127.0.0.1","server_port":18452,"error_type":null}} ``` A fallback: the first target refused the connection, the second answered. Two sends, so the valuation is unknown by design: ```json {"event":"gateway.request","schema_version":1,"request_id":"t108-real-fallback","status":200,"result":"success", "model":"t108-fallback","provider":"mock-local","provider_model":"mock-model","attempts":2,"retries":0,"fallbacks":1, "cost":{"amount":null,"currency":null,"state":"unknown","reason":"multiple_upstream_attempts"}} ``` ## Reading the stream with Vector The events and the log share stdout, so a collector reads one stream and splits it by the `event` member. Log records never have one (they use `msg`), and every event line starts with `{"event":"gateway.request"`. Each event is written as one whole line: the log and the events go through one serialized writer, so their lines never interleave. Measured with Vector 0.61.0 reading the gateway's stdout through a pipe (`gateway | vector --config vector.yaml`): ```yaml # vector.yaml sources: gateway_stdout: type: stdin # or docker_logs / kubernetes_logs for a container transforms: parsed: type: remap inputs: [gateway_stdout] source: | parsed, err = parse_json(.message) if err != null || !is_object(parsed) { abort } . = parsed split: type: route inputs: [parsed] route: audit: '.event == "gateway.request"' sinks: audit_file: type: file # an S3, HTTP or database sink works the same way inputs: [split.audit] path: /var/lib/vector/gateway-requests.jsonl encoding: {codec: json} logs_file: type: file inputs: [split._unmatched] path: /var/lib/vector/gateway-logs.jsonl encoding: {codec: json} ``` In Kubernetes, the `kubernetes_logs` source gives each container line in `.message` as well, so the same `remap` and `route` apply. Order events by `ended_at`, not by arrival: a request that writes its usage record takes longer to finish, so a later short request can be written first. ## Loss and back-pressure The request never waits for its event. The handler copies the metadata into a value and offers it to a bounded in-memory queue of 4,096 events without blocking; one goroutine values, encodes and writes them. When stdout cannot keep up (a stalled collector, a full pipe), the queue fills and new events are **dropped, not delayed**: - `gateway_request_events_dropped_total{reason="queue_full"}` counts events dropped because the queue was full or already closed; - `gateway_request_events_dropped_total{reason="write_error"}` counts events that could not be encoded or written; - `gateway_request_events_written_total` counts events written; - a `request_events_dropped` warning with the totals and `since_last_warning` is logged at most once every 30 seconds, never per event. Alert on the rate of the dropped counter. On shutdown the gateway stops taking new events after the HTTP server drains and writes what the queue still holds, for up to 5 seconds; what is still queued then is counted as dropped. The stream is best effort and at most once: there is no disk buffer, no retry and no acknowledgement. The usage history in PostgreSQL (`usage_analytics`) and [durable receipts](/docs/features/durable-usage/) remain the records to reconcile against: the same `request_id` identifies a request in both. The events roughly double what the gateway writes to stdout, and they share it with the log. The normal log writes synchronously on the request path (`upstream_attempt`, `request` and the others), so a collector that reads stdout slowly already slows requests; with events on, a log record can also wait for an event line being written at that moment. Size the collector for both, and keep stdout on a local pipe or the container runtime's log driver rather than a slow network sink. ## What the event never contains - No prompt, input, instruction, answer, tool call, file, image, audio or embedding. - No provider error message or body, no request or response header, no URL query. - No key value, token, cookie or provider credential: only `key_id`. - No client-chosen field name except plain parameter names, filtered as described for `parameters`. `end_user`, `session_id` and `tags` are values the client or the key declares; treat them like the usage history they also appear in ([data inventory](/docs/security/data-inventory/)). ## Limits - `organization` needs the PostgreSQL store; another identity adapter leaves it null. - A Chat Completions stream reports tokens only when its usage was asked for: by the client (`stream_options.include_usage`) or by an alias with [`stream_usage: inject`](/docs/features/stream-usage/#ask-for-the-usage-on-the-clients-behalf). Otherwise `tokens` and `cost` stay null for that stream. - `tokens.reasoning` and `tokens.cache_write` are known only where the provider reports them in the forwarded usage object; a translated provider whose adapter folds them into other counters leaves them null. - `attempts`, `retries` and `fallbacks` count sends on Chat Completions, Messages, Responses, GenerateContent and the other operations that go through target selection; Realtime, containers, token counting and fine-tuning leave them null. - `cost` is the same valuation as the usage ledger: it needs `usage_valuation` and a rate ([automatic pricing](/docs/features/automatic-pricing/) or the [price book](/docs/features/pricing/)). It is an advisory estimate, not a charge. ## Upgrade notes The setting is new and off by default: nothing changes until `logging.request_events: stdout` is set. Before rolling back to an older binary, remove `request_events` from the YAML, because its strict schema refuses the unknown field. A collector that parsed every stdout line as a log record must start filtering on `event` before the setting is turned on. `wire_api` was added within schema version 1 (T112), as the version rule allows: a collector that maps the event onto a fixed table must accept the new member or ignore unknown ones. No member changed type or meaning. ## See also - [Logs, traces and metrics](/docs/features/observability/): the `request` line, OTLP export and metrics. - [Log destinations](/docs/features/observability/#log-destinations): batched delivery of usage records to object storage and HTTP endpoints. - [Usage valuation](/docs/features/usage-valuation/) and [durable receipts](/docs/features/durable-usage/). # Response headers for clients **Last updated:** 2026-11-22T06:50:00-03:00 (UTC-3) Every inference answer carries `X-Request-Id`, `traceparent` and `X-Gateway-Provider`, and a provider's `Retry-After` on 429 and 503. An application that paces itself, or reports what a call cost, can also receive the provider's rate-limit budget, the target that answered, the number of provider sends and the cost. Each of these is opt-in under `server.response_headers`, because each tells the client something about the operator rather than about its own request. ## How to enable it ```yaml server: response_headers: provider_rate_limits: true # relay the provider's x-ratelimit-* budget attempts: true # X-Gateway-Attempts served_target: true # X-Gateway-Served-Model cost: true # X-Gateway-Cost-USD, when known stream_cost: true # also gateway_cost_usd in a stream's final usage event ``` | Parameter | Default | What the client receives | Why it is off by default | | --- | --- | --- | --- | | `server.response_headers.provider_rate_limits` | `false` | The provider's `x-ratelimit-limit-requests`, `x-ratelimit-limit-tokens`, `x-ratelimit-remaining-requests`, `x-ratelimit-remaining-tokens`, `x-ratelimit-reset-requests` and `x-ratelimit-reset-tokens`, as the provider sent them on the answer being relayed | They describe the operator's provider account, which every key and team on that connection shares: one tenant would see the others' consumption | | `server.response_headers.attempts` | `false` | `X-Gateway-Attempts`: how many provider sends the answer took, retries and fallbacks included | It reveals retries and fallbacks | | `server.response_headers.served_target` | `false` | `X-Gateway-Served-Model`: the model of the alias target that answered, such as `gpt-4o-mini` | It reveals how an alias is routed | | `server.response_headers.cost` | `false` | `X-Gateway-Cost-USD`: the valued cost of the request in USD, such as `0.000017` | It reveals the operator's prices | | `server.response_headers.stream_cost` | `false` | The same cost as `gateway_cost_usd` on a stream's final usage event ([in-band cost](#in-band-cost-on-streams)); requires `cost` | Same as `cost` | The block is read at startup; restart each replica to change it. **Settings & sources → Infrastructure → Inference HTTP** lists the parts that are on (`infrastructure.inference_http.response_headers`). It applies to the inference API (`/v1/*` and the native Gemini `/v1beta/*`), never to the console or the admin API. ## What each header contains, and when it is absent **Provider rate limits.** Only the six names above are relayed; other provider headers (organization, project, processing time and so on) never are. A value is relayed only when the provider sent it once and it looks like a budget (a number, a duration such as `6m0s`, or a timestamp). They come from the provider response the gateway relays, so after a fallback they describe the target that answered. Providers that use other names, such as Anthropic's `anthropic-ratelimit-*`, are not relayed. **Attempts.** The number of provider sends for this request, counted as in the [request events](/docs/features/request-events/); after a [semantic fallback](/docs/features/routing-strategies/#semantic-fallbacks) it adds the refused first send to the fallback's own. It is absent when no provider was called (a cache hit, or a refusal before dispatch). **Served model.** The `model` of the target that answered, from the alias configuration. It is sent only when it is a plain model name: a path or an ARN (for example a Bedrock inference profile, which contains the AWS account number) is not sent. The header never carries a provider credential or internal identifier. **Cost.** The same exact decimal the request log and request events value, without trailing zeros. It needs `usage_valuation` and a price for the model that answered, and for streams the `stream_usage` flag, which meters them. It is never estimated: when the cost is unknown (no price, no reported usage, an error answer, several provider sends, an indeterminate durable outcome) the header is absent, never `0`. A buffered answer that the gateway holds until the request is recorded (with budgets, TPM or usage analytics on) gets the cost as an ordinary header. A stream, or an answer already on its way, is sent before its cost is known, so the cost follows it as an HTTP trailer: the response announces `Trailer: X-Gateway-Cost-USD` and the value arrives after the body, or not at all when unknown. ```http HTTP/1.1 200 OK Content-Type: text/event-stream X-Gateway-Attempts: 1 X-Gateway-Served-Model: gpt-4o-mini X-Ratelimit-Remaining-Requests: 9999 Trailer: X-Gateway-Cost-USD data: ... X-Gateway-Cost-USD: 0.0000027 ``` Trailers arrive after the body; many HTTP clients do not expose them (Go's `net/http` does, in `Response.Trailer` once the body is read; a browser's `fetch` does not), and some proxies drop them. Turn on the [in-band cost](#in-band-cost-on-streams), or read it from the [request events](/docs/features/request-events/) or usage analytics instead. ### In-band cost on streams `server.response_headers.stream_cost: true` (default `false`; requires `cost: true`) also writes the cost on the stream itself, for clients that cannot read trailers, such as a browser's `fetch`. The stream's final usage event gains one top-level member, a decimal string: ```text data: {"id":"chatcmpl-1","object":"chat.completion.chunk","choices":[],"usage":{"prompt_tokens":9,"completion_tokens":4,"total_tokens":13},"gateway_cost_usd":"0.000017"} data: [DONE] ``` | API | Final usage event | | --- | --- | | Chat Completions | The last chunk that carries `usage`: the usage-only chunk (the client asks for it with `stream_options.include_usage: true`), or the finishing chunk of a provider that puts usage there | | Responses | `response.completed` or `response.incomplete` | | Messages | The `message_delta` that carries `usage` | - The value is the trailer's, from the same valuation, and the unknown rule is the same: when the cost is not known the member is absent, never `0`. The trailer is still sent. - Responses that may carry it say so with `X-Gateway-Stream-Cost: gateway_cost_usd` (also exposed to browsers under [CORS](/docs/operate/cors/)), sent when `stream_cost` is on and `stream_usage` meters streams. A `gateway_cost_usd` the upstream itself put on the final usage event is removed, so a client that sees the header can trust the member; without the header, ignore any member of that name. - The member is written only once the provider's end has been seen: the provider closed the stream, or it sent its terminal event and the stream then stopped. To do that, the gateway holds the final usage event and the closing events after it (the `[DONE]` line; `ping` and `message_stop`) until then, within 512 KiB. Any other event after it shows it was not the final one: what was held goes at once, unchanged. Past the bound, or when the stream is cut, the held events are released unchanged and without the member. Nothing else in the stream changes, and the framing (line endings, event names) is kept. - If the request is cancelled (the client leaves, a stream deadline, a gateway stop) after the provider's last event but before it closed the stream, the held events cannot be written any more: the request event records the stream as cut by the client instead of delivered. - A usage event whose JSON spans several `data:` lines is relayed unchanged. Gemini `generateContent` streams are not covered. ## Inspect it **Settings & sources → Infrastructure → Inference HTTP** and `GET /api/v1/admin/config` (`infrastructure.inference_http.response_headers`) show which parts are on. ## Upgrade Nothing changes until a part is turned on. Before rolling back to an older binary, remove `server.response_headers` (and `stream_cost` before rolling back below T164.011), because its strict YAML refuses it. ## See also - [Request events](/docs/features/request-events/): the per-request record with tokens, attempts and cost. - [Routing strategies](/docs/features/routing-strategies/): fallbacks and the `X-Gateway-Fallback` header. # Provider request labels **Last updated:** 2026-11-24T13:10:31-03:00 (UTC-3) [Providers](/docs/features/providers/) · [Content capture](/docs/features/content-capture/) · [Observability](/docs/features/observability/) The gateway already says who spent what: the request log, the reports and the budgets are broken down by organization, team and key. The cloud bill is not. Vertex AI charges a project, and its billing export shows one line per model and day, with no idea which of your teams made the calls. With `provider_request_labels` the gateway adds the caller's organization, team and key ID to every generateContent call it sends to a Vertex AI target, as **request labels**. Vertex AI copies request labels to its billing export, so the bill in BigQuery can be grouped by the same hierarchy the gateway uses, and reconciled with the gateway's own numbers. Use it when someone outside the gateway (finance, a FinOps tool) reads the Google Cloud bill and needs it per team. If the gateway's own reports are enough, leave it off: the labels change nothing in routing, budgets or prices. ## Turn it on ```yaml features: provider_request_labels: true # default false (operator control); applies to the next request provider_request_labels: # every field optional; read on each request, no restart organization: organization # label key for the caller's organization ID team: team # label key for the caller's team ID key_id: key_id # label key for the caller's key ID values: policy # policy | hashed ``` The flag can also be switched in **Settings → Features** or with `PUT /api/v1/admin/features/provider_request_labels`. The block is set in the gateway YAML. A chat request from a key of team `support` in organization `acme` then reaches Vertex AI as: ```json { "contents": [{"role": "user", "parts": [{"text": "hello"}]}], "labels": {"organization": "acme", "team": "support", "key_id": "key_7f3a"} } ``` | Setting | Default | Accepted | Meaning | | --- | --- | --- | --- | | `features.provider_request_labels` | `false` | boolean; operator control | Sends the labels. Runtime flag: no restart | | `provider_request_labels.organization` | `organization` | a label key (see below) | The label that carries the caller's organization ID. Left out of a call whose caller has no organization (the `organizations` flag is off, or the team belongs to none) | | `provider_request_labels.team` | `team` | a label key | The label that carries the caller's team ID. Left out for a key without a team | | `provider_request_labels.key_id` | `key_id` | a label key | The label that carries the caller's key ID | | `provider_request_labels.values` | `policy` | `policy`, `hashed` | How the IDs are written: see [Plain or hashed values](#plain-or-hashed-values) | A label key is 1 to 63 characters: a lowercase letter first, then lowercase letters, digits, underscores or dashes. The three keys must differ. The gateway refuses any other value when it loads the configuration, flag on or off, so turning the flag on never sends a label Vertex AI would refuse. Choose keys your billing queries do not already use for something else, for example `gw_team`. ## Which calls carry the labels | Call | Labels | | --- | --- | | Chat Completions, Messages or Responses request served by a Gemini model on a Vertex AI target (the gateway translates it to generateContent) | Added | | Native `generateContent` and `streamGenerateContent` (`POST /v1beta/models/{model}:...`) on a Vertex AI target | Added, merged with the client's own labels | | The same requests on a Gemini API target (`generativelanguage.googleapis.com`) | Not added: that API has no request labels | | Embeddings on Vertex AI (`:predict`) | Not added: Vertex AI reads labels on `:predict` for image generation only | | The OpenAI-compatible Vertex AI endpoint (preset `vertex_openai`), native passthrough aliases, every other provider | Not added | A Vertex AI target is a provider with `protocol: gemini` and a Vertex AI base URL ([Gemini and Vertex AI](/docs/features/providers/#gemini-and-vertex-ai)). With several targets on one alias, each attempt gets what its own target accepts: a fallback from Vertex AI to another provider sends that provider no labels. Requests the gateway makes for a client (a batch line, a context summary, a fallback) run as the client's key and carry its labels. The gateway's own callers are named by their kind in the key label, never by a person or a run: `playground` (the console Playground), `eval` and `evaltest` (evaluation runs and judges), `auto-route-test`, `console-ask-ai` and `console-compliance`. Their team and organization labels are the real ones. ### Labels the client already sent On the native generateContent route a client may send its own `labels`. The gateway keeps them and adds its three: - A client label under one of the gateway's three keys is **removed**, and the gateway's value written when it has one. The attribution on the bill is the gateway's, so a caller cannot charge its usage to another team by sending `"team": "finance"`, also when its own key has no team. - Vertex AI accepts at most 64 labels in one call. When the client's labels plus the gateway's would pass that, the gateway keeps its own and drops the client's surplus, last in alphabetical order of the key first. - A `labels` member that is not a JSON object is replaced by the gateway's labels. A client label whose value is not a string is forwarded as it came, for Vertex AI to judge. The request the client sent is not changed anywhere else: content capture, the token estimate and the valuation all read the client's body. ## Plain or hashed values Team and key IDs are internal names. Sent as they are, they become visible to everyone who can read the Google Cloud billing export, which is often a wider group than the gateway's administrators. Two settings decide whether a call carries the IDs or a digest of them: - **`provider_request_labels.values: policy`** (default). IDs are sent as they are, except for a team whose [content capture policy](/docs/features/content-capture/#policy-fields) says `identifiers: hashed`. That policy field is the per-team switch: use it for the teams whose identifiers must not leave the gateway. - **`provider_request_labels.values: hashed`**. Every team's IDs are sent as digests. ```yaml content_capture: policies: - team: legal disabled: true # captures nothing identifiers: hashed # and its IDs leave the gateway only as digests ``` The `identifiers` field works whenever the team has a policy, also a disabled one and with `content_capture` off: it restricts what is sent and captures nothing. Know these rules before relying on it: - **Where it is edited.** In the YAML always. In the console and the API (`PUT /api/v1/admin/content-capture/policies/{team}`) only while `content_capture` is on, like the rest of the policy; a console policy saved earlier keeps applying with the flag off. - **Console over YAML.** A policy saved in the console replaces the team's YAML entry, identifiers included. Removing the console policy returns the team to its YAML entry. - **A write that leaves the field out keeps the current value.** A script written before the field existed does not un-hash a team; send `"identifiers": "plain"` to go back. - **Timing.** A console change applies at once on the replica that saved it and within 30 seconds on the others. - **Database trouble.** A gateway that has not yet read the console policies since it started sends digests for every team until it has. After that, a failed refresh keeps the last policies it read. A hashed value is 32 lowercase hexadecimal characters: ```json {"labels": {"team": "9c1f0a4e6b7d2c35a8e1f4d07b6c9a12", "key_id": "41be7d9920f3c6a85d0e7b1c2a94f6e3"}} ``` - It is a **keyed** digest (HMAC-SHA-256). Someone who reads the bill cannot test a guessed team name against it. - The same ID always gives the same digest, so the bill still groups correctly. The same name at two levels (a team and a key both called `ops`) gives two different digests. - The key comes from `storage.provider_encryption_key_env`, or from the console session signing key when there is no provider encryption key. Both are the same on every replica and after a restart. **Without either, each process uses a random key and the digests change at every restart**: configure the provider encryption key before relying on hashed labels. The effective source is shown as `digest_key` (below). - Rotating that key changes every digest once. - The gateway has no screen that turns a digest back into an ID. To read a hashed bill per team, join it with the gateway's own usage export on date and model, or keep `values: policy` for the teams whose names may be shown. ### Plain values and the Vertex AI character rule Vertex AI accepts only lowercase letters, digits, underscores and dashes in a label value, up to 63 characters. An ID that already fits is sent unchanged, which is the case for the IDs the gateway generates. Any other is lowercased, its other characters become underscores, and a dash with 8 hexadecimal characters is appended, so two IDs that differ only in case or punctuation never share a value: | ID | Label value | | --- | --- | | `support` | `support` | | `Team.A` | `team_a-` followed by 8 hexadecimal characters | | an ID longer than 63 characters | its first 54 characters, a dash and 8 hexadecimal characters | ## See the effective settings `GET /api/v1/admin/config` returns the block as the gateway applies it, defaults filled in: ```json { "provider_request_labels": { "enabled": true, "organization": "organization", "team": "team", "key_id": "key_id", "values": "policy", "digest_key": "provider_encryption_key", "max_labels": 64, "max_length": 63, "source": "yaml", "restart_required": false } } ``` The console shows the same in one line at the top of **Providers** while the flag is on, and the content capture policy form has the **Identifiers in provider request labels** choice. Going from hashed back to plain asks for a second click, like every change that exposes more. ## Read the labels in the bill Request labels appear in the [Cloud Billing export to BigQuery](https://cloud.google.com/billing/docs/how-to/export-data-bigquery) in the `labels` column of each usage row, and in Vertex AI's request logging. Google documents the feature in [Add labels to API calls](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/add-labels-to-api-calls). A query per team: ```sql SELECT (SELECT value FROM UNNEST(labels) WHERE key = 'team') AS team, SUM(cost) AS cost FROM `my-project.billing.gcp_billing_export_v1_XXXXXX` WHERE service.description = 'Vertex AI' GROUP BY team ORDER BY cost DESC; ``` The export arrives hours after the usage. Calls made before the flag was on have no labels and fall under `NULL`. ## Limits - **Vertex AI generateContent only.** No other provider or Vertex AI method receives labels; the table above lists each case. - **Three labels, these three.** The gateway does not send the principal, the end user, usage tags or request IDs: high-cardinality or client-supplied values do not belong on a bill. - **No cost on the gateway side.** The labels are not stored, not logged and not part of any metric. - **Not a control.** Labels never change routing, quota or price, and Vertex AI does not validate them against anything. # Analytics **Last updated:** 2026-11-25T17:32:18-03:00 (UTC-3) Who consumed what, how much, how it changed and what needs investigating, right in the console, without Grafana. Analytics reads the usage events recorded in PostgreSQL and separates demand, performance, consumers and cost. Flag: `usage_analytics`. ## The screens **Usage** is the console's home page: a summary at the top; the latest requests are in **Logs**. **Analytics** has these tabs (Quality, Tools, Cost estimates and Savings appear with their flags): | Tab | What it shows | | --- | --- | | **Usage** | Requests, reported tokens, average per event, coverage, demand and input/output series, comparison across models, providers and operations | | **Performance** | End-to-end average and p95, error and success rates over time and, with `analytics_status_breakdown`, the distribution by HTTP status | | **Consumers** | Usage by team, principal (the application) and key ID | | **Cost estimates** | Estimated cost by model, team and provider, with coverage; with `cost_request_insights`, the [cost of one request](/docs/features/usage-valuation/#api) (median, p95, p99, largest, mean) and the most expensive requests, each opening its trace; with `customer_portal`, the spend by customer organization; with `pricing_coverage`, the [pricing coverage](/docs/features/usage-valuation/#pricing-coverage) of the calls. Requires [valuation](/docs/features/usage-valuation/) | | **Tools** | With `tool_call_analytics` and the trace explorer: per tool, the calls, failed calls, success and error rate and average latency, and the calls over time ([below](#tool-calls)) | | Flag | What it adds | | --- | --- | | `analytics_comparison` | Comparison with the previous period of the same length | | `analytics_status_breakdown` | Distribution by HTTP status | | `analytics_export` | [CSV export](/docs/features/analytics-export/) | | `analytics_rollups` | Daily aggregates, rebuilt every five minutes for today and yesterday | | `analytics_rollup_reads` | Periods longer than seven days read the closed days from the aggregates (p95 becomes unavailable) | | `stage_denominators` | [Coverage per stage](#coverage-per-stage): how many inference requests reached each stage, refusals before persistence included | | `analytics_saved_views` | [Saved views and dashboards](/docs/features/analytics-saved-views/): your filters, time range and widgets, private or shared read-only with one team | ## How to use it 1. Choose the period (15 min to 90 days, or custom) and the filters: principal, model, team, provider, key and operation. 2. Click **Apply analytics filters**: the draft does not change the query until then. 3. **Inspect requests** opens Request logs with the same filters and times, so you can see the requests behind a number. With the [trace explorer](/docs/features/trace-explorer/) on, **View traces** opens Traces on the same slice and time window, and a row's error count opens its traces in error. The CSV export and the estimates use exactly the same slice. Team roles pick one of their own teams; there is no global view for them. **Teams and organizations.** A request counts for the organization it ran in. `team` selects a team's requests of the organization it is in now, and `organization` selects what was recorded in that organization, by the teams it has now and by teams that have since moved away. So when a team moves, its earlier spend stays in the former organization's totals and never enters the new one's; the readers on each side are listed in [when a team moves](/docs/features/organizations/#when-a-team-moves). The by-team ranking of a view with no team or organization filter (a global administrator's) adds a team up across the organizations it has been in. ## How to read the numbers - **Buckets:** hourly up to 7 days, daily beyond that, in UTC, displayed in the browser's time zone. - **Not measured ≠ zero.** Latency and price that were not measured appear as missing; unknown cost never becomes zero. - **Tokens:** only those reported by the provider. Coverage says how many events had at least one counter. - **Top 20:** each dimension shows the 20 groups with the most events; a notice indicates when there is a cutoff. Search and sorting on screen act only on those 20. - **Narrow screens:** below 600 px each group of the breakdown is a card with every metric labelled; between that and a wide screen the group column stays in place while the metrics scroll sideways, with a hint under the table. - **P95** is calculated from the events; it is not TTFT or the gateway's isolated overhead. - **Principal** is the application that owns the key, not a console person. - **Retention:** if a [retention policy](/docs/features/metadata-retention/) deleted old events, Analytics says so, instead of showing an empty period as "no traffic". The charts have values accessible by pointer and keyboard, and wide tables scroll internally on phones. ## Coverage per stage Analytics reads persisted usage events, so a request refused before its event was written (no credential, a quota refusal, a provider failure before any answer) is not in it. With the operator flag `stage_denominators` (off by default; requires `usage_analytics` and PostgreSQL), the gateway also counts every model call (a `POST` to a `/v1` or `/v1beta` inference route, or the realtime upgrade; not the file, batch, vector store, container, fine-tuning, video job, stored-response lifecycle, conversation, evaluation, passthrough or model-list routes, the console, health or internal calls) at each stage it reaches: | Stage | Counted when | | --- | --- | | `received` | The request reached the gateway | | `authenticated` | Its credential identified a key | | `admitted` | Every admission check passed and a provider send started, or the cache answered | | `responded` | An admitted request answered 2xx | | `persisted` | Its usage event was written | | `valued` | That event carries a priced [valuation](/docs/features/usage-valuation/) | | `reconciled` | Its [budget reservation](/docs/features/budgets-and-tpm/#how-the-reservation-works) settled from a proven measurement | - **Cost on the request path:** one atomic add in memory per stage reached; no database write. Each replica adds its counts to the current minute in PostgreSQL every 15 seconds (`gateway_stage_counts`, migration 181), and once more on shutdown; a failed write keeps the counts for the next flush. A count lands in the minute it was flushed, so the latest minute is still filling. Minutes are kept 90 days. Measured with `gwbench -mock` (same binary, flag off and on, alternating rounds): median p50 2.96 ms off and 2.98 ms on at concurrency 1, 9.26 ms off and 9.17 ms on at concurrency 16 (about 1,700 requests/s both), three rounds each: within noise. - **Where:** the **Usage** page shows **Coverage per stage · last 24 hours** with each stage's count and its share of `received`. `GET /api/v1/admin/analytics/stages?from=&to=` (RFC 3339, whole minutes, at most 31 days; default the last 24 hours) answers the same with `analytics:read`. - **Scope:** the counts are installation-wide, across every replica and team; a team-scoped role cannot read them (`403`), and they carry no team, key or model. - **Accuracy:** a replica that crashes loses at most the counts of its last 15 seconds; turning the flag off stops counting at once. A request still running when a flush happens is counted at its later stages in a later minute. A flush whose write committed but whose answer timed out is added again on the next flush (at least once). `reconciled` is the gateway's settlement decision; a background response (settled later, from its terminal response) is not counted there. - **Upgrade:** migration 181 adds the table. An older binary rejects the flag name in YAML; the table is ignored. ## Any grouping: the structured query The screens show fixed breakdowns. For any other combination (cost per team per model per hour, 429s per key, provider and error code, blocks per guardrail and team), `GET /api/v1/admin/analytics/query` groups the same events (its `organization` dimension and filter are the organization a request ran in) by up to five dimensions and an optional `minute`, `hour`, `day`, `week` or `month` bucket in a time zone, with chosen metrics, exact filters, an order and a row limit, under the same permission, flag and team scope. m7 ai uses it to answer questions in plain language. Parameters, examples and limits: [m7 ai](/docs/features/ask-ai/#the-structured-usage-query). With [`evaluation_metrics`](/docs/features/evaluation-metrics/#evaluation-results-in-the-analytics-query) the same endpoint also answers over evaluation results: metrics such as `pass_rate`, `mean_score`, `feedback_count` and `judge_cost_usd`, dimensions such as `evaluation`, `assessment` and `evaluation_value`, joined with the dimensions of the judged request. The **Quality** tab of this screen is built on it, and the tab and range of the screen are kept in the address (`#/analytics?tab=Quality&range=7d`). ## Tool calls **Usage → Tools** answers "which tools do my agents call, how often do they fail and how long do they take". Turn it on with: ```yaml features: span_store: true trace_explorer: true tool_call_analytics: true ``` `tool_call_analytics` is a tenant read (with plan entitlements, the team's plan must include it), off by default; it needs the trace explorer. The tab reads the tool spans the [span store](/docs/features/traces/) already keeps: an MCP tool the gateway ran for a request (`execute_tool `, with its MCP server, status and duration) and a tool a client reported running (`client tool`: its name is conversation structure and stays in the span's attributes, so these are one row). An MCP listing (`MCP operation`) is a tool span but not a tool call, and is left out. It shows, for the Usage screen's range and team: - **Tiles:** tool calls and how many tools, the average latency of the calls with a duration (a client-reported tool has none), the success rate (calls whose span is not an error) and the failed calls with the error rate. - **Tool performance:** one row per tool and server, most called first: calls (failed in brackets), success rate, error rate and average latency. A tool name opens the Traces screen on that tool's spans of the range. - **Tool usage over time:** calls per hour (ranges up to 48 hours) or per day, the failed part stacked on top; an empty bucket is a gap. The same figures come from `GET /api/v1/admin/traces/tools` with `from`, `to` (RFC 3339, up to 92 days; the last 24 hours by default) and an optional `q` in the [query language](/docs/features/query-language/) (spans scope, for example `team:payments` or `status:error`), with `logs:read`. It answers `totals` (`calls`, `errors`, `success_rate`, `error_rate`, `avg_latency_ms`, `tools`), `tools` (each with `tool`, `name`, `server`, `calls`, `errors`, `success_rate`, `error_rate`, `avg_latency_ms`, `timed_calls`), `series` (the 8 most called tools and `(other tools)` with `folded: true`, each with `points` of `at`, `calls` and `errors` at `step_seconds`), `read_store` (`database` or `analytics_store`) and `truncated` (the range held more than 5,000 tool and step cells: narrow it; the rows and totals are read over the whole range apart from the series, so they stay exact up to 5,000 tools). Rates are fractions rounded to four decimals, latency in milliseconds to one decimal. It reads your teams only, of each what it recorded in its current organization, from the span engine the Traces screen reads. ## Limits - Window of up to 90 days, 5 s per query and top 20 per dimension. - The panels are separate queries: under continuous writes, they may not reflect exactly the same instant. - Events are recorded best effort: failures before authentication and events lost to a database outage do not appear (count them with [coverage per stage](#coverage-per-stage)). For guaranteed recording, see [durable receipts](/docs/features/durable-usage/). - It is not a financial ledger. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `GET /api/v1/admin/analytics/rollups` | Daily usage aggregates, rebuilt every five minutes for today and yesterday (`analytics_rollups`), for `team` or for an organization administrator's `organization`. A rollup row is kept per organization the requests ran in; a day not built yet, or waiting for the one-time rebuild after an upgrade, is listed in `missing_days` | | `POST /api/v1/admin/analytics/rollups/rebuild` | Rebuilds whole UTC days from the stored events, for late events or after a retention deletion. `204`: every day of the range was rebuilt by the call. `202` with `{"queued": true, "from": "…", "to": "…", "days": N}`: `N` days were left to the background rebuild, because a day is too large for one statement and is built in slices, or because the range did not fit the two minutes of the call. Nothing else is needed: each queued day keeps its earlier rollup until its rebuild is done, and `built_at` of the listing moves when it is. `400`: a range that is not 1 to 90 whole days. `503`: the rebuild failed and nothing was queued | ## See also - [Logs, traces and metrics](/docs/features/observability/). - [Valuation](/docs/features/usage-valuation/) and [usage tags](/docs/features/usage-tags/). - [m7 ai](/docs/features/ask-ai/) and the structured usage query. # Analytics store **Last updated:** 2026-11-27T14:42:00-03:00 (UTC-3) PostgreSQL is the gateway's database and stays the source of truth for usage, money, quotas, receipts, identity and configuration. On large deployments, usage analytics over 30 or 90 days and sparse log filters over long windows outgrow it (see the [measured comparison](/docs/benchmarks/analytics-store/): at 10 million events the 30-day Usage view no longer fits its 5-second deadline). The **analytics store** is an optional read store for those reads: the gateway copies the usage events from PostgreSQL into it, and each purpose that reads it is turned on by its own flag. ClickHouse is its only engine today. The parameters are named by their function (`analytics_store`, `analytics_store_usage`), and `engine: clickhouse` selects what serves it, so another engine would change a value, never a name; until 0.0.1-rc.2 the block was `clickhouse:` and the flags `clickhouse_analytics` and `clickhouse_request_logs`, which are now refused naming the new names ([upgrading from 0.0.1-rc.2](/docs/operate/operations/#upgrading-from-001-rc2-infrastructure-names)). ClickHouse is never inside the gateway image and never written by a request: the copy reads committed PostgreSQL rows in the background. Turning it off, or losing it, leaves every write and every PostgreSQL read as they are. | Flag | Default | What it turns on | | --- | --- | --- | | `analytics_store_usage` | `false` | The copy, and usage analytics read from it (requires `usage_analytics`) | | `analytics_store_request_logs` | `false` | The copy, and request log pages read from it (requires `request_logs`) | Both are operator controls under plan entitlements and can be changed at runtime from **Settings → Features**. The copy runs while at least one of them is on and the `analytics_store` block names an endpoint. ## Configure ClickHouse may be self-hosted (the Compose and Helm profiles can run it beside the gateway) or a managed service. The gateway needs the native protocol port and an existing database; it creates its own table, `gateway_usage_events_v1`, at the first copy. ```yaml features: usage_analytics: true analytics_store_usage: true analytics_store: engine: clickhouse addresses: ["clickhouse.internal:9440"] database: gateway username_env: ANALYTICS_STORE_USER password_env: ANALYTICS_STORE_PASSWORD tls: mode: verify_full ``` Every field below sits under `analytics_store` in the gateway YAML (boot configuration: there is no environment variable or console editor for them, and the console and `GET /api/v1/admin/analytics-store` show only the safe view; the **Usage** panel lists the four `copy.*` bounds from it, read-only). | Field | Default | Bounds | Meaning | | --- | --- | --- | --- | | `analytics_store.engine` | none | `clickhouse` | The analytics store engine. Required once `addresses` is set; any other value is refused naming the engines. The fields below are the ones the `clickhouse` engine reads; a future engine would refuse those it does not support (`analytics_store.copy is not supported by the analytics store engine ...`) | | `analytics_store.addresses` | `[]` | one `host:port` | Native protocol endpoint (9000 plain, 9440 TLS). Empty means the analytics store is not configured. One server: the copied table is a local MergeTree, so a replicated cluster is not supported yet | | `analytics_store.database` | `gateway` | 1–63 letters, digits, `_` | Database that holds the copied table; it must exist | | `analytics_store.username_env` | `""` | environment variable name | Variable (or `_FILE` with `secret_files`) holding the user; empty uses `default` | | `analytics_store.password_env` | `""` | environment variable name | Variable (or `_FILE`) holding the password. In both fields the names 0.0.1-rc.2 shipped, `GATEWAY_CLICKHOUSE_USER` and `GATEWAY_CLICKHOUSE_PASSWORD`, are refused at load naming `GATEWAY_ANALYTICS_STORE_USER` and `GATEWAY_ANALYTICS_STORE_PASSWORD` | | `analytics_store.tls.mode` | `verify_full` | `verify_full`, `disable` | `verify_full` checks the server certificate against the system roots or `root_cert_file_env`; `disable` is plain TCP for a private network | | `analytics_store.tls.root_cert_file_env` | `""` | environment variable name | Variable holding the path of a PEM CA bundle (self-signed or private CA) | | `analytics_store.tls.server_name` | `""` | host name | Name checked in the certificate when it differs from the address | | `analytics_store.dial_timeout` | `5s` | 100ms–1m | One connection attempt | | `analytics_store.query_timeout` | `30s` | 100ms–5m | One copy statement | | `analytics_store.max_open_connections` | `8` | 1–128 | Connections of one replica | | `analytics_store.copy.batch_size` | `5000` | 100–100000 | Events one copy pass reads | | `analytics_store.copy.interval` | `2s` | 200ms–5m | Pause between passes once the copy has caught up; a pass that stopped at its batch bound is followed at once | | `analytics_store.copy.gap_grace` | `10m` | 1m–24h | Age past which an open gap is reported as stuck (`oldest_gap_seconds`); a gap never closes by age alone (see below) | | `analytics_store.copy.max_lag` | `5m` | 10s–24h | How far behind PostgreSQL the copy may be for reads to use ClickHouse | The block is read at start-up: restart to apply a change. Configure every replica alike. A replica without the block turns the change log off only after no replica has copied for 10 minutes, and a replica whose block fails to open leaves the copy to the others; a replica that sees both flags off turns it off after one minute without a pass. Each turn-off makes the next enable copy everything again. **Managed ClickHouse (for example ClickHouse Cloud):** use the service's native TLS endpoint (port 9440) with `tls.mode: verify_full`; the public CA is in the system roots. **The ClickHouse user** needs, on its database, `CREATE TABLE`, `SELECT`, `INSERT`, `ALTER DELETE` and `ALTER UPDATE` (lightweight deletes for redactions and retention), `ALTER TTL` (to move the retention of the span copy when `analytics_store.spans_retention_days` changes), `ALTER ADD COLUMN` (to add a column a release adds to an existing span copy table) and `TRUNCATE`; nothing on other databases and no `URL`, `S3`, `FILE`, `REMOTE` or `SYSTEM` grants. ## Run the analytics store beside the gateway Both profiles can run a ClickHouse server next to the gateway, off by default and never inside the gateway image (`clickhouse/clickhouse-server:25.12.11.4`, pinned by digest, about 1 GB). `scripts/bootstrap-local-secrets.py` writes `GATEWAY_ANALYTICS_STORE_PASSWORD` next to the PostgreSQL password. Both use the same server files (`deploy/helm/gateway/files/clickhouse/`): only the native (9000) and HTTP (8123, used by the image's first-start setup and the health checks) listeners, console logs at warning, and one user, `gateway`, limited to the `gateway` database with the grants above; the image's passwordless `default` user is removed. The server runs as the image's non-root user with every capability dropped and a read-only root filesystem, and refuses to start when its password is empty. A local secret file written before this option existed lacks `GATEWAY_ANALYTICS_STORE_PASSWORD`: run `scripts/bootstrap-local-secrets.py` again (it keeps existing values). **Docker Compose** (`deploy/docker/compose.yaml`): the `clickhouse` service runs only with the `analytics-store` profile (named `clickhouse` until 0.0.1-rc.2), with its data in the `gateway_clickhouse` volume; no port is published. The gateway gets `GATEWAY_ANALYTICS_STORE_USER` (default `gateway`, or the value in your environment). ```bash docker compose -f deploy/docker/compose.yaml --env-file deploy/docker/.env.local --profile analytics-store up -d ``` **Helm** (`deploy/helm/gateway`): `analyticsStore.bundled.enabled: true` adds a one-replica StatefulSet and its Service `gateway-clickhouse` (values under `analyticsStore.bundled`: `image`, `pullPolicy`, `serviceName`, `storage` 20Gi, `storageClassName`, `resources` 250m/1Gi requests and 2/4Gi limits, `nodeSelector`, `tolerations`, `affinity`). `analyticsStore.engine` (default `clickhouse`, the only value) must match `analytics_store.engine` in `gateway.config` when the YAML sets one. Its password is `GATEWAY_ANALYTICS_STORE_PASSWORD` in `gateway.existingSecret`, and the chart sets `GATEWAY_ANALYTICS_STORE_USER=gateway` on the gateway Pods. With `networkPolicy.enabled`, ClickHouse accepts only the gateway Pods on port 9000, and gateway egress to it is allowed when egress rules are on; without it, any Pod that can reach the ClickHouse Pod can try both ports, which still require the password. In both, point the gateway at it and turn a purpose on: ```yaml features: analytics_store_usage: true analytics_store: engine: clickhouse addresses: ["clickhouse:9000"] # Helm: ["gateway-clickhouse:9000"] database: gateway username_env: GATEWAY_ANALYTICS_STORE_USER password_env: GATEWAY_ANALYTICS_STORE_PASSWORD tls: mode: disable # private network between the two containers ``` Size the server for the volume; [through the gateway](/docs/benchmarks/analytics-store/#through-the-gateway-t019006) the store's latency, resource use and copy cost are measured at 1 and 10 million events. In the [engine comparison](/docs/benchmarks/analytics-store/), 50 million events took 3.4 GiB of ClickHouse disk against 27 GiB in PostgreSQL, and ClickHouse is an addition, not a replacement: PostgreSQL keeps every event. ## Retention and deletion The copy follows PostgreSQL: the metadata retention purge and the end-user deletion job change PostgreSQL first, and their triggers carry each deleted or redacted event to ClickHouse at the next pass. ClickHouse has no retention of its own to configure. Lightweight deletes hide rows at once and remove them from disk at the part's next merge. ## How the copy works - **One pass at a time.** Every replica runs the copy loop; a pass locks the single state row in PostgreSQL, so only one runs at a time across replicas and a pass that dies leaves the state as it was. - **Its own connection.** The copy uses one PostgreSQL connection of its own (with the `storage.database` settings, application name `ai-gateway-analytics-copy`), opened on first use, so a pass waiting on a slow ClickHouse never holds a connection that requests wait for. Count one more connection per replica in the database's limit. - **New events** are read after an identifier cursor, in identifier order. An identifier is taken before its transaction commits, so a smaller one can appear after a larger one: every identifier missing between copied events is kept as a gap and looked for again on each pass; an identifier found is copied and taken out of its gap. A gap closes only when every transaction older than the pass that recorded it has ended (PostgreSQL's snapshot horizon passed that pass's transaction ID) and at least 30 seconds have passed; age alone never closes one. A transaction left open (or a long one anywhere in the cluster, which holds the horizon back) keeps its gaps open and shows as `oldest_gap_seconds`; past 50000 open gaps the cursor waits. - **Changes.** End-user redaction and retention deletes are logged by PostgreSQL triggers while the copy is on; the next pass deletes those events in ClickHouse and writes their current row again. - **Idempotent and resumable.** A pass asks ClickHouse which of its events are already there and writes only the others, then commits the cursor in PostgreSQL. A pass that crashed after writing to ClickHouse is repeated without duplicates. - **Off and on again.** When both flags are off, the copy turns the change log off. The next enable empties the ClickHouse table and copies every event again, because changes made meanwhile were not logged. Before it reads anything, an enable waits until every transaction older than itself has ended, so a redaction or delete whose statement ran just before the enable is part of the copy. - **Money columns (T160.003).** With `budget_charge_reports`, each copied event also carries `quota_reservation_id`, `valuation_state`, `estimated_usd` (the known estimate, as exact decimal text) and its budget side, `budget_charge_state` and `budget_charge_units` (1e-12 USD), as they stand when the event is copied: a later reconciliation of its reservation shows in the PostgreSQL reports, not in the copy. A table created by an older release gains these columns (`ALTER TABLE ... ADD COLUMN IF NOT EXISTS`) at the first pass with the flag on; with the flag off the copy neither alters the table nor writes the columns, so an older table keeps working with a user without `ALTER` rights. Earlier rows, and rows copied with the flag off, keep them empty. - **While ClickHouse is unreachable**, passes fail and nothing is lost: the cursor waits and retention deletes and redactions accumulate in the change log (`pending_changes`) until it answers again. ## Usage analytics from the analytics store With `analytics_store_usage` on, `GET /api/v1/admin/analytics` (the Usage page) decides per request where to read: | Condition | Store | `read_store.fallback_reason` | | --- | --- | --- | | The copy is current (lag within `copy.max_lag`) | ClickHouse | — | | No `analytics_store` addresses, or the store failed to open | PostgreSQL | `not_configured` | | The copy is filling after an enable | PostgreSQL | `copying` | | Lag over `copy.max_lag`, or a redaction or delete not yet applied to the copy | PostgreSQL | `behind` | | ClickHouse failed or timed out on any statement (it gets at most half of the read's deadline, so PostgreSQL still has time to answer), and for 30 seconds after such a failure, or after a copy pass failed on ClickHouse, on that replica | PostgreSQL | `unavailable` | The whole view comes from one store: summary, timeline, the six rankings, the end-user and tag rankings, the 50 most recent events, the comparison summary (`analytics_comparison`) and the status panel (`analytics_status_breakdown`). From ClickHouse, p95 is computed over the whole window, so `analytics_rollup_reads` is not used and `p95_unavailable` never appears; rollup reads still apply when PostgreSQL answers. A ClickHouse failure is logged as `analytics_store_read_failed` with its class and the view is answered again from PostgreSQL within its own 5-second deadline. The report names the store: ```json "read_store": {"source": "clickhouse", "lag_seconds": 1.8} ``` ```json "read_store": {"source": "postgresql", "fallback_reason": "behind", "lag_seconds": 912.4} ``` `read_store` is absent while the flag is off, so existing clients see the same report as before. The Usage page shows the store under the time window. `GET /api/v1/admin/analytics/export` follows the same store and names it in the `X-Analytics-Read-Store` response header. **Same answers, same authorization.** ClickHouse statements return the rows PostgreSQL returns for the same filter: equal counts, sums, names, order and times, with averages and p95 equal within a relative 1e-9 (p95 is `quantileExactInclusive`, PostgreSQL's `percentile_cont`). The team a session may see, a named team or an organization is part of the `WHERE` clause in both stores, so it applies before any aggregation. Each copied row carries the organization its request ran in, so a team that moved is split between its former and its new organization exactly as in PostgreSQL ([when a team moves](/docs/features/organizations/#when-a-team-moves)); the team's current organization, or an organization's current teams, is read from PostgreSQL first. Data is only as recent as the copy: events committed in the last `lag_seconds` are not in a ClickHouse answer. **Limits.** - Ties in a ranking (equal request counts) are ordered by bytes in ClickHouse and by the database collation in PostgreSQL. They agree for lower-case ASCII names; with mixed case or accents a tie at the 20th place may name a different entry. - A completed end-user deletion is in PostgreSQL at once and in ClickHouse at the next pass (normally seconds); while that redaction waits, reads stay on PostgreSQL. ClickHouse keeps deleted rows on disk until its next merge of that part. - If a copy pass loses its PostgreSQL session while its ClickHouse write is still in flight, another replica may write the same events again; the table is a `ReplacingMergeTree`, so such duplicates disappear at the next merge, but until then a ClickHouse answer may count them twice. ## Request logs from the analytics store With `analytics_store_request_logs` on, these read the copy under the same conditions as analytics (copy current, ClickHouse answering, otherwise PostgreSQL with the reason): | Endpoint | From ClickHouse | Still from PostgreSQL | | --- | --- | --- | | `GET /api/v1/admin/logs` | Every filter (window, principal, team or organization, key, model, provider, operation, request and trace ID, status, exact status code, owner, end user, session, tags), the three orderings and offsets up to 10000; attempts and timing columns | The client address filter (`client_ip`), whose table is not copied: `fallback_reason: unsupported_filter` | | `GET /api/v1/admin/logs/export` | The same rows as the page; the store is in the `X-Read-Store` header | As the page | | `GET /api/v1/admin/requests/{id}`, request journeys, session summaries, agent graphs | — | Always: a reused request ID's newest event may be newer than the copy, exact lookups are faster in PostgreSQL, and the others join tables that are not copied | A page carries `read_store` like the analytics report; the Logs page shows it under the table. Pages hold the same rows in the same order as PostgreSQL for the events the copy holds; a duplicate a lost copy session may leave is never shown twice (`LIMIT 1 BY id`). Two consequences of the lag: a ClickHouse page lacks the events of the last `lag_seconds` (on the default newest-first page, the most recent seconds), and because each page decides its store on its own, paging by offset while the store changes between pages (a fallback starting or ending) can skip or repeat up to that many rows. As the [measured comparison](/docs/benchmarks/analytics-store/) showed, PostgreSQL answers index-friendly pages and exact lookups in under 3 ms where ClickHouse has a floor of about 3 ms per statement; ClickHouse pays off for sparse filters over long windows (a 90-day page filtered by status, provider and operation took 12.5 s in PostgreSQL at 50 million events and 30 ms in ClickHouse). Turn this purpose on only when such pages are slow. ## Spans written straight to the analytics store With `spans.engine: analytics_store` ([span store](/docs/features/traces/#where-spans-are-stored)), the span writer inserts each batch into this database instead of PostgreSQL, and every span read answers from here: no copy, no lag behind the database. The writer creates `gateway_spans_v1` (shared with the span copy; its own rows have `copy_id` 0), `gateway_trace_summaries_v1` and `gateway_spans_retained_v2`, with a table TTL equal to `spans.retention_days`; it needs no grant beyond the list above (`ALTER TTL` when the retention changes, `ALTER DELETE` for erasure). A copy reset (turning `analytics_store_spans` on after moving back to `engine: database`) deletes only copied rows and keeps the engine's own. While ClickHouse is unreachable, span batches are dropped and counted, requests are unaffected, and span reads answer `503 analytics_store_unavailable`. The measured trade-off is in [Span store engines](/docs/benchmarks/span-store-engines/). Request logs and evaluation results still live in PostgreSQL and reach ClickHouse through the copy. ## Lag and status `GET /api/v1/admin/analytics-store` (console permission `analytics:read`) reports the engine, where reads go and how far behind the copy is. The **Usage** page shows the same panel, titled **Analytics store · clickhouse** (the engine is a value; an answer without it, from a replica older than the rename, shows only **Analytics store**), when either flag is on. ```json { "configured": true, "engine": "clickhouse", "state": "current", "purposes": {"analytics": true, "request_logs": false}, "max_lag_seconds": 300, "lag_seconds": 1.8, "reachable": true, "copy": {"enabled": true, "cursor": 912045, "pending_rows": 0, "pending_rows_capped": false, "open_gaps": 0, "pending_changes": 0, "copied_total": 912040, "resets": 1, "last_pass_at": "2026-11-15T21:00:02Z"}, "settings": {"configured": true, "engine": "clickhouse", "database": "gateway", "tls_mode": "verify_full", "copy": {"batch_size": 5000, "interval": "2s", "gap_grace": "10m0s", "max_lag": "5m0s"}, "restart_required": true} } ``` - `lag_seconds` is the time since the start of the latest pass that found nothing more to copy: every event committed before it is in ClickHouse. It is absent until the first complete pass. - `engine` is the `analytics_store.engine` value, absent while the block names none. - `state` is `not_configured`, `off`, `copying` (filling after an enable), `unreachable`, `behind` (lag over `copy.max_lag`) or `current`. - `pending_rows` counts events after the cursor and stops at 100000 (`pending_rows_capped`); `oldest_gap_seconds` is the age of the oldest open gap. - `organization_backfill_pending` is present (`true`) while rows copied by a release before migration 214 are being copied again with their organization; `state` is then `copying` and reads use PostgreSQL. - A team-scoped session gets only `state`, `purposes` and the lag; the counts and settings describe the whole deployment. No address, environment variable name or file path is ever returned. - A failed pass records a class such as `clickhouse_unreachable`, `clickhouse_authentication_failed`, `clickhouse_unknown_database`, `clickhouse_access_denied` (a grant is missing; the ClickHouse server log names it) or `postgres_error`, and logs `analytics_copy_failed` once per class. ## Upgrade **Migration 214** renames the copy's cursor column and adds the organization to the copied request log. The gateway adds the column to the ClickHouse table at start (`ALTER TABLE … ADD COLUMN IF NOT EXISTS`, which needs the `ALTER` grant the copy user already has) and copies again, once, the rows the earlier release had copied that record an organization; nothing is copied again in a deployment that never had `organizations` on. Reads stay on PostgreSQL until it ends (`organization_backfill_pending`). A replica still on the earlier release stops copying (`analytics_copy_failed` in its log, `503` on its status view) until it is replaced; the upgraded replicas copy meanwhile. Measured cost and the full note: [when a team moves](/docs/features/organizations/#when-a-team-moves). Migration 159 adds the copy state, the gap ranges, the change log and two statement triggers on `gateway_usage_events`; with the flags off the triggers write nothing. Migrate and upgrade every replica before turning a flag on. **From 0.0.1-rc.2:** the `clickhouse:` block, the two `clickhouse_*` flags, the `GATEWAY_CLICKHOUSE_PASSWORD` and `GATEWAY_CLICKHOUSE_USER` names, the Helm `clickhouse:` values and the Compose profile `clickhouse` were renamed (table and steps in [upgrading from 0.0.1-rc.2](/docs/operate/operations/#upgrading-from-001-rc2-infrastructure-names)). Migration 195 renames feature overrides stored under the old flag ids, keeping their value. With the bundled server, add `GATEWAY_ANALYTICS_STORE_PASSWORD` with the value of `GATEWAY_CLICKHOUSE_PASSWORD` before the upgrade (in the vault when a secret manager writes the Secret), and keep the old key until a rollback is no longer possible: a rolled-back StatefulSet still reads it. The ClickHouse Pod restarts once during the upgrade; its data volume and Service keep their names. # Saved analytics views and dashboards **Last updated:** 2026-11-21T09:54:10-03:00 (UTC-3) A saved view keeps a set of [analytics](/docs/features/analytics-experience/) filters, a time range and up to eight dashboard widgets under your own console identity, so you can reopen the same slice later or share it read-only with one team. Flag: `analytics_saved_views` (default `false`). A view stores the **question, not the answer**: it holds no usage data. Whoever opens it, owner or team member, the console asks the ordinary analytics report again with that reader's own session, role, team scope and plan. Sharing a view therefore never shows anyone data they could not already see in **Usage**. ## Enable it ```yaml features: usage_analytics: true # required analytics_saved_views: true # saved views and dashboards ``` The flag is an operator control (it is not part of a team plan), changes at runtime through the feature API or **Configuration → Features**, and applies on the next request. It needs PostgreSQL (migration 134 creates `gateway_analytics_views`); without storage the API answers `503`. Turning it off hides the panel and the API (`404 feature_disabled`) and keeps the stored views; turning it back on shows them again. There is no other setting. The bounds below are compiled; views are user data, not operator configuration, so they have no YAML form. The flag itself has the usual YAML, API and console parity. ## Use it in the console **Observability → Usage** shows a **Saved views / Dashboards** panel under the filters. 1. Choose filters and a time range, then click **Apply analytics filters**. A view saves the *applied* filters, not the draft. For a team role, the team the console selects by default is not saved: each reader of the view gets its own default team, so a view shared with team B does not stay pinned to your first team. Choose a team explicitly to save it. 2. Click **Save as new view**. Give it a name (1–120 characters), an optional description (up to 500), and pick the sharing: - **Private (only you)**, the default. - **Read-only for team …**: team roles choose one of their own teams; global admins and viewers type a team ID. 3. Edit the widgets (1–8). Each has a title, a measure, a grouping and a chart: | Field | Values | | --- | --- | | Measure | `requests`, `tokens` (reported input + output), `error_rate`, `latency` (P95) | | Group by | `time`, `model`, `provider`, `team`, `principal`, `key`, `operation` | | Chart | `line` for `time`; `bar` or `table` for any other grouping | | Groups | 1–20, dimension widgets only (default 10) | 4. **Open view** applies the view's filters and draws its widgets above the usual tabs. A group's name in a bar widget focuses the filters on it; **Inspect requests** in a table widget opens Request logs with the same slice (requires `request_logs` and `logs:read`). 5. **Edit view** saves changes to your own view; **Delete** removes it after a confirmation. What the panel tells you: - *Yours · shared read-only with team t* — the team sees it now. - *Yours · not visible to team t: you can no longer act for it* — see [When a share stops working](#when-a-share-stops-working). - *Shared by u with team t* — a teammate's view; you can open it but not change it. If someone else saved the view since you opened it, saving answers a conflict: **Reload view** loads the current version, then you edit again. If it was deleted meanwhile, the panel closes it and refreshes the list. Editing a view shared with a team you have left starts with **Private** selected and says so. ## How the numbers behave The widgets use exactly the same report as the Usage tabs, so every rule of [reading the numbers](/docs/features/analytics-experience/#how-to-read-the-numbers) applies: - Dimension widgets rank the **top 20 groups the report returns** for the selection; a note says when more groups exist. They do not rank the full inventory. - A value that was not measured shows as *Not reported* and sorts last; it is never drawn as zero (tokens without token reports, P95 from rollup days, error rate without requests). - A team role opening a view with no team filter queries its own default team; a view whose team filter is outside the reader's membership answers `403 team_forbidden` from the analytics report, exactly as typing that filter would. - The time range is relative (`24h`, `7d`…) unless the view was saved with a custom range, which keeps its exact dates. ## Who can do what | Action | Roles | Rule | | --- | --- | --- | | List and open | admin, viewer, user, team_admin, team_viewer (`analytics:read`) | Your own views, plus effective shares: every team for admin and viewer, your live teams for team roles | | Save, edit, delete your own | the same roles (`analytics_views:save`) | Owner only edits | | Share | the same roles | Global roles: any existing team. Team roles: one of their live teams | | Delete someone else's | global admin | Only a view the admin can read (moderation) | The operator role has neither permission. A user bound to a [custom role](/docs/features/custom-roles/) keeps `analytics:read` when the role grants it, but never `analytics_views:save` (it is not part of the custom role catalog): such users can open views but not save them. With [team feature plans](/docs/features/entitlements/) on, a team role reads and writes views only for teams whose plan includes `usage_analytics`, the same ceiling as the report. Every create, update and delete is written to the control audit as `analytics_view.create`, `analytics_view.update` or `analytics_view.delete` with the target `analytics_view:`, the actor, the request ID and the version. The bootstrap administrator token owns its own views (`bootstrap_admin`). The shared viewer token reads every effective share like a global viewer but cannot save, edit or delete views (`403`): it names no person, so nothing it would publish could be attributed. ### When a share stops working A team share is **effective** only while its owner can still act for that team: the bootstrap administrator, a live global admin or viewer, or a live user, team admin or team viewer who is a member of the team; and the team is not deleted. When the owner leaves the team, is disabled, moves to a role without analytics (operator), or the team is deleted, the team stops seeing the view immediately. Nothing is rewritten: the owner still sees it, marked as not visible, and can make it private, share it with another of their teams, or delete it. A save cannot share again with a team the owner left (`403`). Making a view private (saving without a team) revokes the share at once. ## Limits - 50 views per owner and 10,000 in total (`409 view_capacity`). Creates are serialized, so concurrent saves cannot exceed either bound. - 1–8 widgets per view; definition JSON up to 16,384 bytes. - The list returns at most 200 views (own first, then most recently updated) and says when it was shortened; it has no pagination yet, so in a deployment with more shares a global admin moderates the others by ID through the API. - Names and widget titles refuse control and format characters (bidirectional overrides, zero-width), which could disguise a name shown to a team. - Filters follow the analytics bounds: exact values up to 256 bytes without control characters, end user up to 128 characters, usage tag text up to 1,024 bytes, custom ranges of at most 90 days. ## API All routes are under `/api/v1/admin`, take the console session (or the admin bearer token) and answer `Cache-Control: private, no-store`. Writes need same-origin and the `X-CSRF-Token` header. The full schema is in the [OpenAPI contract](/docs/api/). | Method and path | Purpose | | --- | --- | | `GET /analytics/views` | Your views and effective shares (no query parameters) | | `POST /analytics/views` | Create (201) | | `GET /analytics/views/{id}` | One view you can read; anything else is 404 | | `PUT /analytics/views/{id}` | Replace your view at `version` (compare-and-set) | | `DELETE /analytics/views/{id}?version=N` | Delete at version (204) | Create a view shared with a team: ```bash curl -sS -X POST "$GATEWAY/api/v1/admin/analytics/views" \ -H "Cookie: $SESSION" -H "X-CSRF-Token: $CSRF" -H "Content-Type: application/json" \ -d '{ "name": "Weekly traffic", "description": "Requests and top models", "team": "platform", "definition": { "schema": 1, "filters": {"range": "7d", "provider": "openai"}, "widgets": [ {"title": "Requests over time", "measure": "requests", "group_by": "time", "chart": "line"}, {"title": "Top models by tokens", "measure": "tokens", "group_by": "model", "chart": "bar", "limit": 10} ] } }' ``` Response (`201`): ```json { "id": "av_3f9c0d2e4b6a8c1e5f7a9b0c", "name": "Weekly traffic", "description": "Requests and top models", "owner": "usr_…", "own": true, "team": "platform", "share_effective": true, "definition": {"schema": 1, "filters": {"range": "7d", "provider": "openai"}, "widgets": ["…"]}, "version": 1, "created_at": "2026-11-14T06:35:00Z", "updated_at": "2026-11-14T06:35:00Z", "can_edit": true, "can_delete": true } ``` `PUT` takes the same body plus `"version"` and replaces the view as a whole: leaving `team` out (or sending `null`) makes it private. The definition schema refuses unknown fields; `filters.range` is one of `15m`, `1h`, `24h`, `7d`, `30d`, `90d` or `custom` (then `from` and `to` in RFC 3339 are required). | Status | Code | Meaning | | --- | --- | --- | | 400 | `invalid_request`, `invalid_id` | Unknown field, `version` on create, missing or extra query parameter | | 403 | `role_forbidden`, `entitlement_forbidden` | Not the owner, share team not allowed, neither owner nor global admin on delete, the shared viewer token writing, or no team plan with usage analytics | | 413 | `request_too_large` | Body over 32 KiB | | 404 | `feature_disabled`, `view_not_found` | Flag off, or the view does not exist for you | | 409 | `version_conflict`, `view_capacity` | Stale version, or a bound reached | | 422 | `invalid_view`, `invalid_view_definition` | Name/description/team or definition out of bounds | | 503 | `storage_unavailable` | PostgreSQL unavailable | ## Upgrade notes Migration 134 adds one table and runs automatically with the other migrations. As with every migration, an older binary refuses a database migrated by a newer release (`database schema has migration 134, newer than this binary supports`): roll out the new binary to every replica, and roll back only by restoring a backup taken before the upgrade. Views refer to teams by ID: deleting a team row clears the share target of its views, and a soft-deleted team stops the share without changing the view. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `GET /api/v1/admin/analytics/views/{id}` | Reads one saved view the caller may see | | `PUT /api/v1/admin/analytics/views/{id}` | Replaces a saved view the caller owns, at its current version | | `DELETE /api/v1/admin/analytics/views/{id}` | Deletes a saved view the caller owns | | `GET /api/v1/admin/analytics/views` | Lists your own views and the team shares you may read | | `POST /api/v1/admin/analytics/views` | Saves a new view owned by your session identity | ## See also - [Analytics](/docs/features/analytics-experience/) and its [CSV export](/docs/features/analytics-export/). - [m7 ai](/docs/features/ask-ai/#the-structured-usage-query) for any other grouping through the structured usage query. - [Access control](/docs/features/access-control/) and [custom roles](/docs/features/custom-roles/). # Custom dashboards **Last updated:** 2026-11-27T08:05:47-03:00 (UTC-3) A dashboard is a page you build yourself: charts of the gateway's metrics over time, single figures and notes, laid out in the order you choose. You keep it for yourself, or share it with a team or with an organization. Use one when the fixed screens do not put what you look at every day in one place: the spend of one product next to its error rate and its evaluation pass rate, for example. A dashboard keeps no data. Every time someone opens it, the gateway answers each widget with that person's own permissions, so sharing a dashboard never shows anyone more than the **Usage** and **Traces** screens already show them. ## Turn it on ```yaml features: usage_analytics: true custom_dashboards: true # off by default ``` `custom_dashboards` needs `usage_analytics` and a database. It is a tenant feature: with team plans, a team role uses it only for the teams whose plan includes it. You can also turn it on from **Settings → Features** or with `PUT /api/v1/admin/features/custom_dashboards`. Two kinds of widget need more: | To use | Also turn on | |---|---| | Evaluation metrics (pass rate, mean score, feedback) | `evaluation_metrics` ([evaluation metrics](/docs/features/evaluation-metrics/)) | | Widgets over traces and spans | `span_store` and `trace_explorer` ([trace explorer](/docs/features/trace-explorer/)); `trace_query` to write `OR`, `NOT` and groups in a widget's query ([query language](/docs/features/query-language/)) | | Cost metrics | `usage_valuation` | | A breakdown or a filter by usage tag | `usage_tags` | A widget whose source is off says so in its own place; the rest of the dashboard still loads. ## Build a dashboard 1. Open **Observability → Dashboards** and choose **New dashboard**. Give it a name and choose who it is shared with (see [Share a dashboard](#share-a-dashboard)). It opens in the builder. 2. Choose **Add widget**. Pick the type, then what it reads. The **Widget preview** on the right shows the widget with real data as you change it; type the title and the description straight into the preview. 3. Choose **Add widget** in the dialog. Use the arrows on a widget to move it earlier or later, the pencil to change it and the bin to remove it. 4. Choose **Save**. Nothing is stored before that, and every save is a [version](#versions). In the builder you can also drag a widget by its title onto another to take its place, and drag its right edge to resize it; on a narrow screen, where every widget takes the full width, use the arrows and the size in the widget's form. Leaving the builder with unsaved changes, by its own links, by the navigation rail, by signing out, by closing the tab or by going back within Dashboards, asks first. ### Widget types | Type | What it shows | Fields | |---|---|---| | **Time series** | One metric over time, as a line chart or a bar chart, optionally broken down by one dimension | Data, metric, group by, chart, interval, filters (or a query) | | **Single metric** | One figure for the whole range | Data, metric, filters (or a query) | | **Table** | Several metrics side by side, one row per group: the largest groups by the first metric | Data, columns (1 to 6 metrics), what a row is, how many rows (up to 50; up to 8 over traces), filters (or a query) | | **Markdown** | A note: headings (`#`, `##`, `###`), lists, `**bold**`, `*italic*`, `code`, fenced code and `http(s)` links. Anything else, HTML included, is shown as text | Text, up to 4,000 characters | Every widget has a title (1 to 80 characters), an optional description (up to 300) and a size: **small** (a third of the page), **medium** (half), **large** (two thirds) or **full**. On a narrow screen every widget takes the full width. ### Data: usage metrics A widget of source `usage` reads the [usage query](/docs/features/analytics-experience/) (`GET /api/v1/admin/analytics/query`): the same metrics, dimensions and filters, and the same numbers. - **Metric**: requests, errors, error rate, tokens, latency (mean, median, p95, p99), time to first byte, cost and cost per request, and, with `evaluation_metrics` on, evaluation results, pass rate, mean score, feedback and judge cost. The builder lists the ones this gateway offers. - **Group by** (time series): one dimension, such as model, provider, team, key, status class or `tag:`. The chart draws the **five largest groups** by the widget's metric and says how many there are in all. - **Filters**: up to 8 dimensions, each with 1 to 20 exact values and at most 94 values in all. A widget keeps the rows that match every filter. One widget reads requests or evaluation results, never both: the dimensions of a result (evaluation, evaluator, assessment and the like) go with an evaluation metric, and pricing status goes with a metric over requests. The builder offers only what fits the metric, and a save that mixes them is refused. - **Interval** (time series): minute, hour, day, week or month. Left on **Follows the range**, the gateway picks the finest one that fits. A series never has more than 100 points: an interval too fine for the range is widened, and the answer says which one was used. A time series has a point for every interval of the range. An interval without requests is `0` for a count and **no value** for anything else (a rate, a latency, a cost): the line shows a gap there, never a zero. A single figure follows the same rule: the p95 latency of no requests reads **No data**. ### Data: traces, by a query A widget of source `traces` reads the trace explorer's chart (`GET /api/v1/admin/traces/chart`) for the rows a query selects. - **Rows**: traces or spans. - **Query**: the [query language](/docs/features/query-language/) of the Traces screen, for example `status:error model:chat*`. Empty reads every row. The gateway's own calls (judges, helpers) are left out, as the Traces screen leaves them out. - **Metric**: count, errors, duration (mean), tokens or cost. Cost is only for readers who see cost. - **Group by** (time series): status, origin, team or model; the five largest groups are drawn, and the widget says when there are more. ### Data: experiment results A widget of source `experiments` reads the evaluation results of [experiment runs](/docs/features/evals/) alone, which the usage source leaves out as production figures do. It takes the evaluation metrics (results, pass rate, mean score, judge cost and the rest) and any of their dimensions, with one more: **Experiment run**, so a table with one row per run compares runs side by side and a time series follows them. It needs `evaluation_metrics`. The same dimension is in the usage query: `group_by=experiment_run` (or a filter on it) keeps experiment results in an evaluation query; a result of live traffic has an empty run. ### Tables A table of source `usage` or `experiments` lists up to 6 metrics, all over requests or all over evaluation results, for the largest groups by its first metric; the answer says how many groups there are in all. A table of source `traces` has one metric per row of status, origin, team or model, from the trace chart's totals: up to 8 rows, the chart's own bound. ### Time range and time zone A dashboard opens with the range you chose in the builder: the last hour, 6 hours, 24 hours, 7, 30 or 90 days. Anyone reading it can pick another range from **Time range**; that choice is theirs alone, goes into the page address (`?range=7d`) and is not saved. Days and hours start in the dashboard's time zone (an IANA name such as `America/Sao_Paulo`; UTC when empty). ## Share a dashboard | Shared with | Who sees it | What its widgets read | |---|---|---| | **Only me** | Its owner | Whatever the owner may read | | **A team** | The members of that team | **That team alone** | | **An organization** | The members of every team of that organization | **The teams of that organization** | A filter of the widget's own narrows inside that: on a team's dashboard, a widget filtered to another team shows nothing. **What "the teams of that organization" means.** Every source reads an organization by one rule, the rule of the usage query's `organization` dimension: a row belongs to the organization it was **recorded in**, and a row that records none (written before organizations were turned on) belongs to the organization its team is in now. So a team that joins the organization brings no history from its former one, and a team that leaves keeps its past numbers where they were recorded. Requests, evaluation results, traces and spans all follow it, on the database and on the analytics store, so two widgets of one dashboard always count the same organization. In both shared cases a widget reads only as far as each reader may: a member of two of an organization's five teams sees those two teams' numbers on the organization's dashboard, and a widget that needs something the reader's role or team plan does not include says **You may not read this widget** instead of a number. Who may do what follows three permissions: | Permission | Lets you | Who has it | |---|---|---| | `dashboards:read` | Open the dashboards shared with you, and your own | `admin` and `viewer` (every team and organization); `team_admin`, `team_viewer` and `user` (their teams and organizations) | | `dashboards:save` | Keep, change and remove your own dashboards | The same roles, when signed in as a named user (a shared token names nobody) | | `dashboards:share` | Share with a team or an organization, and change or remove what is shared with it | `admin` (any team or organization); an organization admin (its organization and its teams); `team_admin` (the teams they administer) | A shared dashboard belongs to its team or organization, not to its author: whoever holds `dashboards:share` there edits it, and the author keeps only the right to remove it. Only its author can make a dashboard private again. A [custom role](/docs/features/custom-roles/) can withhold any of the three. See [access control](/docs/features/access-control/). When organizations are in use, a team's dashboard stays with the organization the team was in when it was shared. If the team moves to another organization, the dashboard is no longer shown to it. **Query-language widgets on shared dashboards.** A widget of source `traces` is narrowed with a term in front of its query, which the answer's `query` shows: `team:""` on a team's dashboard and `organization:""` on an organization's, whatever the number of its teams ([the `organization` field](/docs/features/query-language/#fields)). So a widget's query must leave room for it: one term, one level of parentheses and 280 bytes under the [language's limits](/docs/features/query-language/#limits), checked when you save. ## The widget library A widget you want on several dashboards goes in the library: it is kept once, and dashboards **link** it instead of copying it. Change the library widget and every dashboard that links it shows the change at once. - **Put a widget in the library**: open it in the builder and choose **Save to library**. It is shared as the dashboard is (only you, the team or the organization) and the dashboard now links it. The library widget is stored at once: it stays in the library even if you then discard the dashboard's draft. - **Link one**: **Add from library** in the builder lists the library widgets you see. A dashboard keeps only the link's place and size. - **Change one**: the pencil on a linked widget edits the library widget itself, if you may edit it (the same rule as dashboards: its owner while it is private, whoever holds `dashboards:share` for its team or organization once it is shared). - **Unlink**: keeps a copy in the dashboard and drops the link. - **Remove one from the library**: in **Add from library**. Dashboards that linked it say so in the widget's place; nothing else on them changes. A shared dashboard shows all its readers the same widgets, so it links only what its whole audience reads: a team's dashboard links the team's library widgets and its organization's; an organization's dashboard links the organization's; a private dashboard links anything its owner sees. A save that links anything else is refused. A link that stops holding later (the library widget was removed or made private) shows **This widget's library widget is not available**. So does a link for a reader who does not see the library widget, such as the author of a team's dashboard after leaving the team. A person keeps up to 100 library widgets (`dashboards.library_per_owner`), and the gateway 10,000 in all (`dashboards.library_total`). ## Built-in dashboards and copies **Dashboards → Built in** lists dashboards the product maintains: **Traffic and errors**, **Latency**, and, when their features are on, **Cost** (`usage_valuation`), **Quality** (`evaluation_metrics`) and **Traces** (`span_store` and `trace_explorer`). They are read-only, have no versions, change only with the product, and read what you may read, like a private dashboard. To change one, choose **Copy**: the copy is yours, private or shared with a team or an organization, and starts its own versions. **Copy** works on any dashboard you can open. A link to the library is kept where the copy's audience reads that library widget; where it does not, the copy takes the widget itself; a link that no longer holds is left out. ## Add a chart from the Traces screen With the chart on in **Observability → Traces**, **Add to dashboard** keeps what the chart shows (traces or spans, the query, the metric and the breakdown) as a time series widget on a dashboard you may edit, or on a new private one. The dashboard is saved at once, as a new version. ## Versions Every save is a version: the name, the description and the widgets as you saved them, with who saved it and when. Open **Versions** on a dashboard to: - **View** an earlier version, with its widgets answered from today's data; - **Restore** it, which saves it again as the newest version. Where the dashboard is shared does not change. Versions belong to the audience they were saved for. When a save changes who the dashboard is shared with (private to a team, one team to another, to an organization), the earlier versions are removed, so notes and filters written for one audience are never read by the next. The dashboard itself and its newest version are kept. The gateway keeps the newest 50 versions of each dashboard (`dashboards.versions_kept`) and drops the oldest. Two people saving at once never overwrite each other: the second save is refused with `version_conflict` and the builder says so. ## Limits and settings The `dashboards` block of the configuration file sets the limits. It is read at startup, so restart the gateway to change it; the defaults suit most installations. ```yaml dashboards: per_owner: 50 # 1-500 dashboards one person keeps total: 5000 # 1-100000 dashboards in all; at least per_owner widgets_per_dashboard: 24 # 1-60 widgets on one dashboard versions_kept: 50 # 1-500 saved versions kept of each dashboard library_per_owner: 100 # 1-1000 library widgets one person keeps library_total: 10000 # 1-100000 library widgets in all; at least library_per_owner ``` | Setting | Default | Bounds | What happens at the limit | |---|---|---|---| | `dashboards.per_owner` | 50 | 1 to 500 | A new dashboard is refused with `dashboard_capacity` | | `dashboards.total` | 5000 | 1 to 100,000, at least `per_owner` | The same | | `dashboards.widgets_per_dashboard` | 24 | 1 to 60 | A save with more widgets is refused; lowering it never changes stored dashboards | | `dashboards.versions_kept` | 50 | 1 to 500 | The oldest version is dropped at the next save | | `dashboards.library_per_owner` | 100 | 1 to 1,000 | A new library widget is refused with `library_capacity` | | `dashboards.library_total` | 10,000 | 1 to 100,000, at least `library_per_owner` | The same | **Dashboards → Limits in effect** and `GET /api/v1/admin/dashboards/settings` show each value and whether it comes from the file or is the default. Fixed limits: a name of 1 to 120 characters, a description of up to 500, a definition of up to 262,144 bytes, 5 series per chart, 100 points per usage series, a range of at most 90 days that does not end in the future, and 20 seconds to answer one widget. ## API All routes take a console session: the session cookie and, on a write, the `X-CSRF-Token` header. The full contract is in the [API reference](/docs/api/). | Route | Does | Permission | |---|---|---| | `GET /api/v1/admin/dashboards` | Lists the dashboards you see, without their widgets, and what you may do | `dashboards:read` | | `POST /api/v1/admin/dashboards` | Creates a dashboard (version 1) | `dashboards:save` | | `GET /api/v1/admin/dashboards/{id}` | One dashboard with its definition | `dashboards:read` | | `PUT /api/v1/admin/dashboards/{id}` | Saves it as a new version; the body carries the current `version` | `dashboards:save` | | `DELETE /api/v1/admin/dashboards/{id}` | Removes it with its versions; `version` in the query is the version you read, so a dashboard someone changed meanwhile is not removed | `dashboards:save` | | `GET /api/v1/admin/dashboards/{id}/versions` | The kept versions | `dashboards:read` | | `GET /api/v1/admin/dashboards/{id}/versions/{version}` | One version with its definition | `dashboards:read` | | `POST /api/v1/admin/dashboards/{id}/versions/{version}/restore` | Saves that version again as the newest | `dashboards:save` | | `GET /api/v1/admin/dashboards/{id}/widgets/{widget}/data` | The data of one widget. `range` (`1h` to `90d`), or `from` and `to` (RFC 3339), replace the dashboard's own range; `timezone` its time zone; `version` reads the widget as a kept version had it | `dashboards:read` | | `POST /api/v1/admin/dashboards/preview` | The data of a widget that is not saved | `dashboards:save` | | `GET /api/v1/admin/dashboards/settings` | The limits in effect and the names a widget may use | `dashboards:read` | | `POST /api/v1/admin/dashboards/{id}/copy` | A new dashboard from one you see, a built-in one included; the body is `name` and where the copy lives | `dashboards:save` | | `GET /api/v1/admin/dashboard-widgets` | The library widgets you see | `dashboards:read` | | `POST /api/v1/admin/dashboard-widgets` | Keeps a widget in the library; the body is `widget` (what it shows, without `id` or `size`) and where it lives | `dashboards:save` | | `GET /api/v1/admin/dashboard-widgets/{widget}` | One library widget | `dashboards:read` | | `PUT /api/v1/admin/dashboard-widgets/{widget}` | Changes it for every dashboard that links it; the body carries the current `version` | `dashboards:save` | | `DELETE /api/v1/admin/dashboard-widgets/{widget}` | Removes it; `version` in the query is the version you read | `dashboards:save` | The `{id}` of the read, copy and widget data routes is a stored dashboard (`db_…`) or a built-in one (`dbb_traffic`, `dbb_cost`, `dbb_latency`, `dbb_quality`, `dbb_traces`); a built-in dashboard takes no update, delete, version or restore. The list answers the built-in ones under `builtin`. A dashboard's widget that links the library is `{"id": "w_…", "library": "lw_…", "size": "…"}`; reading the dashboard returns the linked library widgets under `library`. Create a team dashboard with four widgets: ```sh curl -sS -X POST "$GATEWAY/api/v1/admin/dashboards" \ -b cookies.txt -H "X-CSRF-Token: $CSRF" -H "Content-Type: application/json" \ -d '{ "name": "Checkout overview", "visibility": "team", "team": "team_checkout", "definition": { "schema": 1, "range": "7d", "timezone": "America/Sao_Paulo", "widgets": [ {"type": "single_metric", "title": "Spend", "source": "usage", "metric": "cost_usd"}, {"type": "time_series", "title": "Errors by model", "source": "usage", "metric": "errors", "group_by": "model", "chart": "bar", "filters": {"status_class": ["5xx"]}}, {"type": "time_series", "title": "Slow traces", "source": "traces", "metric": "count", "scope": "traces", "query": "duration>5s"}, {"type": "markdown", "title": "Read me", "text": "# On call\nAsk **platform** first."} ] } }' ``` The answer carries the dashboard's `id` and each widget's `id` (assigned when you send none). Read one widget: ```sh curl -sS "$GATEWAY/api/v1/admin/dashboards/$ID/widgets/$WIDGET/data?range=24h" -b cookies.txt ``` ```json { "widget": "w_3f9a1c20b7de", "type": "time_series", "source": "usage", "metric": "errors", "unit": "count", "from": "2026-11-26T12:00:00Z", "to": "2026-11-27T12:00:00Z", "timezone": "America/Sao_Paulo", "scope": {"visibility": "team", "team": "team_checkout"}, "bucket": "hour", "group_by": "model", "groups_total": 7, "groups_shown": 5, "series": [ {"key": "chat-default", "total": 41, "points": [{"at": "2026-11-26T12:00:00Z", "value": 3}, {"at": "2026-11-26T13:00:00Z", "value": 0}]} ], "reads": [ "/api/v1/admin/analytics/query?from=...&group_by=model&limit=5&metrics=errors&status_class=5xx&team=team_checkout&timezone=America%2FSao_Paulo&to=...", "/api/v1/admin/analytics/query?bucket=hour&from=...&group_by=model&..." ] } ``` `reads` lists the API calls the figure came from: call them yourself and you get the same numbers. `unit` says how to read a value: `count`, `tokens`, `usd` (an exact decimal string), `ms`, `us` (microseconds), `ratio` (a fraction from 0 to 1) or `score`. A `null` value means there is none: do not draw it as zero. A widget that cannot be answered returns an error instead of data: | Status and code | Meaning | |---|---| | `403 role_forbidden`, `team_forbidden`, `entitlement_forbidden` | Your role, your teams or your team's plan do not include what the widget reads | | `429 rate_limited` | Too many requests; try again shortly | | `409 widget_source_disabled` | A feature the widget's source, metric or dimension needs is off on this gateway; the message names it | | `422 widget_query_refused` | The source refused the widget's query for you, for example a field you may not filter on | | `404 library_widget_not_found` | The widget links a library widget that was removed, or is no longer shared with the dashboard's audience | | `422 query_too_costly` | The query ran past its time limit; shorten the range or narrow the filters | | `422 widget_has_no_data` | A Markdown widget has no data | | `404 dashboard_not_found`, `widget_not_found` | The dashboard does not exist or is not shared with you; or it has no such widget | ## What is stored and audited The database holds each dashboard's name, description, definition, owner and place, its kept versions, and the library widgets (`gateway_dashboards`, `gateway_dashboard_versions`, `gateway_dashboard_widgets`). No request data is stored; a filter or a query can name identifiers (a key, a customer, a tag value). Creating, saving, restoring and removing a dashboard are recorded in the admin audit (**Logs → Admin audit**) as `dashboard.create` (a copy too), `dashboard.update`, `dashboard.restore` and `dashboard.delete`, and a library widget's changes as `dashboard_widget.create`, `dashboard_widget.update` and `dashboard_widget.delete`. Removing a dashboard removes its versions. ## Upgrade notes Migrations 320 and 321 add the three tables. With `custom_dashboards` off nothing changes: no route answers, the console shows no **Dashboards** entry and no table is read. The [saved analytics views](/docs/features/analytics-saved-views/) of the Usage screen are a separate, older feature and are not converted. # External usage connectors **Last updated:** 2026-11-22T07:30:00-03:00 (UTC-3) An external usage connector reads a provider's own usage report, which includes traffic that did not pass through this gateway: a coding tool billed to an API organization, a script with a direct key, a provider console. The gateway keeps the latest report of every record, with corrections and withdrawals, and reports it next to its own traffic. Flag: `external_usage_connectors` (default `false`). **Reporting only.** The data arrives after the requests ran, so it can never admit, refuse or reserve anything: a hard budget cannot stop traffic that bypassed the gateway. Route the tool through the gateway when it must be governed. | Source | Report | Credential | | --- | --- | --- | | `anthropic_claude_code` | Claude Code usage report (Anthropic Admin API), `GET https://api.anthropic.com/v1/organizations/usage_report/claude_code`, one UTC day per call, paged | An Anthropic Admin API key, `x-api-key` with `anthropic-version: 2023-06-01` | | `openai_usage_completions` | OpenAI organization usage, completions (Admin API), `GET https://api.openai.com/v1/organization/usage/completions`, daily buckets grouped by model and API key | An OpenAI Admin key with usage read access, `Authorization: Bearer` | Origins are fixed, redirects are not followed and the credential comes from its environment variable at each synchronization: never stored, logged or shown. Other coding assistants (for example GitHub Copilot and Cursor usage feeds) are not implemented yet; the API lists them in `deferred_sources`. The Claude Code report covers Claude Code used with the API organization of the key; whether individual subscription seats appear depends on the provider's plan. ## Enable it ```yaml features: usage_analytics: true # required external_usage_connectors: true usage_connectors: - id: claude-code # ^[a-z][a-z0-9_-]{1,31}$ source: anthropic_claude_code # or openai_usage_completions admin_key_env: ANTHROPIC_ADMIN_KEY account_id: main-org # your label for the provider organization provider_id: anthropic # optional: labels possible overlap with this gateway's traffic finalization_hours: 48 # optional, 1-720; default 48 ``` | Field | Default | Meaning | | --- | --- | --- | | `id`, `source`, `admin_key_env`, `account_id` | required | As above. Source plus account, and source plus credential, are unique across connectors. Keep the account label and the connector ID stable: records are keyed by the label, and finality and overlap are read through the ID. | | `provider_id` | none | A configured provider. Days on which this gateway also served that provider are marked `possible_overlap`; the two are never added together. | | `finalization_hours` | `48` | Days that ended less than this ago are `provisional`. | Connectors are boot configuration; up to 16. The flag is an operator control and needs PostgreSQL (migration 148 creates `gateway_external_usage` and its runs). ## Synchronize `POST /api/v1/admin/external-usage/connectors/{id}/sync` with `{"from": "2026-10-15", "to": "2026-11-15"}` (UTC dates, `to` exclusive, at most 31 days, ending no later than tomorrow). Global administrator, `quotas:manage`, CSRF; audited as `external_usage.sync`. - Every page is read (cursor repeats refused, 512 KiB per page). A record repeated within one fetch refuses the synchronization. - A record's identity is its day (or bucket), actor, tool surface, customer type or project, tier and model. A new identity is a `new_record`; the same identity with different measures replaces them and counts as a `corrected_record`; an identity the provider no longer reports for a synchronized day is set to zero and counts as a `withdrawn_record`. - Claude Code users are stored as a pseudonym (`user_` and an unkeyed SHA-256 digest of the email scoped to the account label), never the email itself. The digest is not encryption: someone with database access and a list of candidate emails can test them. No API response returns actors. API-key actors keep the key name; records of key names that repeat on a day are summed. OpenAI rows keep the key ID, and a repeated OpenAI record refuses the synchronization. - Subscription usage, when the report carries it, is kept apart with a `/subscription` (or other customer type) suffix on the tool. - Sessions of a Claude Code record without a model breakdown are kept under model `[none]`. - Two synchronizations of overlapping periods cannot overwrite each other with older data: a snapshot whose fetch began before a newer overlapping run committed answers `409 sync_superseded`. - Rate limits: the providers' admin endpoints rate limit per organization. A `429` answers `503 connector_rate_limited` with the provider's `Retry-After`, and nothing is written; the Claude Code source makes one call (or more, when paged) per day, so retry later or sync a shorter period. - Claude Code's `estimated_cost` is read as cents and shown as `provider_estimated_usd`; rows without an estimate show `null`, never zero. OpenAI completions usage has no cost: use [provider cost connectors](/docs/features/billing-connectors/) for charges. `GET /api/v1/admin/external-usage/connectors` lists connectors as `usage_connectors` (the YAML names: `id`, `source`, `account_id`, `provider_id`, `finalization_hours`; credential configured or not) with their last five runs. ## Report `GET /api/v1/admin/external-usage?from=2026-10-15&to=2026-11-15` (at most 92 days) returns one row per day, connector, tool and model: `actors`, `requests`, `sessions`, input, output, cache-read and cache-write tokens, `provider_estimated_usd`, `state` (`synced` or `provisional`), `gateway_requests_same_provider` (every gateway request recorded for that provider and day, including refused ones) and `possible_overlap`. `coverage` gives, per connector, `days_covered`, `days_final` and `days_not_synced`, so a day without rows is either covered with no usage or not synchronized. At most 5,000 rows; `truncated` says when more exist. The response states `enforcement: none`. ## Console **Budget & TPM → Finance & reconciliation → External usage** lists connectors and runs, synchronizes the last 30 days (global administrator) and shows the report. Reading needs global `quotas:read`; team roles see nothing. ## Limits - Reporting only, after the fact; no enforcement and no reservation. - Copilot and Cursor are not implemented. - **Upgrade.** Migration 148. Upgrade every replica before turning the flag on. # m7 ai **Last updated:** 2026-11-25T17:18:19-03:00 (UTC-3) Most questions about a gateway are a filter and a group-by away: "how much did each team spend on each model per hour yesterday?", "which keys got the most 429s, and were they ours or the provider's?", "what blocked these requests?", "how do I set up a fallback?". m7 ai answers them in plain language from the console, in any language you ask in, with the data you are allowed to see and nothing else. It shows every step it took, so you can check where a number came from. Flags: `ask_ai` (off in the shipped configuration) and `usage_analytics` (on). Permission: `analytics:read`. With the separate flag `ask_ai_actions` (off), m7 ai can also [propose administrative changes](#administrative-actions) that run only after you confirm them. ## How it works The m7 ai launcher, the round button with m7 inside in the bottom-right corner of the console, opens the chat. You pick a chat model; your question goes to that model through this gateway, with a fixed set of **read-only tools**. The model decides which tools to call; the gateway runs them and returns the results to the model, for up to eight rounds, and the model answers from those results. Every tool reads through one of the console's own `GET` endpoints, **called with your session**. m7 ai therefore never sees more than your screens do: the same role permissions, the same team scope, the same flags and plan entitlements, the same 90-day range. A team viewer asking about another team gets the same refusal the Analytics screen gives (`team_forbidden`), and the model is told to say so. These tools only read. No tool creates, changes, deletes, sends or runs anything, and nothing runs a program on the gateway's host: the text search below is implemented inside the gateway. The only exception is opt-in: with `ask_ai_actions`, `propose_*` tools prepare a change that you review and confirm yourself (see [Administrative actions](#administrative-actions)); even they change nothing on their own. | Tool | What it answers | Reads | | --- | --- | --- | | `usage_query` | Totals, rankings, breakdowns and time series over every matching request: any combination of dimensions, a time bucket in a time zone, metrics, filters, order and row limit | [`GET /api/v1/admin/analytics/query`](#the-structured-usage-query) | | `usage_report` | The Analytics screen's summary with the previous period and the top groups | `GET /api/v1/admin/analytics` | | `request_logs` | A sample of individual requests (metadata only), newest first | `GET /api/v1/admin/logs` | | `search_text` | Regular-expression search, like `grep` and `sed`, over request log metadata, audit events, the effective configuration, the documentation and the API reference | the matching console endpoint, the [documentation build](/docs/operate/deployment-modes/) and the embedded OpenAPI | | `read_document` | A range of lines of one documentation page or of the OpenAPI file | the documentation build, the embedded OpenAPI | | `read_console` | One console resource: session, configuration (and its features, models and providers sections), keys, teams, console users (administrators only), organizations, guardrails, guardrail policies, alert channels and deliveries, quota status and alerts, rate limits, routing status, resilience, price book, MCP health, savings, or one request by ID | the resource's console endpoint | ## Using it 1. Turn on `ask_ai` (Settings & sources → Features, or `features.ask_ai: true` in YAML). `usage_analytics` must be on. 2. Open any console page and click the m7 ai launcher. Choose the model in the panel header; the choice is remembered in this browser. 3. Type the question and press Enter or the send button (Shift+Enter starts a new line). Follow-up questions carry the conversation (the last six turns). 4. Open **Steps** under an answer to see what ran: each tool, its arguments, the HTTP status and a summary such as `10 rows of 191 groups`. For `usage_query`, the step shows the structured query in one line, for example `by team, model · per hour (America/Sao_Paulo) · cost_usd, requests · order cost_usd desc · limit 10`, including whether it covered every team or only yours. Answers render tables, code blocks and bold text. Links are never rendered: a URL that came from logged data stays plain text. m7 in the launcher is live: it breathes, blinks and follows the pointer with its eyes, and hops when you press the launcher. With reduced motion turned on in the operating system (`prefers-reduced-motion`), it stays still and only blinks; with reduced transparency (`prefers-reduced-transparency`), the chat panel is opaque. ### Which model Any enabled chat alias that is not auto-routed works. How well a model follows tool instructions matters more than its size: in our tests a small current model answered most of the example questions below correctly in one or two rounds, while an older small model more often guessed filter values or put the time bucket in the wrong field. The tools correct the common mistakes (see [Limits](#limits-and-cost)), and a stronger model needs fewer rounds. Check the steps when a number matters. ### Example questions | Question | What the model does | | --- | --- | | Cost per team per model per hour in the last 24 hours, top 10 | `usage_query` with `group_by [team, model]`, `bucket hour`, `metrics [cost_usd]`, `order_by cost_usd`, `limit 10` | | Which keys had the most 429s yesterday, and from which provider? Ours or theirs? | `usage_query` filtered on `status 429`, grouped by `key_id, provider, error_code`: `rate_limited` is the gateway's own limit, an empty code is the provider's 429 | | Find timeout errors in the logs | `usage_query` with `non_empty [timeout_kind]`, grouped by `timeout_kind, model, provider` | | Which guardrail blocked the most requests? | `usage_query` grouped by `guardrail` with `non_empty [guardrail]` | | How do I configure a fallback? | `search_text` over `docs` for `fallback`, then `read_document` on the best page | | Who changed something in the control plane today? | `search_text` over `audit` with pattern `.` and `count_by actor` | | Which teams and models are configured, and is m7 ai on? | `read_console` for `teams`, `models` and `features` | ## The structured usage query With [`evaluation_metrics`](/docs/features/evaluation-metrics/), m7 ai also answers quality questions with the same tool: pass rate, mean score, feedback count and judge spend per evaluation, by any dimension of the judged request. `GET /api/v1/admin/analytics/query` is also a plain API, for dashboards and scripts. It needs `analytics:read` and `usage_analytics`, like the report it generalizes. The server builds the SQL from fixed names; nothing the caller sends is ever SQL text. ```bash curl -s -b cookies.txt "http://localhost:8080/api/v1/admin/analytics/query?group_by=team,model&bucket=hour&timezone=America/Sao_Paulo&metrics=cost_usd,requests&order_by=cost_usd&limit=10" ``` ```json { "query": {"from": "2026-11-07T12:25:00Z", "to": "2026-11-08T12:25:00Z", "group_by": ["team", "model"], "bucket": "hour", "timezone": "America/Sao_Paulo", "metrics": ["cost_usd", "requests"], "order_by": "cost_usd", "order": "desc", "limit": 10, "scope": "all"}, "columns": ["bucket", "team", "model", "cost_usd", "requests", "priced_requests", "unpriced_requests"], "rows": [["2026-11-07T14:00-03:00", "research", "claude-sonnet", "0.122475", 41, 37, 4]], "total_groups": 191, "truncated": true, "source": "usage_events", "currency": "USD", "cost_note": "cost_usd sums known valuations; unpriced_requests have no known cost and are not counted as zero" } ``` | Parameter | Values | Default | | --- | --- | --- | | `from`, `to` | RFC 3339 times, at most 90 days apart, `to` not in the future | the last 24 hours | | `group_by` | Comma-separated, up to 5 distinct: `team`, `organization`, `model`, `requested_model`, `provider`, `key_id`, `principal`, `operation`, `status`, `status_class` (`2xx`, `4xx`, `5xx`), `error_code`, `guardrail`, `timeout_kind`, `cache_kind`, `service_tier`, `auto_route`, `end_user`, `session_id`, `owner` (`kind:id`), `origin` (with [evaluation tracing](/docs/features/evaluation-tracing/#the-origin-of-a-request) on; a row without one reads as `app`), `helper_kind` (with evaluation tracing; empty on every row but a [helper call](/docs/features/evaluation-tracing/#helper-calls)), `pricing_status` (`complete`, `partial`, `inconsistent`, `unavailable`, empty for a call that was not answered; with [`pricing_coverage`](/docs/features/usage-valuation/#pricing-coverage)), `customer_org`, `customer_team` (`org/team`) and `customer_member` (`org/member`): the [customer](/docs/features/customer-portal/) the request named (with `customer_portal`), `tag:` | none: one total row | | `bucket` | `minute` (ranges up to 48 hours), `hour`, `day`, `week`, `month` | none | | `timezone` | `UTC` or an IANA `Area/Location` name such as `America/Sao_Paulo`; buckets follow its wall clock, and `bucket` is printed as the local start with its offset, `YYYY-MM-DDTHH:MM±hh:mm`, so the repeated hour of a daylight-saving change stays two buckets. POSIX-style names (`UTC+3`, `GMT-5`, `EST5EDT`, `Etc/GMT+3`) are refused: PostgreSQL reads their sign inverted | `UTC` | | `metrics` | Comma-separated: `requests` (client requests: [helper calls and fallback attempts](/docs/features/evaluation-tracing/#how-requests-are-counted) are left out of it and of `success`, `errors`, `error_rate` and the latency metrics), `calls` (every row), `success`, `errors`, `error_rate`, `input_tokens`, `output_tokens`, `total_tokens`, `cached_input_tokens`, `token_reports`, `cost_usd`, `priced_requests`, `unpriced_requests`, `p50_cost_usd`, `p95_cost_usd`, `p99_cost_usd`, `max_cost_usd`, `avg_cost_usd` (the cost of one request, with `cost_request_insights`), `avg_latency_ms`, `p50_latency_ms`, `p95_latency_ms`, `p99_latency_ms`, `avg_ttfb_ms` | `requests, errors, input_tokens, output_tokens, p95_latency_ms`, plus `cost_usd` with `usage_valuation` | | `=` | An exact filter on any dimension above, repeated for several values (`team=a&team=b`); up to 20 values each and 100 in all, 256 bytes each, no control characters | none | | `tag.=` | An exact usage tag filter | none | | `non_empty` | Comma-separated dimensions that must be set, for "blocked by any guardrail" or "with any timeout" | none | | `order_by`, `order` | `bucket`, a grouped dimension or a requested metric; `asc` or `desc` | with a bucket, time order; otherwise the first metric, largest first. `order` alone ranks by the first metric, also in a series (the top N buckets); use `order_by=bucket` for reverse time order | | `limit` | 1 to 500 | 100 | | `compare` | `previous`: also answer the same query over the period of equal length just before the range, in `previous` (with `quality_kpi_cards`; not for evaluation results) | none | What the values mean: - **`cost_usd`** is the exact decimal sum, in USD, of the requests with a known [valuation](/docs/features/usage-valuation/). It always comes with `priced_requests` and `unpriced_requests`, because a request without a known cost is not free: report the unpriced count, never treat it as zero. - **`p50_cost_usd`, `p95_cost_usd`, `p99_cost_usd`, `max_cost_usd`, `avg_cost_usd`** describe the known cost of one request (one request log row, helper and fallback calls included, as in `cost_usd`) in each group: the percentiles are the cost of an actual request of the group (never interpolated), exact decimals in USD. Requests without a known cost are left out and counted in `unpriced_requests`, which comes with them. `p95_cost_usd` by `team`, `model`, `key_id`, `end_user` or `customer_org` finds who drives the expensive tail. - **`customer_org`, `customer_team`, `customer_member`** are the customer organization, team and member a [trusted key](/docs/features/customer-portal/#identify-customers) named on the request; a team and a member read `org/team` and `org/member` because their IDs are unique only within their organization. Empty when the request named none, and a member is empty after its [erasure](/docs/features/customer-portal/). With `evaluation_metrics` they break evaluation results down too, by the judged request's customer; when the results are kept in the analytics store, `customer_team` is not available there (`400`), and a result written before this release for a request that named an organization without a member reads as no customer there. - **`error_code`** is the gateway's own problem code the client received (`rate_limited`, `guardrail_blocked`, `guardrail_blocked_output`, `model_forbidden`, ...). It is empty on success and when the error came from the provider, so a `429` with `rate_limited` is the gateway's limit and a `429` with an empty code is the provider's. - **`guardrail`** is the ID of the guardrail that blocked the request or its answer. - **`timeout_kind`** is `first_byte`, `idle`, `max_duration`, `client_stall`, `request` or `attempt` when a timeout ended the request. - An empty string is "not set". `non_empty` keeps only the rows where it is set. **Who sees what.** Administrators and viewers see every team (`scope: all` in the response). Team roles (`team_viewer`, `team_admin`, `user`) see every team they belong to and nothing else (`scope: teams`, with the list); a `team=` filter outside their membership answers `403 team_forbidden`. Unlike the Analytics screen, which shows one team at a time, a team role can group by `team` across its own teams. With [feature plan entitlements](/docs/features/entitlements/), cost metrics only cover teams whose plan includes `usage_valuation`. **Flags.** Each dimension or metric needs the flag that records or shows it on the screens: `status` and `status_class` need `analytics_status_breakdown`, `end_user` needs `end_user_tracking`, `session_id` needs `session_tracking`, `organization` needs `organizations`, `owner` needs `identity_ownership`, tags need `usage_tags`, `avg_ttfb_ms` needs `request_timing`, cost metrics need `usage_valuation` and the cost of one request also `cost_request_insights`, the customer dimensions need `customer_portal`, `pricing_status` needs `pricing_coverage` and `compare` needs `quality_kpi_cards`. Without the flag the request answers `400 feature_disabled`. With feature plan entitlements, a team role's query covers only the teams whose plan includes every such right it uses; with none left it answers `403 entitlement_forbidden`. **Errors.** `400` with `invalid_group_by`, `invalid_metrics`, `invalid_bucket`, `invalid_timezone`, `invalid_filter`, `invalid_order`, `invalid_limit` or `invalid_range`; `403 team_forbidden` or `entitlement_forbidden`; `404 feature_disabled`; `422 query_too_costly` when the query runs past its 5-second limit (narrow the range, the filters or the grouping); `503 storage_unavailable`. **How it runs.** Each query runs in a read-only transaction with a 5-second statement timeout and returns at most `limit` rows, with `total_groups` and `truncated` telling you what was left out. It reads the stored usage events within [retention](/docs/features/metadata-retention/); unlike the Analytics screen with `analytics_rollup_reads`, it does not read the daily rollups, so days whose events retention deleted are absent here. ## Searching text `search_text` takes a [RE2](https://github.com/google/re2/wiki/Syntax) pattern (up to 512 bytes) and one source: | Source | What is searched | Who may search it | | --- | --- | --- | | `request_logs` | Request metadata, one record per request as `field=value` pairs (`model=...`, `status=429`, `error_code=...`, `tags.env=...`), paged from the request log with its filters, up to 2,000 records | As the Request logs screen (`logs:read`, `request_logs`, team scope) | | `audit` | Control-plane audit events: time, source, action (such as `team.create`), target, actor, request ID | As the Audit screen (`audit:read`, `audit_explorer`) | | `config` | The effective configuration as `path = value` lines | As the configuration read (`config:read`) | | `docs` | The Markdown pages of the documentation build the gateway serves (`docs_site.dir`) | Anyone with m7 ai, when `ui` and `docs_site` are on | | `api` | The OpenAPI reference embedded in the gateway | Anyone with m7 ai | Options work like their command-line counterparts: `field` matches one record field; `ignore_case`; `invert` (`grep -v`); `count_by` tallies a field over every match; `extract` is a `sed`-style template of capture groups (`$1`, `${name}`) tallied over every match; `context` adds up to three lines around a text match (`grep -C`). Totals and tallies cover everything scanned; up to 50 matches are returned. Text results also rank files by match count, which is how the model picks the documentation page to read. The search runs inside the gateway with Go's RE2 engine, whose matching time grows linearly with the text, so no pattern can make it backtrack for minutes. Because that time also grows with the size of the pattern, counted repeats above 100 (`x{0,1000}`), a repetition inside a counted repeat above 10 (`(.*){0,30}`, `(.{0,3}){0,30}`; `(?:\d{1,3}\.){3}` and `(\d+\.)+` are fine) and patterns that compile to more than 500 instructions are refused; a costly pattern that remains stops at the time budget. The search stops at 2,000 records, 16 MB or 10 seconds, whichever comes first, and says so (`scan_stopped`). A record search resolves its time range once, so requests arriving during the scan are not counted twice, and refuses a `from` or `to` that is not RFC 3339 (`invalid_range`) instead of searching the default 24 hours. A team role that belongs to several teams sees all of them in `usage_query`; the request log and its search follow the Request logs screen, which shows one team at a time (the first, unless the model names another). **Secrets.** The configuration read already omits credentials. The search and `read_console` redact again: every provider header value (only header names are kept), values of fields whose names look like secrets (`api_key`, `token`, `password`, `webhook`, `subscription`, names ending in `-key` or `_key`, ...) become `[redacted]`, except names ending in `_env`, which hold an environment variable's name; and strings shaped like keys or bearer tokens are masked anywhere. Key values are never stored, so no tool can return one. **Documentation.** The gateway does not embed the documentation site; it searches the build it serves when `docs_site.dir` is set. Without it, `docs` answers `docs_not_served` and the API reference (`api`) is still searchable. ## Administrative actions With `ask_ai_actions` on, you can ask for a change in plain language: "create a key for the research team that can use gpt-4o-mini", "revoke key vk_…", "set the budget of team alpha to 250 dollars a month", "add Ana to team beta". The model **proposes** the change; it never makes it. The console shows the proposal as a card under the answer, and the change happens only when you click **Confirm change**. ### What can be proposed | Tool | Change | Runs as | Offered when | | --- | --- | --- | --- | | `propose_create_key` | A virtual or service-account key for a team, with explicit models (no `*`), explicit route scopes (default `route:chat`, never `route:*`) and an optional lifetime (`expires_in`, such as `30d`; no expiry when omitted) | `POST /api/v1/admin/keys` | `identity_management`, and the role may create keys (`keys:manage`, or a delegated member action) | | `propose_revoke_key` | Revoke a managed key (`vk_…` or `sa_…`). YAML keys are refused (`yaml_owned`), as are revoked ones | `POST /api/v1/admin/keys/{id}/revoke` | `identity_management`, and the role may revoke keys | | `propose_create_team` | A team in the default organization | `POST /api/v1/admin/teams` | `team_management` and `teams:manage` | | `propose_set_budget` | The USD budget of a team or a key: `budget_usd`, `budget_period` (`day`, `week`, `month`, `quarter`, `year`, `lifetime`; default `month`, or the current period) and optional `soft_budget`. It updates the subject's budget policy, or its token policy, or adds the policy `budget--`. A disabled policy is enabled (the card shows `disabled: true → false`); token limits and a temporary increase stay, and the card says so | `PUT /api/v1/admin/quota-policies/{id}` | `quota_management`, `budget_limits` and `quotas:manage` | | `propose_add_team_member`, `propose_remove_team_member` | Add a console user (by ID or exact name) to a team or remove them. Team-scoped roles only (`team_viewer`, `team_admin`, `user`); a user keeps at least one team and at most 20. Users provisioned by SCIM are refused (`idp_owned`): their identity provider owns their teams. The card shows the new membership's role: `member` under `membership_roles` (other memberships keep theirs); without it a `team_admin` administers every team it belongs to, so the card says `admin`. As on the Users page, a confirmed change with `membership_roles` off writes every kept team with that default role, so per-team roles stored while the flag was on are not preserved | `PUT /api/v1/admin/users/{id}` | `console_users`, `team_management` and `users:manage` | A tool is offered to the model only when its flags are on and your role's route permission allows the change; a global `viewer`, for example, gets no `propose_*` tool. For `team_viewer` and `user` roles the key tools are offered because a team can delegate key actions to its members; whether this team did is decided when you confirm, by the key route itself (`403 action_not_delegated` otherwise). Periods other than `day` and `month` also need their own budget flags, which the budget route checks. ### What you see and what is sent When the model calls a `propose_*` tool, the gateway builds the exact request itself from the typed arguments: the method and path are fixed per action, and nothing the model sends becomes a method, a path or a raw body. It reads the current state **with your session** (the team, key or user must be visible to you), refuses what cannot work (an unknown model, a wildcard, a YAML key, a user already in the team, a budget equal to the current one) and stores the proposal. The model is told that nothing has changed and that you must confirm. The card shows: - the change and its target, for example *Set the budget of team Alpha (team_3f…)*, policy `budget-team-team_3f…`; - every field that changes, as **Now** and **After** (the current value comes from the read just made; `—` means not set); - notes, such as "The key's secret is shown once, right after you confirm" or the version the change is tied to; - the exact request under **Request** (method, path and JSON body); - the expiry time, and **Cancel** and **Confirm change** (red for a revocation or a removal). **Confirm change** sends `POST /api/v1/admin/ask/proposals/{id}/confirm` with your session cookie and CSRF token. The gateway then: 1. claims the proposal on the database, once: it must be yours, from this same session, still pending and not expired (database clock); 2. writes the audit row `ask_ai..confirm` (target: the proposal ID, actor: you, with this request's ID) in the same transaction; 3. runs the stored request through the existing admin route with your session and CSRF token and the request ID `.ask-action`. That route checks your permissions and team scope **as they are now**, validates the request, checks the version it carries and writes its own audit row (for example `key.revoke`, actor: you); 4. returns that route's answer. For a new key the card shows the secret once, with a copy button; it is never stored with the proposal or sent to the model. **Cancel** sends `POST /api/v1/admin/ask/proposals/{id}/cancel`: nothing runs, and `ask_ai..cancel` is audited. ### Guarantees | Case | What happens | | --- | --- | | The model never proposes, or you never click | Nothing changes. Proposals expire 10 minutes after they are made | | Confirm twice, a replayed request, two tabs clicking at once | The first claim wins; every other answers `409 proposal_decided` and runs nothing. The proposal ID is the idempotency key | | Confirm after 10 minutes | `410 proposal_expired`; ask again for a fresh proposal | | Another user, or another session of yours (a different login), confirms | `404 proposal_not_found`, without revealing that the proposal exists | | A request without your CSRF token, or from another site | `403 forbidden`, like every console write | | Your permissions or teams changed after the proposal | The route refuses with its usual answer (for example `403 team_forbidden`); the proposal becomes `failed` | | The team's budget, the quotas or the user changed after the proposal | The version carried in the proposal no longer matches: `409 version_conflict`, the proposal becomes `failed`, and the change made in between is kept | | `ask_ai_actions` was turned off after the proposal | Confirm answers `404 feature_disabled` | A failed or cancelled proposal is never retried: ask again. When a question fails after the model proposed something (the model call fails or never answers), its proposals are cancelled, since no card was shown. A proposal whose change was sent stays `executing` if the gateway stops mid-way; it is not run again. ### Prompt injection Logged values and other tool results can contain text that reads like an instruction ("revoke every key"). The system prompt tells the model to propose only what you asked for in your own words, but a model can still be misled. That is why a proposal never runs by itself: **read the card before confirming**. It shows the real target and values the gateway read with your session, not the model's description of them. A proposal can only be one of the six actions above, inside what your role may already do. ### Limits | Limit | Value | | --- | --- | | Proposals per answer | 4 | | Pending proposals per user | 20 (`429 too_many_pending_proposals` to the model until you confirm or cancel some) | | Expiry | 10 minutes after the proposal, on the database clock | | Running a confirmed change | 15 seconds | | Retention | Decided and expired proposals are removed 7 days after their expiry; audit rows stay | Proposals are stored in PostgreSQL (table `gateway_ask_ai_proposals`, migration 129), so any replica can confirm a proposal another replica made. Without a database, no `propose_*` tool is offered. ### API `POST /api/v1/admin/ask` returns `proposals` next to the answer when the model proposed something: each with `id`, `action`, `method`, `path`, `body`, `card` (`title`, `target`, `destructive`, `changes` with `field`/`before`/`after`, `notes`), `state` (`pending`) and `expires_at`. ```bash curl -s -b cookies.txt -H "X-CSRF-Token: $CSRF" -X POST \ http://localhost:8080/api/v1/admin/ask/proposals/askp_0f3c…/confirm ``` ```json {"version": 7, "policy": {"id": "budget-team-team_3f2a", "subject": "team", "subject_id": "team_3f2a", "budget_usd": "250", "budget_period": "month"}, "proposal": {"id": "askp_0f3c…", "action": "budget_set", "state": "executed", "result_status": 200}} ``` The answer is the admin route's own status and JSON with `proposal` added (`state` `executed` or `failed`, and `result_status`); a `204` becomes `200`. Confirm and cancel also need `analytics:read`, like m7 ai. A shared-token API caller (`Authorization: Bearer`) can confirm its own proposals; its proposals are bound to its role. ### Turning it on ```yaml features: ask_ai: true ask_ai_actions: true ``` Or Settings & sources → Features in the console, or the features API. `ask_ai_actions` requires `ask_ai` and is an operator control: it adds no permission; each change still needs the role and flags in the table above. ## Logged data is data Some request metadata comes from clients: the end user, the session ID, tags. A client can put text there that reads like an instruction. m7 ai treats every tool result as data: the system prompt says so, the set of tools offered to the model is fixed for the whole question and does not change with anything a tool returns, a tool name the model invents runs nothing, and every tool reads with your permissions. Without `ask_ai_actions`, the worst a manipulated answer can do is misstate what you could already read, and the steps show what actually ran. With it, a manipulated model can also propose a change, which still waits for your confirmation (see [Prompt injection](#prompt-injection)). ## Limits and cost | Limit | Value | | --- | --- | | Question | 1 to 2,000 characters; history up to 10 turns of 8,000 characters | | Tool rounds | 8, with up to 4 calls per round; then one last round without tools, so the model answers from what it has (`limit_reached: rounds` in the API, a note in the console). That round carries the question and a digest of the results (at most 48 KB), not the tool-call history, so every provider accepts it and it stays small | | Prompt tokens per question | 120,000 summed over every round, the last included: before each tool round the gateway estimates that round's prompt (tool definitions included) plus the last round's, and when they would cross the ceiling the last round comes instead (`limit_reached: prompt_tokens`) | | Questions in flight | 2 per console user; a third answers `429 ask_ai_busy` with `Retry-After` | | Answer tokens | 1,500 per round | | Tool result | 24 KB; larger results keep whole rows and say `truncated_for_size` | | Time | 8 s per read plus 10 s per search; 120 s per question | | `usage_query` rows | 200 per call from m7 ai (500 through the API) | Each model call goes through this gateway like any other request: it is recorded under the principal `console-ask-ai:`, counts against that principal's quotas, and bypasses the response cache. With [evaluation tracing](/docs/features/evaluation-tracing/#helper-calls) on, each call is a helper call of sub-kind `ask_ai` (m7 ai), billed to a team: the one you send as `team` in the request, or your only team when you have exactly one (a session with several teams and no `team`, or a global administrator with none, pays at the gateway level). The team's policy then applies to the model, and the calls appear in Cost under **helper · m7 ai**, out of Usage's request counts. A typical question costs one or two rounds and 5,000 to 10,000 prompt tokens. The tools also correct the mistakes models make most often: a call repeated with the same arguments is refused (the model reuses the earlier result); a range that ends in the future is cut at now; a time bucket named among the dimensions becomes the bucket; a filter value of `*` means "set"; an empty result after a filter lists the values that do exist; a search that scanned records but matched none says it is not evidence that nothing happened; a guessed documentation page name suggests the pages that mention it. ## API `POST /api/v1/admin/ask` with `question`, `model` and optional `history`. The response carries `answer`, `steps` (round, tool, the declared arguments, HTTP status, error, summary and, for `usage_query`, the normalized `query`), `rounds`, `limit_reached` when it applies, and token `usage`. Both operations are in the OpenAPI reference (`/openapi.yaml`, and Swagger at `/docs/swagger/`). ## See also - [Analytics](/docs/features/analytics-experience/), [valuation](/docs/features/usage-valuation/), [usage tags](/docs/features/usage-tags/). - [Request audit events](/docs/features/request-events/) for the full per-request record on stdout. - [Access control](/docs/features/access-control/) for roles and permissions. # Analytics export **Last updated:** 2026-10-28T13:54:53-03:00 (UTC-3) Take the usage summary into a spreadsheet or your monthly report: the same view you see in [Analytics](/docs/features/analytics-experience/), as CSV. Flag: `analytics_export`, which requires `usage_analytics`. ## How to use it **In the console:** **Usage → Export summary CSV**. The file uses exactly the period and filters applied on the screen. **Through the API:** `GET /api/v1/admin/analytics/export`, with the same filters as analytics: `from`, `to` (up to 90 days), `principal`, `model`, `team`, `provider`, `key_id` and `operation`. Each filter accepts an exact value of up to 256 bytes. ## What is in the file - The summary for the period and, with `analytics_comparison`, the previous period of the same length. - Up to **20 groups per dimension** (model, team, provider...), sorted by number of events. - Tokens reported by the provider, the coverage (`token_reports`), and the mean and p95 of the duration. The `X-Analytics-Truncated-Dimensions` header lists the dimensions that went over 20 groups; `X-Analytics-Export-Scope: summary-and-top-dimensions` and `X-Analytics-Dimension-Limit: 20` make the scope explicit. Not in the file: cost, prompts, responses, credentials and the time series. For individual events, use the **Request logs** export; for cost, **Cost estimates** in Analytics. ## How to read the numbers - **Tokens** are only those reported by the provider. `token_reports` counts events with at least one counter (including zero); missing information is not zero. - **Duration** is the gateway's, end to end: it is not TTFT nor provider-only latency. - **Success** is HTTP 200 to 399; **error**, 400 or above. - Values that a spreadsheet would interpret as formulas are neutralized. ## Who can use it The same authorization as analytics. Team roles export only their own team; `operator` does not export usage. The response is `no-store`. ## Limits - A window of up to 90 days and a 5 s query. - The panels are separate queries: a new event can appear between them. ## See also - [Analytics](/docs/features/analytics-experience/). - [Logs, traces and metrics](/docs/features/observability/). # Alerts **Last updated:** 2026-11-26T00:47:12-03:00 (UTC-3) Send alerts when a team crosses a budget threshold, a guardrail blocks a request, an MCP server fails its health check, or someone creates or revokes a key. PostgreSQL stores delivery state for Slack, Microsoft Teams, email, PagerDuty and webhooks, with bounded retries and recovery after a replica stops. | Flag | What it turns on | | --- | --- | | `alert_channels` | Delivery and reading of channels | | `alert_channel_management` | Creating, testing, and resending from the console and the API | | `alert_digests` | Default off; additive durable periodic summaries for channels whose `digest.enabled` is true; requires `alert_channels` | | `operational_alerts` | The [operational events](#operational-events): open circuit, provider errors or latency, database down, usage write, secret manager and telemetry export failures (requires `alert_channels`) | | `alert_rules` | Default off; [alert rules](/docs/features/alert-rules/): rules you configure over the request log and the stored spans, the Alerts screen, a backtest and built-in rules. Their alerts are delivered by the channels below | | `alert_signing_rotation` | Default off; [rotate a webhook signing secret](#rotate-a-webhook-signing-secret) with an overlap in which every delivery carries a signature with the new and with the previous secret (requires `alert_channels`) | ## Events | Event | When | | --- | --- | | `quota_budget_threshold` | A budget crosses one of the `alert_thresholds` (see [budget alerts](/docs/features/quota-governance/#soft-budget-and-alerts)) | | `quota_reservation_overrun` | A provider billed more, in tokens or USD, than a [budget or TPM](/docs/features/budgets-and-tpm/) reservation bounded; the excess is debited in full. One event per reservation by default, written in the settlement's own transaction so a burst loses none: each names its reservation, request, model and the reserved and measured amounts. The [quota settings](/docs/features/budgets-and-tpm/#quota-settings) can raise it only above a tolerance, or fold overruns with the same model and set of billed policy subjects into bounded events; queued events are immutable, so later overruns create a new event | | `customer_budget_crossed` | A [customer portal](/docs/features/customer-portal/) organization, team or member reaches one of its alert thresholds; once per level, window and threshold, with the team, organization, level, customer ID, threshold, budget and committed USD | | `customer_override_requested` | A [customer portal](/docs/features/customer-portal/#override-approval-requests) member override request awaits a decision; with the team, organization, member, request ID, amount, expiry and requester | | `customer_override_decided` | That request was approved or denied; with the same fields, the state and who decided | | `guardrail_blocked` | A [guardrail](/docs/features/guardrails/) blocks a request | | `evaluator_health_changed` | With [evaluation tracing](/docs/features/evaluation-tracing/#evaluator-health-and-cost): a judge run leaves an evaluator blocked (the evaluator was auto-paused) or degraded (judge errors); with the team, the evaluator, the state and the reason code; one per evaluator and state per hour | | `mcp_health_failed` | The health check of an [MCP](/docs/features/mcp-execution/) server fails | | `key_created`, `key_revoked`, `key_deleted` | A key is created, revoked, or deleted | | `model_follow_changed` | A [moving model alias](/docs/features/model-aliases/#moving-aliases-follows) starts serving another model, or no model, after a configuration change; one event per change and control version across replicas, with the previous and new model and upstream model | | `evaluation_monitor_alert`, `evaluation_monitor_recovered` | With [`evaluation_monitors`](/docs/features/evaluation-monitors/): a monitor entered warning or alert (also each renotification and a test notification), or returned to OK. The payload carries a typed `monitor` object with the value, the threshold, the window and a link to the matching traces. Subscribing only makes the channel selectable by the monitors of the teams in `rule_teams` and of the organizations in `rule_organizations`: an event goes to the channels its monitor names, never to every subscriber | | `rate_limit_would_limit` | With [`rate_limit_observe_mode`](/docs/features/rate-limits/#observe-only-policies): an observe-only rate policy admitted a request past its limit; at most one event per policy every 15 minutes, with the policy, its subject, limit and window | | `prompt_created`, `prompt_version_published`, `prompt_deleted` | With [`prompt_events`](/docs/features/prompt-registry/#prompt-events): a prompt was created (in the console, through the admin API, by a team-delegated write, or added to the YAML file), a revision was published, or a console prompt was deleted. Written once per change, in the change's own transaction, whatever path made it; the detail holds `prompt_id`, `team`, `organization`, `revision`, `previous_revision`, `name`, `path` (`console`, `api`, `yaml`), `actor` and `request_id`, never the prompt's text | | `prompt_label_deployed` | With [`prompt_labels`](/docs/features/prompt-registry/#labels-and-deploy-to): Deploy to moved a prompt label to a revision; the detail names the label, the revision and the previous one | | `alert_rule` | With [`alert_rules`](/docs/features/alert-rules/): an alert of a rule fired (`state: firing`) or was resolved (`state: resolved`). Subscribing only makes the channel selectable by rules: an alert goes to the channels its rule names, never to every subscriber | | `provider_circuit_open`, `provider_error_rate`, `provider_slow`, `database_down`, `usage_write_failures`, `secret_manager_failures`, `telemetry_export_drops` | With `operational_alerts`: a condition starts (`state: firing`) or ends (`state: resolved`); see [operational events](#operational-events) | Events contain bounded metadata, not prompts, responses or credentials. An overrun is one event per reservation by default. With a deduplication window, folding requires the same model and the same set of billed policy subjects; two different owners are never combined. Once any channel queues an event, its details stop changing. A later overrun, or a full metadata list, starts another event. See [quota settings](/docs/features/budgets-and-tpm/#quota-settings). ## Key expiry notices The optional key_expiry_warnings operator flag produces key_expiring and key_expired for current managed credentials with an explicit deadline. Never credentials produce neither. Thresholds, interval, timeout and batch size are configurable through security.key_lifecycle and the guarded API/console policy editor. A transactional generation/expiry/threshold identity deduplicates notices across replicas; delivery reuses this outbox and configured channels. Notices contain safe identity/deadline and request/trace correlation, never the secret, confirmation nonce or arbitrary tag values. See [key policy](/docs/features/key-policy/#expiry-notifications) for defaults, recovery and exact bounds. ## Operational events With `features.operational_alerts` (off by default; it requires `alert_channels`), every replica evaluates its own state once per `interval` in the background and records an event when a condition **changes state**. They watch the same signals as the [Prometheus alert rules](/docs/features/observability/#alert-rules), for installations that have no Prometheus or want the gateway's channels too, but per replica, over the evaluation interval and without a `for` delay, so they are faster and noisier than the rules. | Event | Subject | Firing when (per interval) | Detail | | --- | --- | --- | --- | | `provider_circuit_open` | `provider/model` | a circuit-breaker destination is open or half open (waiting for its trial call) | `open_destinations` | | `provider_error_rate` | provider ID | failed attempts / attempts ≥ `provider_error_ratio`, with at least `provider_min_attempts` attempts | `error_ratio`, `attempts`, `threshold` | | `provider_slow` | provider ID | p95 latency to response headers > `provider_slow_p95`, with at least `provider_min_attempts` answers | `p95_seconds`, `threshold_seconds` | | `database_down` | `postgresql` | this replica's PostgreSQL ping fails within `storage.database.acquire_timeout`; a pool saturated past that timeout also counts | none | | `usage_write_failures` | `usage` | at least one usage record could not be written | `failures` | | `secret_manager_failures` | `secret_manager` | a secret from the [secret manager](/docs/operate/secret-managers/) failed its last refresh | `failing_secrets` | | `telemetry_export_drops` | `logs`, `traces` or `metrics` | the OTLP exporter dropped records | `dropped` | Every event carries `state` (`firing` or `resolved`) and `replica` (the host name of the replica that judged it); a resolved one also carries `firing_since`, and `reason: no_traffic` when a provider stopped receiving traffic. Failed attempts are transport errors and timeouts, invalid answers, 5xx and 429; client cancellations are not counted. ```yaml features: alert_channels: true operational_alerts: true alerting: operational: interval: 1m # 10s-15m: evaluation period and measurement window cooldown: 15m # 1m-24h: minimum time between two events of one condition and subject provider_error_ratio: 0.2 # 0.01-1 provider_min_attempts: 20 # 1-100000: below it, ratio and latency are not judged provider_slow_p95: 30s # 1s-2m (the last finite latency bucket) channels: - id: oncall name: On-call kind: pagerduty url_env: ONCALL_PAGERDUTY_URL events: [provider_circuit_open, provider_error_rate, database_down, usage_write_failures] ``` Every field shown is its default; leave it out to keep it. The values are read at every evaluation, so a configuration reload applies from the next one without a restart. `GET /api/v1/admin/alert-channels` returns them under `alerting.operational` (next to `alerting.signing_overlap`) with their source (`yaml` or `default`), and **Alert channels** in the console shows them under the event list. How it behaves: - **Transitions only.** A condition that stays down records nothing more. - **Low traffic.** A provider with fewer than `provider_min_attempts` attempts (or answers, for latency) in an interval is not judged: its attempts accumulate over up to 10 intervals until there are enough, and older ones are dropped. An interval with no traffic at all resolves a firing provider condition (`reason: no_traffic`), for example after failover or removal from the configuration. - **Rate limited.** Two `firing` events of the same condition and subject are at least `cooldown` apart; a `resolved` is sent as soon as it is observed, so a short incident is not left open. A flapping condition gives at most one `firing` and one `resolved` per cooldown; when the cooldown ends, the current state is reported if it differs from the last one sent, so the channel always converges. - **Per replica, deduplicated.** Each replica judges its own breakers, traffic and database connection, so each reports its own transitions: with three replicas, an outage they all see gives three `firing` events. The event key contains the condition, subject, replica, state and cooldown bucket, so a retried write is recorded once. - **Never on the request path.** Requests only increment counters; evaluation and writes run in their own goroutine, each write bounded by 2 s. - **Only what someone subscribed to.** A transition that no enabled channel subscribes to is not written. Turning the flag off forgets every state, so turning it on again starts clean. - **Database outages.** The outbox is in PostgreSQL. An event that cannot be written waits in a queue of 64 per replica (the oldest is dropped past that, with an `operational_alerts_dropped` log). `database_down` is therefore delivered once the database is back, followed by its `resolved` at the next evaluation. For live paging on an outage, use the `GatewayDatabaseDown` rule. - **PagerDuty:** firing triggers and resolved resolves one incident per replica, with `dedup_key` `::`. - **State is in memory.** A restart, or turning the flag off, forgets what was firing: a condition that ends meanwhile sends no `resolved`, so close such an incident by hand. Deliveries are retried independently, so a destination can receive a retried `firing` after its `resolved`. ## How to turn it on ```yaml features: alert_channels: true alert_channel_management: true alerting: allowed_private_cidrs: [] # allowed destinations on a private network (e.g., an internal webhook) allow_loopback_http: false # local testing only channels: - id: finance-slack name: Finance Slack kind: slack # slack | teams | webhook | email | pagerduty url_env: FINANCE_SLACK_WEBHOOK_URL events: [quota_budget_threshold] - id: siem name: SIEM kind: webhook url_env: SIEM_WEBHOOK_URL signing_secret_env: SIEM_WEBHOOK_SECRET events: [quota_budget_threshold, key_created, key_revoked] ``` | Key | Default | What it does | | --- | --- | --- | | `channels[].id` | required | Lower-case identifier, up to 64 characters | | `channels[].name` | required | Display name of the channel, 1–80 characters without control characters or surrounding spaces | | `channels[].kind` | required | `slack`, `teams`, `webhook`, `email` or `pagerduty` (see below) | | `channels[].url_env` | required | Variable holding the destination URL, which is a secret | | `channels[].signing_secret_env` | empty | Webhooks only: variable holding the secret that signs each delivery | | `channels[].events` | required | The events the channel receives | | `channels[].disabled` | `false` | Stops deliveries without removing the channel | | `channels[].headers` | empty | Webhooks only, with `alert_webhook_headers`: up to 10 headers sent with every delivery, each `name` with `value` or `value_env` ([below](#send-your-own-headers)) | | `channels[].rule_organizations`, `channels[].rule_teams` | empty | With the `alert_rule` event: the organizations and teams (up to 64 each) whose administrators may attach the channel to their own [alert rules](/docs/features/alert-rules/#open-a-channel-to-the-rules). Global rules may use any channel with the event | `allowed_private_cidrs` and `allow_loopback_http` take effect at startup. **In the console:** **Alert channels** creates channels whose URL and signing secret are **encrypted** with the control plane key (`storage.provider_encryption_key_env`). No read returns the URL or the secret, only the origin (`https://host`). **Test** sends a synthetic message right away. The API is `PUT /api/v1/admin/alert-channels/{id}`. Channels from the YAML cannot be edited in the console. ### By channel type | Type | Configuration | What it receives | | --- | --- | --- | | `slack`, `teams` | Incoming webhook URL | `{"text": ...}` | | `webhook` | Any HTTPS URL; `signing_secret_env` optional | `{event, delivery_id, sent_at, alert, message}` | | `email` | `smtps://user:pass@smtp.example.com:465?from=gw@example.com&to=finops@example.com` | One email per alert. `smtp://` requires STARTTLS | | `pagerduty` | `https://events.pagerduty.com/v2/enqueue?routing_key=` | One event; the `dedup_key` is the delivery ID, `::` for [operational events](#operational-events) or `alert_rule:` for [alert rules](/docs/features/alert-rules/), whose `resolved` resolves the incident | **Webhook signature:** with a secret, every delivery carries `X-Gateway-Signature: t=,v1=`, the HMAC-SHA256 of `t + "." + body`. Verify the signature and the timestamp before you trust the content. ### Verify a webhook delivery `t` is the time of **this attempt**, not of the alert: a retry hours later carries a fresh `t` and a fresh signature over the same body. A receiver should: 1. Split the header on `,`. Take `t`, and every `v1` entry (there are two during a [rotation](#rotate-a-webhook-signing-secret)). 2. Refuse the delivery when `|now - t|` is more than its tolerance. **300 seconds** is a good default; the gateway's own send timeout is 10 seconds, so the tolerance only has to cover clock skew. 3. Compute `hex(HMAC-SHA256(secret, t + "." + raw_body))` over the raw bytes, before any JSON parsing, and accept when it equals **any** `v1` entry, compared in constant time. 4. Discard a repeated `Idempotency-Key` (`:`); within the tolerance that also stops a replayed request. ```python import hashlib, hmac, time def verify(header: str, body: bytes, secrets: list[bytes], tolerance: int = 300) -> bool: parts = [p.split("=", 1) for p in header.split(",")] stamp = next((v for k, v in parts if k == "t"), "") signatures = [v for k, v in parts if k == "v1"] if not stamp.isdigit() or abs(time.time() - int(stamp)) > tolerance: return False for secret in secrets: expected = hmac.new(secret, stamp.encode() + b"." + body, hashlib.sha256).hexdigest() if any(hmac.compare_digest(expected, s) for s in signatures): return True return False ``` ### Send your own headers Some receivers want a header of their own: a bearer token, an API key, a tenant or routing header. With the operator flag `alert_webhook_headers` (off by default; requires `alert_channels`), a `webhook` channel sends up to 10 headers with every delivery, test notifications included: ```yaml features: alert_webhook_headers: true alerting: # The variables a channel made in the console may name. A channel declared # here in YAML may name any variable: you write both. webhook_header_envs: [SIEM_TOKEN] channels: - id: siem name: SIEM kind: webhook url_env: SIEM_WEBHOOK_URL events: [key_created, key_revoked] headers: - name: Authorization value_env: SIEM_TOKEN # the variable holds "Bearer ..." - name: X-Source value: ai-gateway ``` | Key | What it does | | --- | --- | | `headers[].name` | An HTTP header name, 1–64 characters. Names the gateway or HTTP set cannot be used: `Content-Type`, `Content-Length`, `Content-Encoding`, `Host`, `User-Agent`, `Idempotency-Key`, `traceparent`, `tracestate`, `baggage`, `Cookie`, the hop-by-hop headers and any `X-Gateway-*`; a name may appear once | | `headers[].value` | A plain value: up to 1,024 visible ASCII characters, no line break. Shown by the API and the console, so never a secret: a name that looks like a credential (`Authorization`, `Proxy-Authorization`, or one containing `token`, `secret`, `key`, `auth`, `password`, `signature`, `session` or `credential`) is refused with a plain value | | `headers[].value_env` | The name of the gateway's environment variable that holds the value, read at each send. The API and the console show the name and whether it is set, never the value | | `alerting.webhook_header_envs` | The variables a console channel may name in `value_env` (up to 64; default none). Read with the configuration | - **The secret stays out of the API.** A value read from a variable is never stored, logged or returned; the channel list reports only `header_status` (`set`, `allowed`) per header. - **Missing value, no delivery.** When a variable is unset, holds a value that is not safe in a header, or (for a console channel) is no longer listed in `webhook_header_envs`, the delivery fails with `credentials_unavailable` and is retried: the gateway never sends without the header the receiver expects. - **In the console**, **Alert channels → Edit** lists the headers the gateway always sends, read-only, and lets you add rows of a name and a plain value or a variable name; a credential typed as a plain value is refused before it is saved. The API takes the same `headers` in `PUT /api/v1/admin/alert-channels/{id}`. - **Flag off:** headers are kept but not sent, and a write cannot add or change them; a channel's other fields stay editable. ### Rotate a webhook signing secret With `alert_signing_rotation` on, a secret can change without any delivery failing at a receiver that has not switched yet. During the overlap every delivery carries two entries, the new secret first: ```text X-Gateway-Signature: t=1763300000,v1=,v1= ``` A receiver that holds either secret accepts it (step 3 above). Install the new secret at the receiver during the overlap, then end it. **Console channels.** Edit the channel, type the new secret and tick **Rotate**. The API is the same `PUT /api/v1/admin/alert-channels/{id}` with `"signing_secret": "", "rotate_signing_secret": true`. The stored secret becomes the previous one and keeps signing for `alerting.signing_overlap`, measured on the database clock so every replica stops at the same instant. **End the overlap now** (`"end_signing_overlap": true`) drops the previous secret early; it works with the flag off too, so an overlap can always be cut short. | Field | Default | Bounds | Notes | | --- | --- | --- | --- | | `alerting.signing_overlap` | `24h` | `5m`–`720h` | Read when a rotation starts; changing it does not move the end of an overlap already running | - Rotating needs a stored secret (`409 no_signing_secret`) and a new one (`400`); with the flag off it is refused (`403 feature_disabled`). - A second rotation during an overlap retires the older previous secret: only the newest two sign. - A new secret **without** `rotate_signing_secret` replaces the current one at once and drops any overlap, as before; so does removing the secret or changing the channel type. - Both secrets are encrypted with the control-plane key and included in [provider secret re-encryption](/docs/security/keyring-rotation/). The list shows only whether a previous secret overlaps and until when (`previous_signing_secret_configured`, `previous_signing_secret_until`), never a value. Each rotation is audited as `alert_channel.rotate_signing_secret`, and an early end as `alert_channel.end_signing_overlap`. Once an overlap ends, the dispatcher removes the retired ciphertext from storage within one cycle (10 s). - Turning the flag off stops the second signature on the next delivery; the stored previous secret still expires on time. **YAML channels.** Set `previous_signing_secret_env` to the variable that holds the secret being retired, and `signing_secret_env` to the new one; restart. Deliveries carry both signatures while the variable is set and the flag is on. Remove `previous_signing_secret_env` to end the overlap. It must differ from `signing_secret_env`. ```yaml alerting: channels: - id: siem name: SIEM kind: webhook url_env: SIEM_WEBHOOK_URL signing_secret_env: SIEM_WEBHOOK_SECRET_2026_11 previous_signing_secret_env: SIEM_WEBHOOK_SECRET_2026_05 events: [quota_budget_threshold] ``` **Upgrade:** schema migration 168 adds two nullable columns; older replicas ignore them and keep signing with the current secret only, so finish the rollout before rotating. ## How delivery works - Alerts sit in a queue in PostgreSQL. Each replica checks the queue every 10 s; a delivery is attempted by one replica at a time and picked up again if that replica goes down. - Every attempt carries `Idempotency-Key: :` and `X-Gateway-Event`, so the destination can discard repeats. Delivery is at least once: a destination may receive a duplicate if it accepted a request but the acknowledgment was lost. - **Success:** HTTP 2xx. - **Retried:** network error, timeout, 408, 429, 5xx (and 4xx from the mail server), with a 30 s wait that doubles up to 1 h, for up to 8 attempts. - **Fails immediately:** other 4xx (and 5xx from the mail server) and a refused destination. **Retry**, in the console, requeues it. - A new channel only receives alerts created **after** it; the history is not dumped into it. **SSRF protection:** HTTPS is required; every resolved address is validated and dialed directly. Loopback, link-local, special ranges, and private networks (outside `allowed_private_cidrs`) are refused before connecting. Redirects are not followed. ## Limits - Periodic digests summarize eligible queued alerts; they are not spend reports, invoices or proof of complete source history. Provider failures are [operational events](#operational-events), judged per replica. - Delivery history has no automatic retention. - Metric: `gateway_alert_deliveries_total{channel,outcome}` at `/metrics`. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `POST /api/v1/admin/alert-channels/{id}/test` | Sends one synthetic message to the channel now, bounded to 10 seconds | | `GET /api/v1/admin/alert-deliveries` | The delivery outbox, newest first, with each delivery's state and attempts | | `POST /api/v1/admin/alert-deliveries/{channel}/{alert}/retry` | Queues a failed delivery again with a fresh attempt budget | ## See also - [Alert rules and the Alerts screen](/docs/features/alert-rules/). - [Budgets and TPM](/docs/features/budgets-and-tpm/). - [Logs, traces, and metrics](/docs/features/observability/). ## Channel name schema The existing YAML, API and console channel workflow uses names of `1`–`80` Unicode code points (Go runes), without leading/trailing whitespace or control characters. The console preserves valid names containing supplementary Unicode characters; it does not truncate them by UTF-16 code-unit length. The server remains authoritative for invalid-name rejection. Channel IDs retain their existing ASCII pattern and maximum `64` characters. Channel targets and signing references remain private, with the existing version, authorization and audit rules. ## Periodic additive digests Enable `features.alert_digests` (default `false`, requiring `alert_channels`) and opt a channel in with `digest.enabled: true`. Individual budget, overrun and operational notifications continue through their original outbox. A digest never suppresses, acknowledges or replaces them. This is an operator feature; the global alert permissions, encrypted destinations, CSRF, trust rules and retries still apply. ```yaml features: alert_channels: true alert_digests: true alerting: channels: - id: finance-summary name: Finance alerts and summary kind: webhook url_env: FINANCE_WEBHOOK_URL events: [quota_budget_threshold, quota_reservation_overrun] digest: enabled: true interval: 24h max_alerts: 100 ``` | Field | Default | Bounds / meaning | | --- | --- | --- | | `digest` | Absent | Existing individual-only behavior; no serialized member is added to an unchanged channel | | `digest.enabled` | `false` | Opts this channel into additional periodic summaries | | `digest.interval` | `24h` | Whole-second Go duration from1m to168h; omit or use an empty string for the default | | `digest.max_alerts` | `100` | Effective1–500 source references per snapshot; omitted or raw0 uses100; overflow remains for later bounded batches | Use the same `digest` object in `PUT /api/v1/admin/alert-channels/{id}` or **Alert channels** in the console. The existing global `version` protects edits; blank secrets retain their encrypted values. YAML channels remain operator-owned and read-only in the console. A policy may be staged while the global flag is off, with its inactive state shown. The flag never grants administrative rights. ### API update example For an existing **console-created** channel, reuse its current destination without sending it again. Supply your authenticated session cookie file and CSRF token, and the actual channel ID; the command reads the current control version before saving. An intervening edit returns409 for review rather than overwriting it. YAML-owned channels return409 and are edited in YAML. ```sh BASE_URL='http://localhost:8080' : "${COOKIE_JAR:?Set the authenticated console cookie file}" : "${CSRF_TOKEN:?Set the session CSRF token}" : "${CHANNEL_ID:?Set an existing console-created channel ID}" export CHANNEL_ID VERSION=$(curl --fail-with-body -sS -b "$COOKIE_JAR" \ "$BASE_URL/api/v1/admin/alert-channels" | \ python3 -c 'import json,sys; print(json.load(sys.stdin)["version"])') export VERSION python3 -c 'import json,os; json.dump({"version":int(os.environ["VERSION"]),"channel":{"id":os.environ["CHANNEL_ID"],"name":"Finance alerts and summary","kind":"webhook","events":["quota_budget_threshold","quota_reservation_overrun"],"disabled":False,"digest":{"enabled":True,"interval":"24h","max_alerts":100}}},__import__("sys").stdout)' | \ curl --fail-with-body -sS -b "$COOKIE_JAR" -X PUT \ -H "X-CSRF-Token: $CSRF_TOKEN" -H 'Content-Type: application/json' \ --data-binary @- "$BASE_URL/api/v1/admin/alert-channels/$CHANNEL_ID" ``` This replaces that channel's name, kind, subscriptions and digest policy. Set the fields to your reviewed values before running it; leaving out `url` and the signing-secret fields preserves the encrypted values. It does not turn on the global feature flag. Use the existing feature API or **Settings & sources** to enable `alert_digests` separately. ### Windows, ownership and incomplete history First activation starts a durable observation window in PostgreSQL. Original alerts from before activation are excluded, including old alerts whose individual enqueue was delayed. Windows are rolling intervals with explicit UTC timestamps; they are not calendar, billing or budget periods. Digests consume only already queued immutable source alerts. The existing individual enqueue scans at most500 alerts per event type per pass and has a7-day original-event eligibility horizon; a digest does not certify recovery of alerts never enqueued inside that horizon. Each snapshot belongs to one exact owner/group. Budget threshold alerts group by exact subject kind and ID. When an overrun's owner cannot be proven from its durable source, it remains isolated by that source event's identity; a shared model name never combines owners. Other event groups preserve their provable event/subject/team boundary. Counts describe included source alerts, without adding financial amounts or implying ledger settlement. PostgreSQL locks the channel cursor and commits snapshot, source memberships and outbox row together. Unique membership prevents an alert entering another snapshot for that channel. Late committed rows remain eligible rather than disappearing behind a moving timestamp cursor. Each snapshot is additionally capped at192KiB compact JSON, leaving reserve below the256KiB PostgreSQL JSONB text ceiling. Long metadata can therefore produce multiple parts with fewer than `max_alerts` sources, each preserving the exact group/window. A full batch leaves the closed window pending until its remaining eligible rows drain; no remainder is silently dropped. Empty windows send no message. Missing source proof produces an explicit failure, never an invented empty or complete report. ### Pause, edits, delivery and recovery Turning off `alert_digests`, disabling the channel or setting `digest.enabled: false` pauses digest materialization and claims **before** incrementing attempts or leases. Existing individual deliveries retain their own behavior. An attempt already admitted under a captured configuration may finish; disabling is not a recall of an in-flight notification. Cursor, membership, frozen snapshots and failures survive restart. Reenabling resumes bounded catch-up of eligible alerts after first activation, including alerts queued while paused; it does not reset history or replay already included sources. Interval/maximum-size edits take effect in the next window after the current captured-policy window drains. Pending snapshots never change. Reusing an existing channel ID preserves its existing pending history; use a new ID for a separate destination history. Digests reuse the existing at-least-once retries. Their stable delivery ID and `Idempotency-Key` let a destination discard repeats after a lost acknowledgment. A delivery is not externally exactly once. Manual retry does not bypass disabled dispatch. As for individual alerts, a pending delivery uses the channel's current approved destination and secret; changing that destination does not rewrite its snapshot. The generic webhook envelope has `event: alert_digest`, `delivery_id`, `sent_at`, `message` and `digest`. The immutable `digest` contains `id`, `channel_id`, `window_start`, `window_end`, `alert_count`, `group_type`, `group_id`, `sources`, `request_id` and `traceparent`. Each source has `id`, `event`, original `subject`, `created_at`, and optional safely available `request_id`/`trace_id`. `group_type` is `quota_subject/` with the exact subject ID, `event_subject_team/` with compact JSON `[sourceSubject, explicitTeam]`, or `source_event` with the source alert ID when ownership cannot be proven. All overruns use that last conservative fallback. Sources and snapshots carry bounded metadata, without raw source details or amounts; the [OpenAPI contract](/docs/api/) includes their exact schemas. `alert_digest` cannot be selected in the subscription list, preventing summaries of summaries. Slack, Teams, email and PagerDuty receive a bounded summary using their existing transport. Every digest has a stable request ID/trace context for retries; its source IDs link back to the individual alerts. Payloads and secrets remain absent from telemetry. Delivery history adds an optional `digest` summary containing `id`, `window_start`, `window_end`, `alert_count`, `group_type` and `group_id`; ordinary delivery records retain their shape. The console labels summaries separately and uses the same retry action. Channel delivery counts include individual notifications and digests, not unique financial incidents. ### Upgrade Migration116 adds digest cursor, immutable snapshot and membership storage; it does not rewrite existing alert/ledger rows. Run the normal backup/migration procedure before the new gateway when automatic migration is off. Upgrade all replicas before enabling the flag or policy. Older binaries do not understand the new configuration or newer database version; rollback requires the established pre-upgrade backup/configuration procedure. No provider call, external scheduler or cache service is required. # Alert rules **Last updated:** 2026-11-26T01:29:25-03:00 (UTC-3) Alert rules watch the request log and the stored spans for the conditions you call critical, such as a burst of 5xx answers on one model, a guardrail blocking a team, p95 latency over a limit or yesterday's spend at three times its usual level. What a rule finds becomes an **alert** on the **Alerts** screen of the console, where you acknowledge, resolve and mute it, and the rule's channels deliver it to Slack, Microsoft Teams, email, PagerDuty or a webhook. | Flag | Default | What it turns on | | --- | --- | --- | | `alert_rules` | off | Rules (YAML, API and console), their evaluation, the Alerts screen, the backtest and the built-in rules | | `alert_channels` | off | Delivery of the alerts to [alert channels](/docs/features/alerting/); without it alerts are still recorded and shown | Follow this page in order the first time: turn it on, open a channel to the rules, create one rule, backtest it, then read how alerts behave. ## Turn it on ```yaml features: alert_rules: true alert_channels: true # only to deliver alerts alerting: channels: - id: oncall name: On-call kind: slack url_env: ONCALL_SLACK_WEBHOOK_URL events: [alert_rule] # makes the channel selectable by rules alert_rules: tick: 30s # 5s-5m: how often a replica looks for due rules items: - id: checkout-5xx name: 5xx burst on checkout scope: team team_id: checkout mode: scheduled signal: requests filters: - {field: status, op: gte, values: ["500"]} metric: count operator: gte threshold: 10 window: 5m every: 1m severity: critical cooldown: 15m channels: [oncall] ``` The flag is read on every tick and every request, so turning it on or off needs no restart. It requires PostgreSQL (schema migration 207). Rules declared in YAML are read-only in the console; rules created in the console or through the API are stored in PostgreSQL and take effect on every replica within one `tick`. ## Open a channel to the rules A rule delivers only to the channels it names. A channel becomes selectable when it subscribes to the `alert_rule` event; nothing is fanned out to it by the subscription alone. | Channel field | Default | What it does | | --- | --- | --- | | `events: [alert_rule]` | absent | Lets rules name this channel | | `rule_organizations` | empty | Organization IDs (up to 64) whose administrators may attach the channel to their organization's rules and to the rules of its teams | | `rule_teams` | empty | Team IDs (up to 64) whose administrators may attach the channel to that team's rules | Global rules may use any channel that has the event. A team or organization rule may use a channel only when its team or organization is listed, because its alerts carry that tenant's data. Set both lists in YAML, in `PUT /api/v1/admin/alert-channels/{id}` or in **Alert channels** in the console, where the two fields appear once `alert_rule` is ticked. ```yaml alerting: channels: - id: acme-oncall name: Acme on-call kind: pagerduty url_env: ACME_PAGERDUTY_URL events: [alert_rule] rule_organizations: [acme] ``` PagerDuty opens one incident per alert (`dedup_key` `alert_rule:`) with the rule's severity, and closes it when the alert resolves. A generic webhook receives the usual envelope with `event: alert_rule` and an `operational_event.detail` holding `alert_id`, `rule_id`, `rule`, `severity`, `state` (`firing` or `resolved`), `scope`, `team` or `organization`, `group`, `title`, `metric`, `value`, `threshold` and `window`. [Digests](/docs/features/alerting/#periodic-additive-digests) include these alerts like any other. ## The rule model Every rule has an identity and a scope, a condition, and how it notifies. | Field | Default | Bounds and meaning | | --- | --- | --- | | `id` | required in YAML | Lower case, up to 64 characters. The gateway assigns the ID of a stored rule (`ar_…`) | | `name` | required | 1–120 characters | | `description` | empty | Up to 500 characters; say what to do when it fires | | `scope` | required | `global` (every team), `organization` (what was recorded in `organization_id`: the requests and spans that ran in it, whichever team made them) or `team` (what `team_id` recorded in the organization it is in now) | | `disabled` | `false` | Stops evaluation without deleting the rule | | `mode` | required | `realtime` or `scheduled` | | `signal` | required | `requests` (the request log) or `spans` (the [span store](/docs/features/traces/), which needs `span_store`) | | `filters` | none | Up to 10; every one must match | | `group_by` | none | One field: the condition is judged per value and each value gets its own alert | | `query` | none | With `trace_query`: a query in the [query language](/docs/features/query-language/), joined to the filters by AND, on a scheduled rule (`alerting.alert_rules.items[].query` in YAML) | | `severity` | `warning` | `info`, `warning` or `critical` | | `cooldown` | `15m` | `1m`–`168h`: minimum time between two notifications of the same rule and group | | `channels` | none | Up to 8 channel IDs open to the rule's scope | ### Filters A filter is `{field, op, values}`. `eq` (the default) and `neq` take 1–20 values and mean *any of* and *none of*. `gt`, `gte`, `lt` and `lte` take one whole number and apply to numeric fields. | Signal | Text fields | Numeric fields | | --- | --- | --- | | `requests` | `team`, `model`, `requested_model`, `provider`, `operation`, `status_class` (`2xx`…`5xx`), `error_code`, `origin`, `key_id`, `principal`, `end_user`, `guardrail`, `timeout_kind`, `service_tier` | `status`, `duration_ms`, `input_tokens`, `output_tokens`, `attempts` | | `spans` | `team`, `kind`, `subkind`, `name`, `origin`, `status` (`ok`, `error`, `unset`), `error_code`, `model`, `provider`, `key_id`, `principal` | `http_status`, `duration_ms` | Values are plain identifiers (letters, digits and `. _ : / @ -`, up to 200 characters). A rule never reads prompts, answers or headers: only the metadata the request log and the spans already hold. `group_by` takes any text field above except `end_user` and `service_tier`, plus `status` and `http_status`. ### A query beside the filters With [`trace_query`](/docs/features/query-language/) on, a scheduled rule you define may also carry a `query` in the gateway's query language, joined to the filters by AND: `query: "canary.side:canary status:error -origin:evaluation"`. `signal: requests` reads the request log's fields, including span fields (the requests that have such a span) and evaluation terms; `signal: spans` reads the span fields (`child.` and `parent.` are refused). A rule has no reader, so a text search of captured content is refused. A realtime or built-in rule keeps its filters. If `trace_query` is turned off, a rule with a query is not scanned (state `query_disabled`) rather than run without it. See [the query language in an alert rule](/docs/features/query-language/#in-an-alert-rule). ### Realtime rules ```yaml - id: guardrail-blocks name: Guardrail blocked a request scope: global mode: realtime signal: requests filters: - {field: error_code, values: [guardrail_blocked]} group_by: team severity: warning ``` A realtime rule has filters only (at least one). Each request is matched in memory when its request log row is recorded, and each span when the span writer keeps it; a match is offered to a bounded queue (2,048) and never waits on the database, so the request path does no I/O. One writer per replica folds matches by rule and group for one second and writes each fold once, so a burst of 500 matches a second costs one write per group, with the count added to the alert. A match that finds the queue full is dropped and counted (`gateway_alert_rule_alerts_total{transition="dropped"}`). Use a realtime rule for conditions where one occurrence matters. For "more than N in a window", rates and latency, use a scheduled rule. ### Rules over prompt events With [`prompt_events`](/docs/features/prompt-registry/#prompt-events) on, `signal: prompts` matches each change of the prompt registry as it is recorded: a team's rule sees its own team's prompts, an organization's rule the prompts of its teams, a global rule every prompt. It is realtime only (a scheduled one is refused) and has no backtest (`409 backtest_unavailable`). | Field | Type | What it is | | --- | --- | --- | | `event` | text | `prompt_created`, `prompt_version_published`, `prompt_deleted` or `prompt_label_deployed` | | `prompt_id` | text | The prompt | | `team` | text | The prompt's owning team | | `path` | text | How the change was made: `console`, `api` or `yaml` | | `label` | text | The label a `prompt_label_deployed` event moved (empty otherwise) | | `revision` | number | The revision published (or the last one, for a creation or a deletion) | ```yaml - id: checkout-prompt-publications name: A checkout prompt was published scope: team team_id: checkout mode: realtime signal: prompts filters: - {field: event, values: [prompt_version_published]} group_by: prompt_id severity: info channels: [checkout-oncall] ``` With the flag off the rule is refused when saved (`409 feature_disabled`) and a stored one stops matching. ### Rules over finished experiments With [`experiment_traces`](/docs/features/experiment-traces/#experiment-finished-alert) on, `signal: experiments` matches each experiment run of its own team or organization as it finishes (`completed`, `failed` or `canceled`). Realtime only, no backtest (`409 backtest_unavailable`); with the flag off it is refused when saved (`409 feature_disabled`). | Field | Type | What it is | | --- | --- | --- | | `team` | text | The run's team | | `status` | text | `completed`, `failed` or `canceled` | | `dataset_id` | text | The dataset the run ran | | `model` | text | The alias the items called | | `suite_id` | text | The regression suite of a suite run | | `verdict` | text | A suite run's verdict: `passed`, `failed` or `error` | | `items` | number | The run's items | | `failed` | number | The items whose model call failed | | `duration_ms` | number | From the run's creation to its end | ```yaml - id: release-gate-failed name: The release gate failed scope: team team_id: checkout mode: realtime signal: experiments filters: - {field: verdict, values: [failed]} severity: warning channels: [checkout-oncall] ``` ### Scheduled rules and scans ```yaml - id: slow-chat name: Chat p95 above 8 s scope: organization organization_id: acme mode: scheduled signal: requests filters: - {field: operation, values: [chat]} metric: p95_latency_ms operator: gt threshold: 8000 min_samples: 50 window: 15m schedule: "*/5 * * * *" group_by: model ``` | Field | Default | Bounds and meaning | | --- | --- | --- | | `metric` | `count` | Requests: `count`, `error_count`, `error_rate`, `avg_latency_ms`, `p50_latency_ms`, `p95_latency_ms`, `p99_latency_ms`, `spend_usd`, `total_tokens`. Spans: the first seven | | `operator` | `gte` | `gt`, `gte`, `lt` or `lte` | | `threshold` | `1` for a count | `0`–`1e15`; `error_rate` is a ratio from 0 to 1. A count with `lte 0` is a "no traffic" rule. Any other metric needs a threshold: `gte 0` is always true and is refused | | `min_samples` | `0` | Matching rows a rate or latency needs before it is judged; below it the scan reports no data | | `window` | `5m` | `1m`–`744h`, whole seconds: the time range each scan reads | | `every` | `1m` | `30s`–`24h`: a fixed interval | | `schedule` | none | A five-field cron expression in **UTC** (`minute hour day-of-month month day-of-week`, with `*`, numbers, ranges `a-b`, lists `a,b` and steps `*/n`); set `schedule` or `every`, not both | A scan is one bounded aggregate over the window: at most 50 groups (the highest values, or the lowest for `lt` and `lte`), 5 sample rows per alert, a 10-second statement timeout and a 15-second budget per rule. Metrics count every matching row, helper calls and fallback attempts included; add `{field: origin, values: [app]}` to count client requests only. An error is a status of 400 or more, or an answer cut after it started. `spend_usd` sums known valuations: when no matching row is priced it is unknown, never zero, and the rule does not fire. **Where a scan reads.** Requests are read from the [analytics store](/docs/features/analytics-store/) while analytics may read it (`analytics_store_usage` on, the copy complete and within its maximum lag), and from PostgreSQL otherwise or when that read fails. `spend_usd` always reads PostgreSQL, where the valuations are. Spans are read from the analytics store when it is the span engine, and from PostgreSQL otherwise. Each alert and each rule's last scan say which (`read_store`). The same scan returns the same rows on both engines. **One replica per scan.** Every replica looks for due rules each `tick`, and a rule's lease on the database clock lets one replica scan it at a time; a lease left by a crashed replica expires after two minutes. A scan that outlives its lease writes nothing. A replica runs at most 50 scans per tick, the longest overdue first, at most 10 of one team or organization, and stops starting scans once they have used the tick itself. A cron rule first runs at its next slot, not when it is created; a schedule that can never run (February 30) is refused. A scheduled rule **resolves its own alerts**: when a scan completes and a group no longer meets the condition, its alert is resolved by `system` and, when the alert had notified, a `resolved` message goes to the rule's current channels. ## Backtest before you save **Backtest 24 h** in the rule editor (`POST /api/v1/admin/alert-rules/preview`) answers what the rule would have matched in the last 24 hours, without saving it or notifying anyone: - a realtime rule: the matches per hour; - a scheduled rule: the value of its metric on consecutive windows of its own `window` (at least five minutes; one window when it is 24 hours or longer), and in how many it would have fired. This approximates the rule's sliding evaluation; a rule with a window under five minutes is judged on five-minute windows, so its counts read higher than a real scan's; - a built-in rule: what it would raise if it ran now; - up to 20 of the newest matching rows, each a link to its request or trace. Tune the threshold until the number of firing windows is what you would want to be paged for, then save. ## Built-in rules Five rules are ready-made. None exists until you turn it on, for the scope you choose, under **Rules → Built-in rules** or by declaring a rule with `builtin:`. Each then behaves as an ordinary rule: tune it, mute it, delete it. | `builtin` | Fires when | Defaults | | --- | --- | --- | | `spend_spike` | spend of the last 24 hours ≥ `multiplier` × the daily baseline and at least `minimum_increase` USD above it | 3×, 50 USD | | `traffic_spike` | requests of the last 24 hours, the same way | 10×, 1,000 requests | | `latency_spike` | p95 latency of the last 24 hours against the average daily p95 | 3×, 500 ms, `min_samples` 100 | | `error_rate_spike` | error rate of the last 24 hours against the average daily error rate | 3×, 0.05, `min_samples` 100 | | `deprecated_model_traffic` | a deprecated model received requests in the last 30 days | one alert per model | ```yaml - id: spend-by-team name: Daily spend spike scope: global builtin: spend_spike multiplier: 2.5 # 1.1-1000 minimum_increase: 20 # in the metric's unit baseline_days: 14 # 2-28, default 7 group_by: team channels: [finance] ``` The baseline is the average of the `baseline_days` full days before the last 24 hours, per group. A group needs two baseline days with data before it is judged. For spend and traffic a day without requests since the first day with data counts as zero; for latency and error rate only days with requests are averaged. Spike rules run hourly (cron `5 * * * *`) with a 24-hour cooldown unless you set `every`, `schedule` or `cooldown`. Each alert carries the daily series it was judged on. `deprecated_model_traffic` watches the models you declare and, with the [model registry](/docs/features/model-registry/) on, the gateway models whose upstream model a source publishes with a deprecation date: ```yaml - id: deprecated name: Traffic to deprecated models scope: global builtin: deprecated_model_traffic deprecated_models: - {model: gpt-4-0613, date: "2026-12-01"} - {model: legacy-chat} ``` A declared name is a gateway model ID or an upstream model name; an upstream name covers every gateway model that targets it. The alert of each model shows its requests per day for the last 30 days, the last request, the deprecation date and where the deprecation came from (`declared`, `registry_scheduled` or `registry_date_passed`). The registry is advisory and may be unreachable: the alert then says `registry: unavailable`, only declared models are checked, and no alert is resolved by that run. It runs daily at 06:00 UTC and resolves a model's alert once 30 days pass without traffic. ## The Alerts screen **Alerts** in the console navigation has two tabs. **Alerts** lists what the rules found, newest first, with filters by state (active, open, acknowledged, resolved), severity and text. Each alert shows its severity, state, owner, rule, group, how many times it was seen and when. **Details** shows the value against the threshold or baseline, the window, the filters, the daily series of a built-in rule and the matched samples; **Request** opens a sample's [request journey](/docs/features/observability/#request-journey), **Trace** its [trace](/docs/features/traces/), and **Matching logs** opens the request log filtered to the alert's team, window and filters. | Action | Effect | | --- | --- | | Acknowledge | Marks an open alert as being handled; it stays active and keeps counting | | Resolve | Closes the alert. A notified alert of a rule sends `resolved` to the rule's current channels. A later match opens a new alert | | Mute (1 hour to 7 days in the console, `1m`–`720h` in the API) | The alert keeps counting but sends no notification until the mute ends | | Unmute | Ends the mute | **Rules** lists every rule you may see with what it watches, when it runs, its last scan (`ok`, `firing`, `no data` or `error` with its class) and its next run. From it you create, edit, mute and delete rules and turn on the built-in ones. Deleting a rule resolves its active alerts and keeps them in the history. ### How an alert lives - **One active alert per rule and group.** A new finding adds to the open or acknowledged alert (`occurrences`, `last_seen_at`, the latest detail); it never opens a second one. This holds across replicas. - **Notifications.** The first finding notifies. Further findings notify again only after `cooldown` since the last notification of that rule and group, also across a resolve and reopen. A muted alert or a muted rule records and does not notify. - **Retention.** Resolved alerts are deleted 90 days after they were resolved. Active alerts are kept. ## Who sees what Access is by permission inside the roles, scoped to the caller's teams and organization: | Permission | Allows | Built-in roles | | --- | --- | --- | | `alert_rules:read` | Listing alerts and rules of your teams, and of the organization you administer | admin, viewer, operator, team_admin, team_viewer, user | | `alert_rules:manage` | Creating, editing, muting and deleting rules; acknowledging, resolving and muting alerts; the backtest | admin, team_admin (its administered teams; an organization admin also its organization) | | `alert_rules:global` | Widens both to every team, every organization and the global rules | admin, viewer and operator (read only) | - A **global** rule sees every team's traffic and its alerts name teams, so only sessions with `alert_rules:global` see or change it. - An **organization** rule aggregates the organization's teams: its alerts are visible to that organization's administrators, not to members of one team. - **When a team moves to another organization**, its rule stops counting what it recorded under the former one, the former organization's rule keeps counting that and nothing the team does since, and the new organization's rule counts the team from the move on. A row that records no organization (`organizations` off) stays with its team. A scheduled rule's `query` follows the rule: its evaluation and span terms are resolved over the same rows the scan counts, so an organization's rule matches the results a team that left recorded there and a team's rule only those of its organization of now. The alerts themselves follow: `GET /api/v1/admin/alerts` shows a team's reader the alerts raised while the team was in its current organization, and shows the former organization's administrators the ones raised there, which they read (in the list and among the records of a trace) and cannot acknowledge, resolve or mute. An alert raised before the upgrade records no organization and stays with its team. See [when a team moves](/docs/features/organizations/#when-a-team-moves). - A **team** rule and its alerts are visible to the team's members and managed by its administrators. - Anything outside your scope answers `404`, the same as a missing object, and a filter never widens it. Channels of other tenants are not listed, and naming one answers the same `422` as a channel that does not exist. - A [custom role](/docs/features/custom-roles/) narrows these and is read-only, like every custom role: it may keep `alert_rules:read` (and, based on `viewer` or `operator`, `alert_rules:global`), never `alert_rules:manage`. One based on `viewer` without `alert_rules:global` sees no global object. Every write is audited: `alert_rule.create`, `.update`, `.delete`, `.mute`, `.unmute`, and `alert.acknowledge`, `.resolve`, `.mute`, `.unmute`. ## Alerts other features raise Some features raise their own alerts through the same screen, states, cooldown and channels: an alert's `source` names the raiser (`rule` for a rule of yours). [Topics](/docs/features/topics/#findings) raises findings with the sources `topics` (a topic changed) and `insights` (cost and reliability detectors), and its budget and provider pauses with `topics`. Filter the list by raiser with `GET /api/v1/admin/alerts?source=topics`. ## Alerts as telemetry An alert is part of the gateway's own telemetry, not a separate system. - **Logs.** Each transition (`opened`, `acknowledged`, `resolved`) writes an `alert_rule` line to stdout and to [OTLP logs](/docs/features/observability/) with `alert_id`, `rule_id`, `rule`, `source`, `severity`, `scope`, `team`, `organization_id`, `group`, `state`, `occurrences`, `title`, `value` and, when a row matched, `matched_request_id`, `matched_trace_id` and `matched_span_id`. Join them with the request log and the traces by those IDs. - **Metrics**, at `/metrics` and over OTLP: | Series | Labels | | --- | --- | | `gateway_alert_rule_alerts_total` | `transition` (`opened`, `repeated`, `notified`, `acknowledged`, `resolved`, `dropped`), `severity`, `scope`, `source` | | `gateway_alert_rule_scans_total` | `outcome` (`ok`, `firing`, `no_data`, `error`, `lost_lease`) | | `gateway_alert_deliveries_total` | `channel`, `outcome` (the existing delivery counter) | Rule, team and organization IDs are never metric labels. ## Raising alerts from another feature Evaluation monitors and other gateway features raise their alerts through the same interface, so they land on the same screen with the same lifecycle. Inside the gateway: ```go alert, err := s.RaiseAlertSignal(ctx, gateway.AlertSignal{ Source: "evaluation_monitor", // lower snake case; the alert's source MonitorID: monitor.ID, // up to 64 characters Name: monitor.Name, TeamID: monitor.TeamID, // the alert is team-scoped Group: evaluator.ID, // optional: one alert per group Severity: "warning", // info, warning or critical Title: "Pass rate 0.62 below 0.80 over 1h", Detail: map[string]any{"metric": "pass_rate", "value": 0.62, "threshold": 0.8, "operator": "lt"}, Cooldown: time.Hour, // 0: 15m Channels: monitor.Channels, // only those open to the team receive it }) // when the monitor's condition clears (firing lists the groups still failing): err = s.ResolveAlertSignal(ctx, signal, firing) ``` `RaiseAlertSignal` folds into the active alert of `Source`, `MonitorID` and `Group`, honors the cooldown and the alert's mute, and queues deliveries only for channels open to the team. With `alert_rules` off it does nothing and returns `ErrAlertRulesDisabled`. `Detail` is bounded metadata (12 KiB), never content; the screen understands `metric`, `value`, `threshold`, `operator`, `window_from`, `window_to`, `group_by`, `group` and `samples`. ## Limits - Realtime rules are matched per replica from what that replica served. Their findings fold into one alert in PostgreSQL, but a match queued on a replica that crashes within the one-second fold is lost; a scheduled rule over the same filters is the durable check. - A scheduled rule sees a request once its request log row is written, and reads the analytics store up to that copy's lag behind. - With `group_by`, a scan judges the 50 highest groups (the 50 lowest for `lt` and `lte`) and opens at most 20 alerts per scan; the other groups that meet the condition keep the alerts they have. A scan that returned 50 groups does not resolve alerts, since a missing group is then not proof that it cleared. A group with no matching row returns nothing, so a grouped "no traffic" rule cannot see a silent group: use one rule per group, or an ungrouped rule. - A rule deleted or disabled stops matching on the other replicas within one `tick`; a stored rule's queued matches are discarded once it is deleted. - Realtime alerts do not resolve by themselves: resolve them on the screen. Scheduled and built-in alerts resolve when the condition clears. - The gateway stores at most 50 rules per team, per organization and for the global scope, 500 in all; YAML holds at most 200. A YAML rule may name only a YAML channel that is open to its scope. - The alert list pages by last occurrence: an alert that fires again while you page moves to the top, so a later page can miss it until you refresh. - Spans rules need `span_store`; with it off a scheduled span rule reports `span_store_disabled` on each scan and a realtime one never matches. - A rule cannot change its scope, organization or team; create another rule. ## YAML reference Every key of `alerting.alert_rules`, with where it is explained above. The API and the console take the same fields under the same names. | Key | Default | What it is | | --- | --- | --- | | `alerting.alert_rules.tick` | `30s` | How often each replica looks for due scheduled rules and reloads the realtime ones, `5s`–`5m` | | `alerting.alert_rules.items[].id` | required | The rule's identifier in YAML, lower case, up to 64 characters | | `alerting.alert_rules.items[].name` | required | Display name of the rule, 1–120 characters | | `alerting.alert_rules.items[].description` | empty | Free text shown with the rule, up to 500 characters | | `alerting.alert_rules.items[].scope` | required | Whose traffic the rule reads: `global`, `organization` or `team` | | `alerting.alert_rules.items[].organization_id` | empty | The organization of an `organization` rule | | `alerting.alert_rules.items[].team_id` | empty | The team of a `team` rule | | `alerting.alert_rules.items[].disabled` | `false` | Stops the rule without removing it | | `alerting.alert_rules.items[].mode` | required | `realtime` or `scheduled`; a built-in rule is always scheduled | | `alerting.alert_rules.items[].signal` | required | `requests` or `spans`; a built-in rule always reads requests | | `alerting.alert_rules.items[].filters[].field` | required | The field a filter compares, from the [filter table](#filters) | | `alerting.alert_rules.items[].filters[].op` | `eq` | The comparison: `eq`, `neq`, `gt`, `gte`, `lt` or `lte` | | `alerting.alert_rules.items[].filters[].values` | required | The values compared, 1–20 for `eq` and `neq`, one number otherwise | | `alerting.alert_rules.items[].metric` | `count` | The aggregate a scheduled rule judges | | `alerting.alert_rules.items[].operator` | `gte` | How the metric compares with the threshold | | `alerting.alert_rules.items[].threshold` | `1` for a count | The value the metric is compared with | | `alerting.alert_rules.items[].min_samples` | `0` | Matching rows a rate or latency needs before it is judged | | `alerting.alert_rules.items[].window` | `5m` | The time range each scan reads, `1m`–`744h` | | `alerting.alert_rules.items[].group_by` | none | One field whose every value is judged and alerted separately | | `alerting.alert_rules.items[].schedule` | none | A five-field cron expression in UTC for when the rule runs | | `alerting.alert_rules.items[].every` | `1m` | A fixed interval between runs, `30s`–`24h` | | `alerting.alert_rules.items[].severity` | `warning` | `info`, `warning` or `critical`, shown and delivered with the alert | | `alerting.alert_rules.items[].cooldown` | `15m` | Minimum time between two notifications of one rule and group | | `alerting.alert_rules.items[].channels` | none | Up to 8 alert channel IDs that receive the rule's alerts | | `alerting.alert_rules.items[].builtin` | none | Turns the item into one of the [built-in rules](#built-in-rules) | | `alerting.alert_rules.items[].multiplier` | per built-in | How many times the baseline a spike must reach, `1.1`–`1000` | | `alerting.alert_rules.items[].minimum_increase` | per built-in | How far above the baseline a spike must be, in the metric's unit | | `alerting.alert_rules.items[].baseline_days` | `7` | Full days averaged into a spike rule's baseline, 2–28 | | `alerting.alert_rules.items[].deprecated_models[].model` | required | A gateway model ID or upstream model name declared deprecated | | `alerting.alert_rules.items[].deprecated_models[].date` | empty | Its published deprecation date, `YYYY-MM-DD`, shown in the alert | ## Admin API routes Every route needs a console session or an admin Bearer token, the permission shown and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | Permission | What it does | | --- | --- | --- | | `GET /api/v1/admin/alerts` | `alert_rules:read` | Alerts newest first with `state`, `severity`, `rule_id`, `team`, `organization`, `scope`, `q`, `limit` (1–200) and `cursor`, and the counts by state | | `GET /api/v1/admin/alerts/{id}` | `alert_rules:read` | One alert | | `POST /api/v1/admin/alerts/{id}/{action}` | `alert_rules:manage` | `acknowledge`, `resolve`, `mute` (`{"duration":"1h"}`) or `unmute` | | `GET /api/v1/admin/alert-rules` | `alert_rules:read` | Rules (`alert_rules.items`, with the effective `alert_rules.tick`) and their last scan, the catalog of fields, metrics and built-in rules, and the channels you may attach | | `POST /api/v1/admin/alert-rules` | `alert_rules:manage` | Creates a rule; the gateway assigns its ID | | `POST /api/v1/admin/alert-rules/preview` | `alert_rules:manage` | The 24-hour backtest of an unsaved rule | | `PUT /api/v1/admin/alert-rules/{id}` | `alert_rules:manage` | Replaces a stored rule: `{"version": n, "rule": {...}}` | | `DELETE /api/v1/admin/alert-rules/{id}?version=n` | `alert_rules:manage` | Deletes a stored rule and resolves its active alerts | | `POST /api/v1/admin/alert-rules/{id}/mute` | `alert_rules:manage` | Mutes a rule (`{"duration":"24h"}`) or unmutes it (`{}`) | ```sh curl --fail-with-body -sS -b "$COOKIE_JAR" -X POST \ -H "X-CSRF-Token: $CSRF_TOKEN" -H 'Content-Type: application/json' \ --data-binary '{"name":"5xx burst","scope":"team","team_id":"checkout","mode":"scheduled","signal":"requests","filters":[{"field":"status","op":"gte","values":["500"]}],"metric":"count","operator":"gte","threshold":10,"window":"5m","every":"1m","severity":"critical","channels":["oncall"]}' \ "$BASE_URL/api/v1/admin/alert-rules" ``` ## Upgrade Migration 207 adds three tables (`gateway_alert_rules`, `gateway_alert_rule_state`, `gateway_alerts`) and changes no existing row. Upgrade every replica before turning the flag on: an older replica neither matches realtime rules nor understands the `alert_rule` event of a channel. Turning the flag off stops evaluation and hides the screen; rules and alerts stay stored. ## See also - [Alert channels, operational events and digests](/docs/features/alerting/). - [Logs, traces and metrics](/docs/features/observability/) and the [Prometheus alert rules](/docs/features/observability/#alert-rules), which page from metrics when the gateway itself is unhealthy. - [Access control](/docs/features/access-control/). # Durable receipts **Last updated:** 2026-11-23T09:00:15-03:00 (UTC-3) Normal usage recording is best effort: if the database fails midway, an event can be lost. With **durable receipts**, the gateway writes a receipt to PostgreSQL **before** calling the provider. If it cannot write it, it does not call: it responds `503`. Every call that went out to the provider therefore has a record. Flag: `durable_usage`, which requires `usage_analytics` and PostgreSQL. Receipts are the foundation of [budgets and TPM](/docs/features/budgets-and-tpm/), which depend on knowing, with certainty, what was sent. ## How it works 1. The key is authenticated and authorized (scopes, team policy, RPM, model). 2. The gateway writes the receipt and only then checks the cache or calls the provider. The response carries the ID in `X-Gateway-Usage-Receipt`. 3. When the response ends, the receipt and the usage event are finalized together, in one transaction. | State | Meaning | | --- | --- | | `pending` | The request was accepted; the final outcome has not been recorded yet | | `completed` | The gateway recorded the final observation. It does **not** mean HTTP success or a reconciled charge | | `indeterminate` | The outcome could not be proven (crash, cancellation, a stream with no recognized end). It does **not** mean the provider did not process it | The receipt stores identities, team, route, alias, correlation IDs, timestamps and state; after the end, the provider, status and reported counters. It **does not store** the prompt, the response, authorization headers or credentials. - Each request has its own internal ID: the same `X-Request-Id` can appear in several receipts. - Finalizing twice with the same data does not duplicate the event; divergent data is rejected. - In streams, the gateway recognizes the end event of Chat, Messages, Responses and Gemini. Without a recognized end, the receipt stays `indeterminate`, and the content is still delivered. - Once the provider's answer has ended (the recognized end event of a stream, or the end of a JSON body), a client that disconnects or stops reading does not make the receipt `indeterminate`: the provider's outcome is already known. A disconnect before that end does. ## Realtime sessions A [realtime](/docs/features/realtime/) session has **one receipt per response**, not one per session: - The receipt is written when the response is admitted (on the client's `response.create`, or on `response.created` for a response the provider starts by itself), before the request reaches the provider. If it cannot be written, the response is refused with an `error` event (`durable_usage_unavailable`) and the session stays open. - It is completed on `response.done`, with the reported usage, whatever the response's status (`completed`, `cancelled`, `failed`, `incomplete`). A `response.done` whose counters cannot be validated makes it `indeterminate`. - A response still running when the session ends (client disconnect, provider close, session ceiling, drain, emergency stop) makes it `indeterminate`, and its budget reservation stays held. - A response the provider refused before starting (an `error` naming the `event_id` of the `response.create`) is completed with status 400 and no tokens. - Every receipt of a session carries the upgrade's `request_id`; the upgrade itself has no receipt, since nothing is billed until a response starts. ## Recovery A live operation owns its pending receipt. Each replica tracks its active request contexts and, for Realtime, each unfinished response. The receipt follows that actual lifecycle; it has no second timer based on the alias's ordinary `request_timeout`. Renewal does not extend the operation's own timeout. Opt-in [stream clocks](/docs/features/stream-timeouts/) can allow a healthy stream beyond ordinary request_timeout; its receipt still follows that actual context, with no second deadline or replay. Timeout classification does not by itself prove a charge or make an incomplete outcome complete. - The existing lease is 5 minutes; the replica renews its active pending receipts every one-third of that lease (100 seconds), in bounded batches of up to 1,000. It renews before the worker's initial recovery pass. - Recovery still runs every 30 seconds on each replica, in batches of up to 500. - Only `pending` rows renew. A completed or recovered receipt is never revived by a heartbeat, and final observations/fingerprints are not rewritten. - Normal completion, actual context cancellation and Realtime response/session termination release local ownership. Cleanup also runs if finalization fails, recording is bypassed or a panic unwinds the handler. An already-running renewal may finish after release, so abandonment is measured from the last successful renewal, not exactly from disconnect. - A `pending` receipt whose lease expired without a final observation becomes `indeterminate` in a recovery pass. An active stream can therefore outlive five minutes when its heartbeats succeed; a crashed replica stops renewing. **Nothing is ever resent to the provider.** - If the database goes down after the send, the response is still delivered to the client; renewal/finalization may fail and recovery conservatively marks an expired unproven outcome indeterminate. A late original final observation still uses the existing idempotent finalization. - Turning off the flag makes new requests go back to best-effort mode; recovery of the old ones continues. ## Diagnosing a long-running receipt Use the receipt's internal ID together with its `request_id` and `trace_id`; a repeated client request ID is not a unique receipt. A receipt older than five minutes can be legitimately pending while its handler or Realtime response is still active. Investigate `durable_lease_renew_failed`, database connectivity and worker shutdown before concluding that it was abandoned. The recovery state alone does not establish whether the provider charged and must never trigger inference replay or release an unknown budget reservation; use the separate [financial proof/reconciliation](/docs/features/quota-finance/). ## Single charge Without it, a request protected by a [budget or TPM limit](/docs/features/budgets-and-tpm/) makes three separate durable commits after the provider answers: the quota measurement, the quota settlement and the receipt's finalization. Each has its own timeout, and a failure between them leaves one side recorded: the budget charged with no usage event, or a usage event whose reservation stays `reserved` until a manual reconciliation. Flag: `single_charge_settlement` (operator control, off by default; requires `budget_limits` or `tpm_limits`, and the usage and quota stores on the same PostgreSQL). With it on: - **The receipt carries its reservation.** When the request is admitted under a quota reservation, the receipt is written with that reservation's ID, and the usage event repeats it (`quota_reservation_id`). The link is part of the receipt's captured identity: a final event that names another reservation is refused. An asynchronous video job is not linked; it still settles at its terminal proof. - **One transaction.** When the answer ends, the measurement, the settlement of every counter of the reservation (team, key, end user, group, global, provider, customer organizations, teams, members and their per-model allowances), the usage event, its valuation and the receipt commit together, or none of them does. The settlement decision is the same as without the flag: the approved rate captured at admission, `unknown` when the answer does not prove a priced measurement, `released` when no provider attempt started. - **Refusals do not lose the observation.** A measurement the reservation refuses (another response model, an unpriced category, a unit cost the approved rate does not accept) settles the reservation as `unknown`, holding its reserved amount, instead of leaving it open. A reservation another decision already closed (a [reconciliation](/docs/features/quota-finance/), or an earlier settlement) keeps that decision; the receipt still records its observation, with `charge_resolution: decided_elsewhere`, and a late owner's exact measurement is still recorded as evidence for a reconciliation. - **A failed transaction falls back to separate writes, without losing the observation.** If the single transaction fails (database error, timeout, deadlock after one retry), nothing of it commits. The request then records the usage event, its valuation and the receipt in their own transaction, keyed on the receipt: its final fingerprint makes a repeat, or a single transaction that did commit after all, a no-op, never a second event. It then writes the measurement and the settlement in their own transactions, exactly as without the flag, so a failed write never turns an exact charge into a held one; only an open reservation moves its counters, so it is never charged twice. The receipt is `completed`, or `indeterminate` when the outcome really is unknown. Whatever the database still refuses stays open for the recovery worker. Nothing is settled from memory after a crash and the provider is never called again. - **The recovery worker resumes what stays open.** The durable usage recovery pass (every 30 seconds on each replica) first marks expired leases `indeterminate`, as before, and then resumes the final receipts (`completed` or `indeterminate`) whose linked reservation has no recorded decision and that have not changed for the grace period. When the reservation is still `reserved` and a quota measurement was recorded for it, the worker settles from that measurement (`recovered_measurement`); with no measurement it holds the reservation as `unknown` (`recovered_held`), which keeps the reserved amount charged until a reconciliation; a reservation already decided is recorded as `decided_elsewhere`. Each receipt is its own transaction, locked with `SKIP LOCKED`, so replicas run it at once without double settlement; a resumed receipt is never resumed again, and one that fails waits another grace without stopping the others. A late owner that finalizes within the grace commits its own exact charge; one that comes after the worker records its event and keeps the worker's decision. The pass also runs with the flag turned off, for receipts linked while it was on. | `charge_resolution` | Meaning | | --- | --- | | `finalized` | Settled in the receipt's own finalization transaction | | `decided_elsewhere` | The reservation was already closed (reconciliation, earlier settlement) or archived | | `recovered_measurement` | The worker settled it from the recorded quota measurement | | `recovered_held` | No measurement proves the usage; held as `unknown` at the reserved amount | The worker's bounds are boot configuration (restart to change): ```yaml charge_accounting: recovery_batch: 100 # 1-500 receipts per recovery pass recovery_grace_seconds: 300 # 60-86400; a final receipt waits, unchanged, this long ``` | Key | Default | What it does | | --- | --- | --- | | `charge_accounting.recovery_batch` | `100` | How many receipts one recovery pass resumes, 1–500 | | `charge_accounting.recovery_grace_seconds` | `300` | How long a final receipt waits unchanged before the worker resumes its open reservation, 60–86400; a late request can still settle its own charge in that time | Both are boot settings (restart to change), shown read-only by the API and the console; `0` takes the default. `GET /api/v1/admin/durable-usage` then adds `quota_reservation_id` and `charge_resolution` to each linked receipt and a `charge_accounting` object with the effective bounds under their YAML names (`recovery_batch`, `recovery_grace_seconds`, `background_poll_seconds`, `background_max_age_seconds`) and a `single_charge` block with the filtered counts (`linked`, `awaiting_recovery`, `recovered`, `held`); the console shows them under **Logs → Delivery receipts → Single charge**. With the flag off, new receipts and events carry no link, and the API shows no `single_charge` block. **Write cost.** The three post-response commits become one. The before and after measurement with the T044 harness is in [how performance is measured](/docs/performance/method/#single-charge-t160001). **Upgrade.** Migration 166 adds the nullable link and resolution columns and two partial indexes; existing receipts and events keep no link. Turn the flag on after every replica runs this version: an older replica keeps the separate writes for its own requests, which is safe, and the worker also resumes a linked receipt that an older path finalized without settling. Turning the flag off stops new links; receipts linked while it was on keep their link in the API and are still resumed. ### Background responses With `quota_background_responses` (T168), a Responses background create is reserved but not linked to its receipt: its reservation settles later, from the provider's terminal response, as described in [budgets and TPM](/docs/features/budgets-and-tpm/#background-responses). The same `charge_accounting` block bounds its worker: ```yaml charge_accounting: background_poll_seconds: 30 # 5-3600; how often open background responses are asked about background_max_age_seconds: 86400 # 600-604800; then one never seen ending is held as unknown ``` `GET /api/v1/admin/durable-usage` then adds a `background_responses` block (the installation-wide counts `pending`, `settled`, `released`, `unknown`, `expired`); the console shows it under **Logs → Delivery receipts → Background responses**. With [organization admins](/docs/features/organization-admins/) on, a team-scoped session (team user, team viewer, team or organization admin) counts only the team it reads, so one organization never sees another's background activity. ## Durability Acceptance, finalization and recovery require `fsync=on` in PostgreSQL and force synchronous commit. Reliable disks, backups, failover and synchronous replicas remain the installation's responsibility. ## How to query **In the console:** **Logs → Delivery receipts**, with filters, the three states and pagination. Fields that were not observed are shown as such, never as zero. **Through the API:** `GET /api/v1/admin/durable-usage`, with `analytics:read`. | Filter | Values | | --- | --- | | `from`, `to` | RFC3339, up to 90 days (by acceptance time in PostgreSQL) | | `principal`, `model`, `team`, `provider`, `key_id`, `operation` | Exact, up to 256 bytes | | `request_id`, `internal_event_id` | Exact | | `state` | `pending`, `completed` or `indeterminate` | | `offset` | 0 to 10,000; 50 items per page | The response includes coverage by state, the items, `has_more` and `next_offset`. Team roles see only their own teams; `operator` does not read usage. The provider is known only at the end, so filtering by provider excludes pending receipts. Keep the gateway and database clocks in sync: a database clock that runs ahead can push recent receipts out of the default window. ## Limits - It is not a financial ledger, an invoice or an exactly-once guarantee at the provider. For money, see [budgets](/docs/features/budgets-and-tpm/) and [reconciliation](/docs/features/quota-finance/). - One receipt per request, not per attempt: retries show up in the logs, not in separate receipts. A realtime session is the exception: one receipt per response. - An `indeterminate` outcome leaves the [valuation](/docs/features/usage-valuation/) unknown. - The database grows with the receipts: plan retention, backup and capacity. - To turn it off, use the flag; never drop the table. ## See also - [Logs, traces and metrics](/docs/features/observability/). - [Usage in streams](/docs/features/stream-usage/). - References: [reliability and the WAL in PostgreSQL](https://www.postgresql.org/docs/current/wal-reliability.html). ## Internal writer boundary Event/valuation/receipt writes share a typed writer contract. Acceptance commits before dispatch; finalization commits the event, optional captured valuation/rate and receipt state together. A failed selected writer is never replaced by another database, and failed durable finalization does not fall through to best-effort event recording. Recovery and pending-only renewal continue for existing receipts after the operational flag is disabled; shutdown owns their worker lifecycle. This internal boundary does not expose an additional operator-selectable database mode or change the API/flags above. General regressions use PostgreSQL only. Optional database support qualification is separate and reused, as described in quality. # Durable queues and dead letters **Last updated:** 2026-11-22T06:50:00-03:00 (UTC-3) Durable queues hold background work that must survive a restart, a crash or a failing destination. A job is a PostgreSQL row: the gateway confirms it only after the row is committed, delivers it under a lease that a worker keeps alive with a heartbeat, retries it with a bounded exponential delay, and after its last attempt keeps it as a dead letter that an operator can inspect, send back or purge. Every replica runs the workers; the lease guarantees that a job is held by one worker at a time. | Flag | Default | What it turns on | | --- | --- | --- | | `durable_queues` | `false` | The queue workers, the `log_delivery`, `alert_delivery` and `fx_refresh` workloads, the admin API under `/api/v1/admin/queues` and the console page **Settings → Durable queues**; an operator control under plan entitlements | Three workloads run on the queues: - **Log delivery**: a [log destination](/docs/features/observability/) batch that failed its two in-memory retries used to be dropped and counted. With `durable_queues` on, a batch that failed for a reason that may heal is queued instead and delivered later by any replica. - **Alert delivery** (T168): an [alert channel](/docs/features/alerting/) delivery the outbox gave up on, after its own eight attempts, for a failure that may heal, is retried by the queue and then kept as a dead letter you can reprocess. - **FX refresh** (T168): the [display currency](/docs/features/display-currency/) reference rates are fetched once per refresh slot for the whole deployment, with retries and a dead letter, instead of once per replica. ## How a job moves ```mermaid stateDiagram-v2 [*] --> ready: enqueue (committed) ready --> leased: claimed (attempt counted) leased --> done: handler succeeded leased --> delayed: retryable failure delayed --> ready: backoff elapsed leased --> ready: lease expired (worker crashed) / released on shutdown leased --> dead: permanent failure or last attempt dead --> ready: reprocess (operator) dead --> [*]: purge (operator) or retention done --> [*]: retention ``` - **Admission.** An enqueue is refused with `queue_full` when the queue already holds `max_depth` jobs that are waiting or dead-lettered. Dead letters count, so a destination that keeps failing cannot grow storage without bound: reprocess or purge them to make room. Admission takes a per-queue transaction lock, so the depth check is exact across replicas. - **Durable confirmation.** An enqueue returns only after its transaction commits. A connection lost before `COMMIT` leaves no job. Code that writes its own rows can enqueue inside its own transaction, so the job exists exactly when those rows do. - **Idempotency.** A job may carry an idempotency key, unique per queue. Enqueuing a known key admits nothing and returns the existing job, while that job is waiting, dead or kept as done (`completed_retention_hours`). - **Lease and visibility timeout.** A worker claims a job with a lease of `visibility_timeout_seconds` and renews it every `heartbeat_seconds`. If the worker stops renewing it (the process crashed, hung or lost the database), the job is delivered again after the lease expires. A worker that lost its lease is stopped and cannot complete or fail the job any more. Claims use `FOR UPDATE SKIP LOCKED`, the same lease contract as batches and evaluation runs. - **Attempts.** An attempt is counted when the job is claimed, not when it fails. A job whose worker crashes every time still reaches `max_attempts` and becomes a dead letter with the class `lease_expired`, instead of crashing workers forever. - **Retries.** A retryable failure waits `backoff_base_seconds × 2^(attempt−1)`, capped at `backoff_max_seconds`, with jitter: the delay is uniform in the upper half of that step, so replicas that failed together do not retry together. A permanent failure dead-letters the job at once. - **Error classes.** A failure is stored and logged as a short identifier (`timeout`, `unreachable`, `failed`, `rejected`, `denied`, `destination_removed`, `lease_expired`, `invalid_payload`), never as error text. Payloads never appear in logs. - **Shutdown.** At SIGTERM a replica stops claiming jobs, without waiting for the drain delay. Jobs in flight get the shutdown deadline (`lifecycle.drain_delay` plus `lifecycle.shutdown_timeout`, counted from SIGTERM) to finish; past it they are cancelled and released, with the attempt they were charged refunded, so another replica takes them at once. - **Payloads and retention.** A payload larger than `max_payload_bytes` is refused at enqueue. A done job keeps its metadata and idempotency key for `completed_retention_hours`, but its payload is erased when it completes. A dead letter keeps its payload for `dead_letter_retention_hours`, then it is deleted. Waiting jobs are never deleted by retention. Delivery is at least once: when a handler's effect reached its destination but the answer was lost, the job runs again. Log records carry `request_id`, which a consumer can use to deduplicate. ## Enable ```yaml features: durable_queues: true log_destinations: true # the log_delivery workload runs only while log destinations are on durable_queues: poll_interval_ms: 1000 log_delivery: max_depth: 1000 max_attempts: 8 max_payload_bytes: 1048576 visibility_timeout_seconds: 60 heartbeat_seconds: 15 job_timeout_seconds: 30 backoff_base_seconds: 5 backoff_max_seconds: 900 concurrency: 2 completed_retention_hours: 24 dead_letter_retention_hours: 168 alert_delivery: {} # same fields and defaults as log_delivery fx_refresh: {} # same fields and defaults as log_delivery ``` The `durable_queues` block is boot configuration: change it in the YAML (or the Helm values file) and restart. A value of 0 or an omitted field takes the default. The flag itself can also be changed at runtime through feature management (`feature_management`); turning it off stops the workers and the log-delivery hand-off but keeps the jobs, which resume when it is turned on again. | Field | Default | Bounds | Meaning | | --- | --- | --- | --- | | `poll_interval_ms` | 1000 | 100–60000 | How often each replica looks for due jobs | | `.max_depth` | 1000 | 1–1000000 | Waiting plus dead-lettered jobs; past it an enqueue is refused (`queue_full`) | | `.max_attempts` | 8 | 1–100 | Deliveries, crashed ones included, before the dead letter. Captured per job at enqueue | | `.max_payload_bytes` | 1048576 | 1024–16777216 | Largest payload accepted | | `.visibility_timeout_seconds` | 60 | 5–3600 | Lease; an unrenewed job is delivered again after it | | `.heartbeat_seconds` | 15 | 1–1800, at most half the visibility timeout | Lease renewal interval | | `.job_timeout_seconds` | 30 | 1–3600 | Bound of one attempt; reaching it is a `timeout` failure | | `.backoff_base_seconds` | 5 | 1–3600 | First retry step | | `.backoff_max_seconds` | 900 | base–86400 | Largest retry step | | `.concurrency` | 2 | 1–64 | Jobs of this queue one replica runs at once | | `.completed_retention_hours` | 24 | 1–8760 | How long a done job keeps its metadata and idempotency key | | `.dead_letter_retention_hours` | 168 | 1–8760 | How long a dead letter, payload included, is kept | The queues are `log_delivery`, `alert_delivery` and `fx_refresh`; each has its own profile with the fields above (`durable_queues..`) and the same defaults and bounds. ## The log delivery workload Each [log destination](/docs/features/observability/) keeps sending its batches as before: in memory, with two retries. When a batch still fails: | Failure | Without `durable_queues` | With `durable_queues` | | --- | --- | --- | | Timeout, unreachable, HTTP 5xx, 408 or 429, sink replaced while sending | Dropped and counted | Queued as one job; `durably_queued` counts its records | | HTTP 401/403 (`denied`) or 4xx/partial rejection (`rejected`) | Dropped and counted | Dropped and counted: retrying would fail the same way | | Cloud credential unavailable | Kept in memory and retried | Unchanged | | Queue full, payload too large, database down | — | Dropped and counted, with a `log_batch_queue_refused` warning | A queued batch is keyed by its destination and content, so the same batch is queued once. Any replica delivers it through the destination's current configuration. On redelivery, a `denied` or `rejected` answer, or a destination that no longer exists (`destination_removed`), dead-letters the job at once; other failures are retried. While `log_destinations` is off, the jobs wait and spend no attempts. The log destination status (`GET /api/v1/admin/log-destinations`) reports `durably_queued` and `redelivered` record counts per destination. Records are request metadata, never prompts or answers, but they do name users, keys and models: treat dead-letter inspection accordingly. ## The alert delivery workload The [alert outbox](/docs/features/alerting/) sends each delivery itself, with eight attempts up to an hour apart, and then marks it `failed`. With `durable_queues` on: | Last outbox attempt | Without `durable_queues` | With `durable_queues` | | --- | --- | --- | | Timeout, network error, HTTP 408, 429 or 5xx, credentials unavailable | `failed`; retried only by hand | `failed`, and queued as one job keyed by channel and alert | | A permanent refusal (HTTP 4xx other than 408 and 429, or a refused destination) | `failed` | `failed`, not queued: it would fail the same way | | Queue full or database down | — | `failed`, with an `alert_delivery_queue_refused` warning | The job payload names the delivery only (`channel_id`, `alert_id`, `event`), never the URL, secret or message. A delivery is queued only after the outbox recorded it failed. The job holds the outbox row while it sends: a delivery retried by hand meanwhile (**Retry** on the alert channel) is not sent by the job, which then completes without sending, and a manual retry waits for a send in progress. A redelivery reads the alert again from its source and sends it through the channel's current configuration and signing secret; success marks the outbox row `delivered`. A removed or disabled channel dead-letters the job at once (`destination_removed`); a permanent refusal too; other failures are retried with the queue's backoff. While `alert_channels` is off the jobs wait. `subject` is the channel ID. A channel may receive a delivery twice (at least once): deduplicate by the `delivery_id` in the payload. ## The FX refresh workload Without the queue every replica fetches the [reference rates](/docs/features/display-currency/) on its own `fx.refresh_interval` timer. With `durable_queues` on, each timer enqueues the fetch of the current slot (the time truncated to `fx.refresh_interval`) under the same idempotency key, so the first replica admits it and the others find it: one fetch per slot for the deployment. A failed fetch is retried with backoff and, past `max_attempts`, kept as a dead letter (`unreachable` or `storage_unavailable`); the stored day then ages into stale as before, never guessed. Every replica still reloads the latest stored day on its timer. A job is kept as done for `completed_retention_hours`; with a refresh interval longer than that, a slot could be fetched again after the done job is pruned, which only repeats the same read. While `fx_display` is off the jobs wait. `subject` is the source (`ecb`). ## Operate from the API or the console Console page: **Settings → Durable queues** shows each queue's counts and profile, a **Queue profiles** table with the eleven bounds of every queue under their YAML names (from `durable_queues` in `GET /api/v1/admin/config`, read-only, restart to change), the dead letters with their error class and attempts, and, for roles that may manage them, **Inspect**, **Reprocess**, **Purge**, **Reprocess all** and **Purge all** (optionally limited to one error class). | Permission | Roles | Grants | | --- | --- | --- | | `queues:read` | admin, viewer, operator | Queue counts and profiles; dead-letter metadata | | `queues:manage` | admin, operator | Payload inspection, reprocess and purge | Team roles have neither. Every inspection, reprocess and purge writes one audit row per job (`queue.dead_letter.inspect`, `queue.dead_letter.reprocess`, `queue.dead_letter.purge`) in the same statement as the change. | Method and path | Permission | Purpose | | --- | --- | --- | | `GET /api/v1/admin/queues` | `queues:read` | Queues, profiles and counts (`ready`, `delayed`, `leased`, `dead_letters`, `done`) | | `GET /api/v1/admin/queues/{queue}/dead-letters` | `queues:read` | Dead letters, newest first; `error_class`, `limit` (1–200, default 50), `cursor` | | `GET /api/v1/admin/queues/{queue}/dead-letters/{id}` | `queues:manage` | One dead letter with the first 4096 bytes of its payload (audited) | | `POST /api/v1/admin/queues/{queue}/dead-letters/{id}/reprocess` | `queues:manage` | Back to the queue with a fresh attempt budget, due at once | | `DELETE /api/v1/admin/queues/{queue}/dead-letters/{id}` | `queues:manage` | Delete for good | | `POST /api/v1/admin/queues/{queue}/dead-letters/reprocess` | `queues:manage` | Bulk reprocess | | `POST /api/v1/admin/queues/{queue}/dead-letters/purge` | `queues:manage` | Bulk purge | A bulk request selects explicit IDs or all dead letters, at most 500 per call, oldest first: ```json {"ids": ["qj_0123456789abcdef0123456789abcdef"]} ``` ```json {"all": true, "error_class": "timeout", "limit": 100} ``` A bulk purge of `all` also needs `"confirm": true` (otherwise `400 confirmation_required`). The answer lists the jobs acted on: ```json {"reprocessed": ["qj_0123456789abcdef0123456789abcdef"], "count": 1} ``` A dead letter as the list returns it: ```json { "id": "qj_0123456789abcdef0123456789abcdef", "queue": "log_delivery", "subject": "siem", "state": "dead", "attempts": 8, "max_attempts": 8, "last_error_class": "timeout", "payload_bytes": 2048, "payload_sha256": "9f2c…", "reprocessed": 0, "idempotent": true, "enqueued_at": "2026-11-15T01:00:00Z", "available_at": "2026-11-15T01:42:10Z", "dead_at": "2026-11-15T02:10:00Z" } ``` `subject` is the workload's label; for `log_delivery` it is the destination ID. Errors: `404 feature_disabled` with the flag off, `404 not_found` for an unknown queue or a job that is not a dead letter of it, `400 invalid_selection`, `401`/`403` for a missing or insufficient session, `503 storage_unavailable`. ## Upgrade notes - Migration 155 creates `gateway_queue_jobs`. Migrate and upgrade every replica before turning the flag on: an older replica neither runs the workers nor hands log batches to the queue (its failed batches are still dropped and counted). - With the flag off nothing changes: log destinations drop exhausted batches exactly as before, alert deliveries end `failed` and every replica fetches the reference rates itself. - T168 adds the `alert_delivery` and `fx_refresh` queues and their YAML profiles; no migration. An older binary refuses the two profile keys in YAML and leaves their jobs in the table: remove the keys before rolling back. A recovered crash is delivered once more under a new lease, as for `log_delivery` (`TestQueueFXRefreshOncePerSlotPostgres`, `TestQueueAlertDeliveryAfterOutboxPostgres`). # Usage in streams **Last updated:** 2026-11-27T12:30:47-03:00 (UTC-3) In streamed (SSE) responses, the provider can report usage in a finishing chunk or terminal event; it is not necessarily the last SSE event. With `stream_usage`, the gateway reads the bounded stream while it relays it to the client and records the input and output counters, without changing a single byte. Without the flag, streamed calls have no tokens in the history. It applies to the native streams of Chat Completions, Responses, Anthropic Messages and Gemini. With [durable receipts](/docs/features/durable-usage/#recovery), a live stream keeps its pending receipt renewed until the actual operation ends. The receipt lease is not an additional generation timeout. This heartbeat does not create usage counters: terminal provider evidence is still required below, and a truncated or cancelled answer remains conservative. ## Administrative interruption An emergency stop interrupts an unfinished stream without a provider-blaming error event, a normal terminal marker or a retry. Once response headers have been sent, the HTTP connection is aborted rather than given a second status. With usage collection, an actual stop is logged at Info with `termination: gateway_panic`; its measurement keeps the observer's original state. A known stop reason creates no tokens or financial proof. A terminal response or completed receipt already observed before a later stop keeps its existing evidence. Client cancellation and genuine provider read errors retain their own classification. See [operations](/docs/operate/operations/#emergency-stop-panic) and [telemetry](/docs/features/observability/#logs-and-traces-otlp). ## How to turn it on ```yaml features: stream_usage: true ``` In **Chat Completions**, the provider sends the usage only when the request sets `stream_options: {"include_usage": true}`. By default that is the client's choice; an alias with [`stream_usage: inject`](#ask-for-the-usage-on-the-clients-behalf) asks for it when the client did not. ## What is recorded | Route | Where usage comes from | Recorded | | --- | --- | --- | | Chat Completions | Last chunk with `usage` and `choices: []`, followed by `[DONE]` | `prompt_tokens`, `completion_tokens` | | Responses | `response.completed`, `response.incomplete` or `response.failed` | `input_tokens`, `output_tokens` | | Messages | `message_start`, cumulative `message_delta` and `message_stop` | `input_tokens`, final `output_tokens` (without summing deltas) | | Gemini | Valid `finishReason` on every candidate and the last `usageMetadata` | `promptTokenCount`, `candidatesTokenCount` | **Only proven counters are recorded.** An interrupted stream, or missing, invalid or partial counters leave usage **absent**, never zero. Identical duplicates are not summed. A stream the provider cut is still recorded as a failure: its request log row and request event carry `error_code: stream_interrupted` with the status the client received, every error count includes it, the provider error counter and the circuit breaker count it, and a budget reservation stays held, because the provider may have charged for the part it generated. - Responses `incomplete` or `failed` can have valid usage, if the provider reports it; that does not turn into success. - In Gemini, output is only `candidatesTokenCount`; the gateway does not deduce reasoning tokens from the total. - Anthropic cache and tool tokens stay in their own fields and are not added to the input. ## Guarantees - **No byte changes:** payload, events, order, status and headers stay the same. The one exception is an alias with `stream_usage: inject`, which removes the usage it asked for (below). - **No extra cost:** no additional call, no retry, no queue. - The gateway writes to the client before observing, and a slow client slows the stream down (backpressure). Observation limits, per stream: 256 KiB per event, 32 MiB in total and 100,000 events (64 candidates in Gemini). Beyond that, measurement is turned off for that stream and the content keeps being delivered. ## Ask for the usage on the client's behalf Most applications stream without `stream_options`, so their streamed calls have no tokens: the request log, [budgets and TPM](/docs/features/budgets-and-tpm/), [valuation](/docs/features/usage-valuation/) and [request events](/docs/features/request-events/) cannot say what they used, and under a budget such a stream is refused before the call (`stream_profile_not_supported`). Changing every application is often not possible. With `stream_usage: inject` on the alias, the gateway asks the provider for the usage itself, measures it, and takes it out of the stream before it reaches the client, so the client receives what it would have received without the option. ```yaml features: stream_usage: true # required: it is what reads the usage models: - id: gpt-5-mini stream_usage: inject # default: client targets: - provider: openai model: gpt-5-mini ``` | Field | Default | Values | | --- | --- | --- | | `models[].stream_usage` | `client` (also when absent) | `client`: the client's `stream_options` decides, as before. `inject`: the gateway asks for the usage when the client did not. | The setting belongs to the alias, not to a target: whether the client sees a usage chunk is a property of the alias it calls, and every fallback target of one request must give the client the same stream. It is accepted only on an alias with the `chat` capability, and not on an `auto_route` alias (set it on the aliases the route chooses) or a [`alias_of`](/docs/features/model-aliases/) entry (it follows its canonical model). An unknown value is refused when the configuration loads and when the console or the model API saves the alias. The value is checked whatever the flag says, but it is applied only while `stream_usage` is on: without the flag nothing reads the usage, so nothing is asked for. Saved in the console (**Models**, the alias editor, **Stream usage**) or through the model API, it applies to the next request, with no restart; in the YAML it follows the usual rollout. ### When it applies All of these must hold; otherwise the request goes out exactly as the client sent it: - the request is a Chat Completions stream (`stream: true`) on `/v1/chat/completions`. The Messages, Responses and GenerateContent routes translated through the chat pipeline already ask for the usage themselves, since their own terminal events carry it; - the client did not ask for the usage: `stream_options` is absent or `null`, or an object whose `include_usage` is absent, `null` or `false`. A client that sent `include_usage: true` keeps its stream exactly as before. A value the gateway cannot complete (`stream_options` that is not an object, an `include_usage` that is not a boolean) is the client's request and is forwarded as it is, so the provider answers it as before. ### What the provider receives | Target | What the gateway changes | | --- | --- | | `openai` on Chat Completions (including any compatible backend) | `stream_options.include_usage: true`, keeping the client's other `stream_options` members (for example `include_obfuscation`) | | SageMaker (the body is forwarded) | The same | | OCI | The same, which its translation sends as `streamOptions.isIncludeUsage: true` | | Anthropic, Gemini, Bedrock, Cohere, an `openai` target on the Responses API | Nothing: these providers always end their stream with the usage. Their translator then emits the canonical usage chunk, as if the client had asked, so the request is measured | Before this setting, a translated stream whose client did not ask for the usage was measured only for a budget or a valuation (the translator reads the provider's usage for them); the request log and the request event had no tokens. With `inject` they have them too. The change is made to each attempt's own copy of the body, after the [request parameter policy](/docs/features/request-parameter-policy/) of the target. The client's body, which the semantic cache key, guardrails and the next fallback target start from, is not changed. The policy and this setting are independent: `stream_options` is not in the policy's allowlist and cannot be dropped, so no policy can undo the injection. ### What the client receives Exactly the stream the provider would send without `include_usage`, which by the [Chat Completions contract](https://developers.openai.com/api/reference/resources/chat/subresources/completions/streaming-events) has no usage at all: - the final chunk that exists only for the usage (`"choices": []` with a non-null `usage`) is removed. A client that reads `choices[0]` of every chunk would fail on it. A compatible backend that leaves that chunk's `choices` out, or sends `null`, gets the same treatment; - the `usage` member that every other chunk then carries (`"usage": null`, or a provider's usage on its finishing chunk or a running count) is removed from the chunk; everything else in the chunk keeps its bytes and order; - `data: [DONE]`, comments, `id:`/`event:`/`retry:` lines, error events, the status and the headers are forwarded unchanged. The gateway holds back only the event being received and forwards each event as soon as its closing blank line arrives (at its CR, for a provider that ends lines with CRLF, as SSE dispatches it): no read-ahead, no extra goroutine, the same backpressure. An event is decided whole, so a usage split across reads is still removed. The cost of that: a provider that sends one event in slow pieces, or a comment without its blank line, reaches the client only when the event ends, so a client with a short idle timeout sees the gap the provider left inside the event. Something the gateway cannot decide safely is forwarded as received: - an event over the 256 KiB observation bound is forwarded as it arrives, untouched (the usage chunk is a few hundred bytes); - a chunk whose JSON spans several `data:` lines keeps its `usage: null` (rewriting it would change its framing); a usage-only chunk is removed either way; - data that is not a JSON object, or not valid JSON, passes untouched; - an event the provider never finished (the stream ended or failed in its middle) is delivered as received, before the gateway's interruption event, as it would have been. If the client leaves or the request ends before the provider's last event, the stream ends as any other cancelled stream: the unfinished event held is not delivered and the measurement is `cancelled`. With [`stream_settle_on_disconnect`](#when-the-client-disconnects) the provider is read to its end instead, and nothing more is delivered. Since no complete event is ever held, a cancellation after `[DONE]` keeps the stream `reported`, as without the setting. ### What is measured The observer reads the provider's stream before the removal, so the injected usage is measured like a usage the client asked for: the request log's input and output tokens, the request event (`tokens`, `cost`), the [valuation](/docs/features/usage-valuation/) and, under a budget or TPM, the reservation is admitted and settled. On an openai Chat Completions target such a stream no longer needs the client's `include_usage`: the budget admits `stream_options` absent or `null`, or an object with only `include_usage` (`true`, `false` or `null`) and `include_obfuscation`, which changes padding, not tokens. The `stream_usage` log record of such a request adds `usage_injected` with `chunks_removed` and `members_removed`, so a measured stream the client asked nothing of is explainable. A provider that ignores the option sends no usage: its stream reaches the client unchanged, the measurement is `missing` and the usage stays unknown (a budget reservation stays held), never zero. ### Before you turn it on - A compatible backend that refuses `stream_options` answers 400 to every streamed request of the alias. Check the backend first, or keep `client` on that alias. - A backend that always streams a usage, even unasked, loses it from the client's stream under `inject`: the client then receives the stream the Chat Completions contract promises for a request without `include_usage`. - The usage is metered, not hidden from the provider: the provider still bills the same tokens; the option changes only what it reports. - Semantic cache hits make no provider call and keep their behavior: they include the usage only when the client asked. ### Upgrade and rollback Nothing changes on upgrade: every alias keeps `client` until it sets `inject`. There is no migration; an alias saved through the API keeps the field in its stored JSON. Before rolling back to an older binary, remove `stream_usage` from the YAML (its strict schema refuses the unknown field); an older binary ignores the field in a stored alias and sends streams as the client wrote them. ## When the client disconnects By default a client that leaves in the middle of a stream ends the provider call with it: the gateway closes the provider connection at once. The final usage never arrives, so the stream is not measured, and under a [budget](/docs/features/budgets-and-tpm/) its reservation stays held as `unknown`, because the provider may have charged for what it generated. Some clients do this on every run (a coding agent that opens a last call on exit and closes the connection without reading it). Each run then leaves one unknown reservation. For those, turn on `stream_settle_on_disconnect`: ```yaml features: stream_usage: true stream_settle_on_disconnect: true ``` | | Off (default) | On | | --- | --- | --- | | Provider call after the client leaves | Closed at once | Read to its end; nothing more is written to the client | | Usage | Not measured | The provider's final usage, as for a stream the client read whole | | Reservation | Held as `unknown` | Settled at the measured amount | | What the provider generates | Usually stops when the connection closes | **The whole answer, which the provider bills in full** | | Request log | Cut by the client, no tokens | Cut by the client (`client_closed_stream`), with tokens and cost | **The trade.** With the flag on, a client that gives up no longer stops the generation: the provider produces, and bills, the whole answer up to the request's own output limit. You pay for output nobody reads, and in exchange every call is measured and no budget is held by an unknown amount. Leave it off where clients cancel long answers on purpose; turn it on where unknown reservations from abandoned streams are the problem. It is an operator flag, off by default, changed in the YAML or under **Settings & sources** without a restart, and it requires `stream_usage`. **Which streams.** Every stream the gateway measures for a reservation or a [valuation](/docs/features/usage-valuation/): Chat Completions, Responses, Anthropic Messages and Gemini `streamGenerateContent` (the Gemini API and Vertex AI), native or [translated](/docs/features/protocol-translation/) (Bedrock, Anthropic, Gemini and Cohere behind another route's dialect). The disconnect is noticed when the client's connection closes or a write to it fails. It counts from the moment the call goes out to the provider: a client that leaves while the gateway is still waiting for the provider's first byte no longer cancels the call, and the whole answer is read without being written. **Bounds.** The read after the disconnect never runs free: - the stream's own [clocks](/docs/features/stream-timeouts/) keep counting: `network.stream_idle_timeout` between provider bytes and `network.stream_max_duration` for the whole stream (or the request timeout without `stream_timeouts`); - it stops after 256 KiB plus 1 KiB per token the reservation holds, and never past the 32 MiB the observer reads from any stream; - the emergency stop ends it at once. When a bound ends it, or the provider ends without a valid final usage, nothing is measured and the reservation stays held, exactly as with the flag off. Once the client has left, the gateway makes no new provider call for it: a retry or a fallback that would send the request again ends the request instead. The `stream_usage` log line then carries `after_client_disconnect` with `measured: false` and the bytes read. **Where it does not apply**, and the reservation stays held: - a stream that is not measured: `stream_usage` off, or a [passthrough](/docs/features/passthrough/) route, whose optional usage never proves a charge; - a client that leaves before the call went out to the provider (while the request is still being admitted): nothing was sent, so nothing is held; - a non-streaming call the client abandons: there is nothing to read ahead of the answer; - [realtime](/docs/features/realtime/) sessions: each response is settled by its own terminal event, and the session ends with its WebSocket; - an answer cut by an output guardrail, a gateway clock or the emergency stop: those are the gateway's decisions, not the client's. For the unknown reservations that remain, see [financial reconciliation](/docs/features/quota-finance/). ## Limits - Stream counters are for analytics, not for invoicing: [valuation](/docs/features/usage-valuation/) values a stream only when these counters are reported and every event fits its text profile. For budgets on streams, see `quota_streaming` in [protected profiles](/docs/features/quota-protocols/). - The reason for a missing measurement goes in the request's structured log (`reported`, `missing`, `incomplete`, `invalid`, `limit_exceeded`, `cancelled`...), not in the console. ## See also - [Logs, traces and metrics](/docs/features/observability/). - [Durable receipts](/docs/features/durable-usage/). - Official contracts: [OpenAI Chat streaming](https://developers.openai.com/api/reference/resources/chat/subresources/completions/streaming-events), [OpenAI Responses streaming](https://developers.openai.com/api/reference/resources/responses/streaming-events), [Anthropic streaming](https://platform.claude.com/docs/en/build-with-claude/streaming), [Gemini GenerateContent](https://ai.google.dev/api/generate-content). # Metadata retention **Last updated:** 2026-11-26T02:16:00-03:00 (UTC-3) Usage events grow forever if nobody deletes them. Retention removes, in small batches and without getting in the way of inference, the usage events older than the period you set, along with the valuations and finalized receipts that depend on them. Flag: `metadata_retention`, which requires PostgreSQL. **Nothing is deleted by default.** With the flag off or `retain_days: 0`, everything is preserved. ## How to turn it on ```yaml features: metadata_retention: true metadata_retention: revision: 1 # increase it on every YAML change retain_days: 90 # 7 to 3,650; 0 preserves everything batch_size: 250 # 1 to 1,000 events per batch interval: 10m # 1 min to 24 h between batches ``` 90 days is only an example: choose the period with whoever is accountable for audit and backup. The existing defaults and bounds are shared by YAML, the administrative API and the existing console controls: | Field | Default and accepted policy | | --- | --- | | `retain_days` | `0` preserves; positive values `7`–`3650` | | `batch_size` | Omitted or `0` uses `250`; positive values `1`–`1000` | | `interval` | Empty uses `10m`; valid Go duration `1m`–`24h` | | `revision` | Default `0`; allowed `0`–`2147483647`; a positive YAML period requires a positive revision and the monotonic update rule below | The interval retains full Go duration syntax without an extra thirty-two-character form limit. Defaults are selections, not new retention periods or permission to delete. The existing managed policy writer and YAML revision remain separate controls; see [parameter definitions](/docs/reference/parameter-registry/). **In the console:** **Metadata retention** shows the policy in effect, its source (YAML or console), the cadence, the last run, and a preview of what would be removed. Editing requires the global admin (`retention:manage`). Any positive period asks you to check **I authorize irreversible deletion of expired usage, valuation and finalized receipt metadata**, a box that starts unchecked on every edit. **Through the API:** | Endpoint | What it does | | --- | --- | | `GET /api/v1/admin/retention` | Policy, version, and schedule; the YAML `revision` in force is `metadata_retention.revision` | | `PUT /api/v1/admin/retention` | `{base_fingerprint, version, policy:{retain_days,batch_size,interval}, confirm_delete_expired_metadata}` | | `DELETE /api/v1/admin/retention` | Reverts to the YAML (with the same confirmation, if the YAML has a positive period) | | `GET /api/v1/admin/retention/preview` | A sample of up to 1,000 eligible events, without deleting anything | There is no "delete everything now": the first run waits for the interval. ## What is removed and what stays | Data | Outcome | | --- | --- | | Usage event without a receipt, older than the period | Removed | | Event with a finalized receipt (`completed` or `indeterminate`), with occurrence **and** finalization older than the period | Removed, along with the receipt | | The event's valuation | Removed in the same transaction | | Receipt still without a final result | **Preserved** | | Frozen prices and price book history | **Preserved** | | Audit, identities, configuration, counters, and the [budgets](/docs/features/budgets-and-tpm/) ledger | **Never removed** by this function | The period is measured by the PostgreSQL clock. An old request that is finalized now starts counting again from its finalization. Analytics warns you when a period was affected by retention, instead of showing the empty range as "no traffic". ## How it works - Each replica checks every minute whether it is time to run; a shared lock guarantees one run at a time across the cluster. - **One batch per run**, taking up to 5 s. Rows in use are skipped and left for the next batch. - The batch's removal, count, and audit are written together; any failure rolls back the whole batch. - Retention never runs on the inference path. Batches and time are bounded, but the cost depends on the volume and the database indexes. Reclaiming disk space (`VACUUM`) and purging data from backups are operations tasks. ## YAML and multiple replicas - What is saved in the console takes precedence over the YAML; removing the override reverts to the YAML. - When you change the YAML, **increase `revision`**. A replica with a lower revision does not run retention. Two different baselines with the same revision both stop until a higher revision resolves it. - Concurrent changes get `409`, and the console keeps your draft. ## Pausing and rolling back - To pause, save a period of zero or turn the flag off. What has already been deleted does not come back. - When you roll back to an earlier version of the gateway, do not drop tables or versions. ## Limits - An active [legal hold](/docs/features/data-governance/#legal-holds) suspends this purge: the batch is skipped and runs on a later tick once every hold is released. Contractual retention of the audit log is [audit retention](/docs/features/data-governance/#audit-retention). - No anonymization. - The preview is a sample: with `truncated: true`, the numbers are a minimum, not the total. - The budgets ledger has its own archiving, in [financial reconciliation](/docs/features/quota-finance/#archiving-the-ledger). Captured prompts and answers ([content capture](/docs/features/content-capture/)) are not usage metadata: each record carries its own expiry, from its team policy, and is purged every minute whatever this setting says. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `PUT /api/v1/admin/retention` | Stores the retention policy of expired usage metadata at the current version | ## See also - [Durable receipts](/docs/features/durable-usage/). - [Analytics](/docs/features/analytics-experience/). - [Operations](/docs/operate/operations/). ## Evaluation results With `evaluation_result_retention` (T186.016, operator control, off by default) the same window also removes evaluation results and dataset runs, in bounded batches, after each pass; human annotations, annotated or retained traces and the datasets themselves are kept. See [retention of results](/docs/features/public-trace-api/#retention-of-results). # Evals, prompts and Playground **Last updated:** 2026-11-27T01:31:49-03:00 (UTC-3) Switching models or changing a prompt without measuring is a gamble. The gateway includes the full evaluation cycle: datasets, experiments, judges and human annotation on real traffic. Alongside it come versioned prompts and a Playground for testing. ## Evals With `evaluation_results` on, every score is an [evaluation result](/docs/features/evaluation-results/) attached to the span, trace or session it judged, shown on the request log and the trace, and exported over OTLP. With `evaluation_tracing` on, each judge run is [its own trace linked to what it judged](/docs/features/evaluation-tracing/), request log rows say whether a request came from your application, a judge or an experiment, evaluators report health and 7-day cost, and Cost shows evaluation spend as its own line. With `evaluation_metrics` on, every result is also a [metric](/docs/features/evaluation-metrics/): Prometheus and OTLP series with a pass-rate formula, evaluation metrics and dimensions in the analytics query, and a Quality tab on the Usage screen. With `evaluation_monitors` on, a team sets [monitors](/docs/features/evaluation-monitors/) over an evaluator's pass rate, result count, judge spend, a span query or an evaluator's health, with a backtest, and is told through its alert channels when one crosses its threshold and when it recovers. | Feature | What it does | Flag | Learn more | |---|---|---|---| | **Evaluators** | An evaluator owns where it runs: span, trace or session scope with idle windows, a query-language filter, sampling and status; every save is a version with a readable spec, compare and restore; the editor tests on real traffic and shows the weekly volume and cost before Publish; a daily cost ceiling | `evaluators` | [Evaluators](/docs/features/evaluators/) | | **Code, templates, runs on chosen traffic** | JavaScript code evaluators in the extension sandbox with no host operation, a library of more than 60 judges, decision models, code and rules with fixtures, and Evaluate selection, a query over past traffic or a run on one trace, with progress and cancel | `code_evaluators` | [Evaluators](/docs/features/evaluators/#code-evaluators) | | **Datasets** | Versioned inputs and expected outputs, imported from CSV or from real captures | `evals` | [Evals](/docs/features/evals/) | | **Experiments** | Runs a dataset against a model or prompt and compares runs side by side, with charts | `evals` | [Evals](/docs/features/evals/) | | **Experiments as traces** | Each item one trace with its judges nested, dataset version history with diff, notes and restore, a run on an older version, Add to dataset from a span, judging a past run again with an estimate, the experiment_finished alert and the experiments an alias serves | `experiment_traces` | [Experiments as traces](/docs/features/experiment-traces/) | | **Remote experiments** | The team's own service executes the items, signed, behind the outbound URL guard; outputs answered or posted back, judged like any other | `remote_experiments` | [Remote experiments](/docs/features/experiment-traces/#remote-experiments) | | **Comparison summaries** | A short summary of compared runs through the team's chosen alias, estimated first, never stored | `experiment_summaries` | [Comparison summaries](/docs/features/experiment-traces/#comparison-summaries) | | **Regression suites** | Assertions (evaluators or sentences) over a dataset with trials, a pass threshold and a minimum pass rate, and a CI verdict with exit codes | `regression_suites` | [Regression suites](/docs/features/experiment-traces/#regression-suites) | | **Agent evaluations** | Tasks × targets × trials run on the client (Python runner and CLI; model aliases, the Claude Agent SDK, the OpenAI Agents SDK) with predicate, judge and command checks; each trial one trace; a scorecard with pass rate, pass@k, cost per successful task from the ledger, latency and failure classes | `agent_evaluations` | [Agent evaluations](/docs/features/agent-evaluations/) | | **Evaluators** | LLM judge with templates, code evaluators and a decision-model judge | `evals` | [Evals](/docs/features/evals/) | | **Scores** | Numeric, categorical and boolean scores, also through the API (`POST /v1/scores`) | `evals` | [Evals](/docs/features/evals/) | | **Real traffic** | Captures samples of real requests (encrypted, with retention) and judges them with evaluators filtered in the query language | `eval_capture` | [Evals](/docs/features/evals/) | | **One capture policy** | Rules judge chat, Messages, Responses and generateContent requests, streams included, from the team's content capture: the request after guardrail masking and the answer, never the request as received | `content_capture_evaluation` | [Content capture](/docs/features/content-capture/#one-policy-for-audit-and-evaluation-content_capture_evaluation) | | **Reasoning and images for judges** | An evaluator can opt in to read the model's reasoning (`include_reasoning`), kept apart from the answer; a multimodal judge gets captured images back from the media store | `content_capture_reasoning`, `content_capture_media` | [Content capture](/docs/features/content-capture/#the-models-reasoning-content_capture_reasoning) | | **Annotation queues** | Human reviewers score, correct the output and comment, with mentions and Markdown | `eval_capture` | [Evals](/docs/features/evals/) | | **Human review** | A queue takes traces and spans and shows each item as the trace view does, with the judges' results; several people review one item under their own locks, and the item carries every reviewer's value, the final value of each field and whether they differed; item assignment, required fields, drafts, export, and calibration of each judge against the reviewers | `review_multi_annotator` | [Human review](/docs/features/human-review/) | | **Review automations** | A rule in the query language fills a review queue or a dataset from live traffic, forward only, with a sample rate and caps | `review_automations` | [Human review](/docs/features/human-review/#automations) | | **Topics** | Traces, sessions and agent runs clustered into named topics per facet (Intent, Sentiment, Outcome, Issues, Signals) on your own models and keys: live maps and snapshots, treemap, scatter and table with spend, latency, error rate and pass rate per topic, the topic term in the trace explorer and in evaluator rules, a dataset or an evaluator from a topic, an MCP server and `gateway topics` commands | `topics`, `topics_custom_facets` | [Topics](/docs/features/topics/) | | **Findings** | Topic changes and model-free cost and reliability detectors (prompts never cached, large tool results, verbose answers, recurring tool errors, retry loops, wasted spend) raised as alerts with their impact and evidence | `topics_findings` | [Topics](/docs/features/topics/#findings) | | **Public API** | Datasets and experiments from the SDK or from CI (`/v1/datasets`, `/v1/dataset-runs`) | `evals_public_api` | [Evals](/docs/features/evals/) | | **Evaluators and results from code** | Read results (`GET /v1/evaluations`) and keep evaluators as code (`PUT /v1/evaluators/{name}`, publish) with scoped keys; run a dataset with local evaluators from the Python client | `public_trace_api` | [Public trace API](/docs/features/public-trace-api/) | | **Result retention** | Evaluation results and dataset runs follow the metadata retention window; annotations and datasets are kept | `evaluation_result_retention` | [Public trace API](/docs/features/public-trace-api/#retention-of-results) | ## Prompts and Playground | Feature | What it does | Flag | Learn more | |---|---|---|---| | **Versioned prompts** | Templates with immutable revisions, explicit publishing and local rendering | `prompt_registry`, `prompt_management` | [Prompts](/docs/features/prompt-registry/) | | **Mandatory system prompt** | Applies a static published system-only revision to an owning team's Chat alias before guardrails and quotas | `system_prompt` | [System prompt](/docs/features/enforced-system-prompt/) | | **Per-team read access** | Each team reads its own prompts | `prompt_scoped_read` | [Prompts](/docs/features/prompt-registry/) | | **Playground** | Chat with streaming, image input, media modes (image, video, speech, transcription) and comparison between models | `playground`, `playground_streaming`, `playground_images` | [Playground](/docs/features/playground/) | | **From log to Playground** | Opens a captured request in the Playground to reproduce it | `eval_capture` | [Evals](/docs/features/evals/) | # Evals **Last updated:** 2026-11-27T01:31:49-03:00 (UTC-3) Before you switch models or prompts, prove that the change is an improvement. Evals run a dataset against a model and a prompt, score the responses with judges (an LLM, a rule or a person) and compare the results with the baseline, item by item. They also evaluate real traffic, by sampling. Everything is native to the platform. | Flag | What it turns on | | --- | --- | | `evals` | Datasets, evaluators, experiments, comparison, score analytics and annotation queues. Requires PostgreSQL, `ui` and `chat_completions` | | `evals_public_api` | Experiments from code and in CI, with a team key | | `eval_capture` | Capture and evaluation of real traffic; requires the control plane encryption key | | `content_capture_evaluation` | [One capture policy for audit and evaluation](/docs/features/content-capture/#one-policy-for-audit-and-evaluation-content_capture_evaluation): rules judge chat, Messages, Responses and generateContent requests, streams included, from the team's content capture; requires `content_capture` | | `evaluation_results` | Scores become [evaluation results](/docs/features/evaluation-results/) on spans, traces and sessions: pass/fail assessments, typed values (JSON included), error results, evaluator versions, edit history, encrypted judge reasoning, the `/evaluations` API and results on the request log, the trace drawer and sessions | | `experiment_traces` | [Experiments as traces](/docs/features/experiment-traces/): each experiment item one trace with its judges nested, dataset version history with diff and restore, a run on an older version, Add to dataset from a span, judging a past run again, `experiment_finished`; requires `evaluation_tracing` | | `regression_suites` | [Regression suites](/docs/features/experiment-traces/#regression-suites) with a CI verdict; requires `experiment_traces` | | `remote_experiments` | [Remote experiments](/docs/features/experiment-traces/#remote-experiments): the team's own endpoint executes the items; requires `experiment_traces` | | `experiment_summaries` | [Comparison summaries](/docs/features/experiment-traces/#comparison-summaries) through the team's chosen alias; requires `experiment_traces` | | `agent_evaluations` | [Agent evaluations](/docs/features/agent-evaluations/): tasks × targets × trials run by the client-side runner, each trial one trace, and a scorecard per target; requires `experiment_traces` and `evals_public_api` | | `evaluation_tracing` | [Judge calls as linked, labelled traffic](/docs/features/evaluation-tracing/): each judge run in its own trace linked both ways to what it judged, judge trace, request and ledger cost on results, the origin of every request (app, evaluation, experiment, playground, helper, shadow) as a log, usage and cost dimension, evaluator health and 7-day cost; requires `evaluation_results` | Everything belongs to a team: the global admin sees and operates everything, a `team_admin` operates the teams they administer, and the other roles can only read. Interactive reference at `/docs/swagger/`, tag **Evals**. ## Concepts | Concept | What it is | |---|---| | **Score config** | Defines a score by name: numeric (range), boolean, categorical (2–20 categories) or text. The type does not change | | **Score** | A value on a target: a request (`request_id`), a session (`X-Gateway-Session-Id`) or an experiment item. It is validated immediately against the config; once accepted, it is never discarded later | | **Dataset** | Items with `input`, `expected_output` and `metadata`. The optional JSON Schema is enforced on every write. Each change is a new version, and `?as_of=` reads the dataset as of a point in time. Items are added one by one (the item form takes the input, the expected output and an optional metadata JSON object, which judges read as `metadata`), by **CSV** or from traffic **captures**. Datasets are listed by name and items by ID, in the API and the console | | **Evaluator (LLM-as-judge)** | A prompt with `{{input}}`, `{{output}}` and `{{expected}}`, a chat alias as the judge and the output (boolean, numeric range or categories). The response is strict JSON Schema; an invalid response is retried once, and 429/5xx get backoff. Editing creates a new version. Other `{{variables}}` read input, output, expected or metadata, whole or by path (`$.messages[-1].content`), with a preview in the console | | **Experiment** | Dataset × model × prompt from the registry (published revision) × evaluators | ### Decision-model judge The judge can be a decision alias (TypeSafe Jev, Cloudflare Clef via System One): a boolean score becomes the probability of "yes", and a categorical one becomes the most likely category. ### Code evaluators Besides the LLM judge, an evaluator can be a deterministic rule (equality, contains, regex, valid JSON, JSON field, length) that scores without calling a model, in experiments, on live traffic and in the sample test. ## How an experiment runs The experiment runs in the background, **through the gateway itself**, as the dataset's team (principal `eval:`). This means: - routing, fallbacks, quotas, budget, ledger and logs all apply; - the judge does not need its own credential. Execution details: - an item missing a prompt variable fails **without calling the model**; - the run records the dataset's point in time, the prompt revision and the evaluator versions; - the prompt is its published revision, or with [`prompt_tracking`](/docs/features/prompt-registry/#the-prompt-page) any stored revision you choose (`prompt_revision`, 1–100, in `POST /evals/runs`; the prompt page's **Run experiment** fills it in); - a restart resumes pending items; - the id of each judge score is deterministic, so repeating does not duplicate. ### What a run costs Because every model call and every judge call goes through the gateway, the request log already prices them. The experiment list shows a **Cost** column, and the run detail shows the run's cost and each item's cost, read from that log: | Request | Request ID | |---|---| | The item's model call | `eval..` (an API run uses the request ID the client linked) | | Each judge call of the item | `eval...judge..` | How to read the amount: | Shown | Meaning | |---|---| | `US$0.00000436` | Every request of the run or item has a known price; the amount is exact | | `US$0.00000186 (partial)` | Some requests have no known price (for example a fallback whose first provider is not in the price book). The amount is the known part; the tooltip says how many requests are not valued | | `Unknown` | No request has a known price. Unknown is never shown as zero | | `—` | No request of the run or item is in the request log (an item that failed before calling the model) | The comparison of several runs shows the same amounts: a **Cost** column per run in the summary and each run's cost on every item, next to its input and output tokens. Costs are shown only when `usage_valuation` is on and your role has `analytics:read`, the same rule the request journey follows. The amounts come from the valuation the gateway recorded for each request; to get one, give the models a price ([automatic pricing](/docs/features/automatic-pricing/)). In the API, `GET /api/v1/admin/evals/runs` and `GET /api/v1/admin/evals/runs/{id}` return `cost` on the run and on each item, and `GET /api/v1/admin/evals/compare` returns it on each compared run and on each run's item cell: `state` (`known`, `partial` or `unknown`), `known_usd` (exact decimal string), `requests` and `unvalued_requests`. ### From an evaluation to its request Every request ID on the Evals screens is a link to its entry in **Logs → Requests**, which opens the request journey: the item's model call in the run detail, each judged request in an evaluator's execution log, each capture on the **Captures** tab, request targets on the **Scores** tab and in annotation queues. The link is the request journey permalink (`#/logs/request/`), so it opens only for people who can see that request. Long IDs are shortened in the middle; hover for the whole ID, or use the copy button next to it. ## Compare experiments In **Evals → Experiments**, select 2 to 5 runs of the same dataset and click **Compare runs**; selections survive paging, so runs on different pages can be compared. The equivalent API is `GET /api/v1/admin/evals/compare?runs=a,b,c`. In the run list, a **latest** chip marks the most recent run of each dataset, and a **baseline** chip marks the run the comparison measures against (while you pick, the oldest picked run, which becomes the default baseline). The experiment list's **Scores** column shows every score's average and count, and for a categorical score every label with its count, for example `topic billing 10 · other 30 · support 20`. The default baseline is the oldest run, and you can change it with the **Baseline** field or **Make baseline** next to a compared run. The comparison shows: - **Per run:** completed and failed items, average latency, p50 and p95, input and output tokens, the cost (see [What a run costs](#what-a-run-costs)) and the average of each score (or the label distribution). Next to each average of a compared run is its difference from the baseline's average, over all items: `0.77 (60) −0.03 vs baseline` reads "an average of 0.77 over 60 scores, 0.03 below the baseline". - **Per score, against the baseline:** how many items improved, got worse, stayed the same, changed label or ended up **without a score** (an item or judge that failed). - **Per item, side by side:** each run's output, the scores and the delta, its latency, input and output tokens and cost, and its request ID, which links to the request journey (see [From an evaluation to its request](#from-an-evaluation-to-its-request)). - **Charts** (**Charts** box): the average of each score per run, the distribution of each score and of latency in bins that are the same for all runs, and tokens. They cover every item, even with a filter. Each run keeps its color when the baseline changes, and each chart has a **Data** table. In a narrow card the distribution is drawn sideways, one labelled row per bin. - **On a phone** the summary and the items are cards, one per run or item, each value labelled with its run. On a wide screen a comparison of many runs scrolls sideways with the first column pinned. Comparison rules: - **Higher is better** for numbers and booleans. - **Regression** is a drop in score or an item that failed where the baseline completed. - **Filters:** **Regressions only** and **Changes only** apply before pagination. - **Filter by score:** keep the items whose score passes a condition, for example `correct = false` or `helpfulness > 4`. Pick the score, an operator and a value, and optionally the run it applies to (by default an item matches when any compared run passes). Numbers and booleans (`true`/`false`) take `=`, `≠`, `>`, `≥`, `<` and `≤`; labels and text take `=` and `≠`. An item without that score in a run does not match there, also for `≠`. The score filter combines with **Regressions only** and **Changes only**, and like them applies before pagination. - **Edited item:** when the runs read different versions of an item, the item is flagged and the comparison warns you. The responses are not comparable. ### Share a comparison The address of the page holds the comparison, so reloading it or sending the link opens the same comparison, with its baseline and filters: ```text #/evals/compare?runs=,[,…]&baseline=[&items=regressed|changed][&score=&op=eq|ne|gt|gte|lt|lte&value=[&score_run=]] ``` For example `https://gateway.example.com/ui/#/evals/compare?runs=run_a,run_b&baseline=run_a&items=regressed&score=correct&op=eq&value=false`. The link carries run IDs only: whoever opens it sees the comparison only if they can read those runs, and the costs only under the rule above. Opening a comparison adds a browser history entry, so **Back** returns to the run list. ### Compare API parameters | Parameter | Default | What it does | |---|---|---| | `runs` | required | 2 to 5 run IDs of one dataset, comma separated | | `baseline` | the first run | The run the others are measured against; one of `runs` | | `filter` | `all` | `regressed` or `changed` keep only those items | | `score` | none | A score name (up to 80 characters); turns on the score filter | | `score_op` | `eq` | `eq`, `ne`, `gt`, `gte`, `lt` or `lte`; the last four need a number or `true`/`false` | | `score_value` | required with `score` | The value to compare with, up to 200 characters; `true` and `false` read as 1 and 0 | | `score_run` | any run | Apply the score filter to one of `runs` only | | `limit`, `offset` | `100`, `0` | Item page, 1–500 items, after every filter | The response has `total_items` after the filters, `score_filter` echoing the score filter (absent without one), and on each compared run `avg_delta` (per score with an average in both runs: this run's average minus the baseline's, over all items; absent on the baseline) and `cost`. Each item's run cell has `request_id`, `input_tokens`, `output_tokens` and `cost`. ## Lists: columns, views, exports and pages The Experiments, Datasets, Evaluators, Scores and Score configs lists share one toolbar: | Control | What it does | |---|---| | Search and filters | Narrow the rows: text search on Experiments, Datasets, Evaluators and Score configs, plus status, kind or archive filters; on **Scores**, the exact score name, the source and the target type, applied by the server | | **Columns** | Show or hide columns. The name column and the actions always show; some columns (dataset, creation time, IDs, versions) are hidden until you show them | | **View** and **Save view** | Save the current columns, filters and rows per page under a name, and apply it later; **Delete view** removes it | | **Export CSV** | Downloads every row that matches the filters, not only the page on screen, with the visible columns and the values the list shows. Amounts are exact decimals in USD (`0.00000622`, `0.00000186 (partial)`, `unknown`); a text that a spreadsheet would run as a formula starts with an apostrophe. Scores are read from the server 500 at a time, up to 10,000 rows; narrow the filters for more | | Pages | 25, 50 or 100 rows per page, **Previous** and **Next**, and the range shown, for example `26–50 of 260` | Columns, rows per page and saved views are kept in this browser for each console user and list. They are a convenience: a private window or blocked site data starts from the defaults, and nothing about them is stored on the server. The **Scores** tab counts every score your teams can read, not the first page. The list is paged by the server: ```bash curl -s "https://gateway.example.com/api/v1/admin/evals/scores?source=annotation&limit=50&offset=50" \ -H "Authorization: Bearer $ADMIN_TOKEN" ``` ```json {"data": [{"id": "score_1", "name": "helpfulness", "value": 4, "source": "annotation", "target_type": "request", "target_id": "req_…"}], "total": 260, "offset": 50, "limit": 50, "has_more": true} ``` `limit` is 1–500 (any other value reads 100, as before paging), `offset` is 0–100000 (anything else is `400 invalid_request`; narrow the filters to reach older scores). `total` counts the scores that match the filters among the teams you can read, and `has_more` says whether a later page has rows. Scores are ordered newest first. When a list is empty, the screen says what the object is and links its section of this guide. ## Score analytics **Evals → Analytics** (or `GET /api/v1/admin/evals/score-analytics?team_id=…&name=…`) shows one team's score over a period, with source, target and type filters: | Type | What appears | |---|---| | Numeric | Count, mean, standard deviation, range and an exact 10-bin histogram | | Boolean | Count and true rate | | Categorical | Count per label and mode | | Text | Count and trend only | - **Trend:** the series goes by hour, day or week, with zeros in periods with no score, drawn with a time axis and a count axis; hover or focus a period to read its count and average. A period with the only scores is drawn as a labelled point. The default period is the last 30 days by the database clock. - **Mixed types:** a name with values of more than one type (no score config) asks you to choose the type. - **Agreement:** stays on the same tab, now with RMSE and macro F1. ## Judge templates **New evaluator → Start from a template** fills in the evaluator with a ready-made rubric: | Template | Measures | |---|---| | correctness | Agreement with the reference | | faithfulness | Absence of unsupported claims | | helpfulness | Usefulness, from 1 to 5 | | relevance | Relevance, from 1 to 5 | | conciseness | Conciseness, from 1 to 5 | | safety | Absence of toxic or dangerous content | | tone | Tone: rude, neutral or courteous | | language_match | Response in the user's language | - **Edit and test before saving.** The template is only a starting point. - **Higher is always better**, so the comparison counts drops as regressions. - **Expected output:** templates that read `{{expected}}` need datasets with an expected output. Live traffic does not have one. ## Feedback from applications ```bash curl -s https://gateway.example.com/v1/scores -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \ -d '{"id":"fb-123","name":"thumbs","data_type":"boolean","value":1,"target":{"type":"request","id":""}}' ``` The key needs the `scores:write` scope. The target must be a request, a session or a run item belonging to the key's team. Repeating the same `id` updates the score. With `evaluation_results` on, the same call also takes span, trace and join-key targets, assessments, statuses, JSON values, end-user feedback with its submitter and batches of up to 1000: see [Evaluation results](/docs/features/evaluation-results/#send-results-from-your-application). ## Experiments from code and in CI With the `evals_public_api` flag (requires `evals`), a team key runs experiments from code, the usual pattern for experiments in CI. | Scope | What it allows | |---|---| | `evals:read` | `GET /v1/datasets`, `/v1/datasets/{name}`, `/v1/datasets/{name}/items`, `/v1/datasets/{name}/runs` and `/runs/{run}` | | `evals:write` | `POST /v1/dataset-runs` and `POST /v1/dataset-run-items` | | `scores:write` | `POST /v1/scores` with a `run_item` target | The flow of a CI script: 1. **Open the run:** `POST /v1/dataset-runs` with `dataset_name` and `name`. The run pins the dataset version in `dataset_as_of`. 2. **Read the items:** `GET /v1/datasets/{name}/items?as_of=&page=1&limit=50`, page by page. 3. **Run the application** on each item. If it calls the model through the gateway, keep the `X-Request-Id` from the response. 4. **Link the result:** `POST /v1/dataset-run-items` with `run_id`, `item_id`, `output` and `request_id`. With `request_id`, latency and tokens come from the ledger. Without it, send `latency_ms` if you want. 5. **Score:** `POST /v1/scores` with `target {"type":"run_item","id":""}`. 6. **Compare:** in the console (**Evals → Experiments**, where the runs appear tagged **API**) or at `GET /v1/datasets/{name}/runs/{run}`. ```python from openai import OpenAI import json, urllib.request GW, KEY = "https://gateway.example.com", "" def api(method, path, body=None): req = urllib.request.Request(GW + path, data=body and json.dumps(body).encode(), method=method, headers={"Authorization": "Bearer " + KEY, "Content-Type": "application/json"}) return json.load(urllib.request.urlopen(req)) run = api("POST", "/v1/dataset-runs", {"dataset_name": "capitals", "name": "prompt-v2", "metadata": {"commit": "abc123"}}) items = api("GET", f"/v1/datasets/capitals/items?limit=100&as_of={run['dataset_as_of']}")["data"] client = OpenAI(base_url=GW + "/v1", api_key=KEY) for item in items: raw = client.chat.completions.with_raw_response.create(model="gpt-4o-mini", messages=[{"role": "user", "content": item["input"]}]) answer = raw.parse().choices[0].message.content linked = api("POST", "/v1/dataset-run-items", {"run_id": run["id"], "item_id": item["id"], "output": answer, "request_id": raw.headers["x-request-id"]}) api("POST", "/v1/scores", {"name": "correct", "value": int(item["expected_output"] in answer), "target": {"type": "run_item", "id": linked["item"]["score_target"]}}) ``` Rules that apply to CI: - **Everything belongs to the key's team.** Datasets, runs and requests of another team respond as if they did not exist. - **The dataset is read-only through the key.** Items are created and edited in the console. - **Opening by name also works:** `dataset_name` + `run_name` in `dataset-run-items` opens the run on first use and reuses it afterwards. API run names are unique per dataset (409 `duplicate` on `POST /v1/dataset-runs`). - **Relinking an item replaces the result** (200 instead of 201). Repeating a CI step duplicates nothing. - **Console runs do not accept links** (409 `invalid_state`). - **A run can be partial.** `total` counts the items linked so far; `dataset_items` is the size of the dataset version the run pinned. A run with `total` below `dataset_items` did not run every item, and the console shows it as **incomplete** ("1 of 4 items linked"). - **Higher is better.** The comparison counts a drop as a regression. A score where lower is better (words, cost) shows up as an "improvement" when it gets worse. Send the inverse, or a range where higher is better. - **Linking right after the answer:** the usage ledger row is written after the response leaves, so `POST /v1/dataset-run-items` waits up to 3 seconds for the request to appear before answering `400 request_not_found` (the same wait and the same answer for another team's request and for an unknown one). A stream's row lands when the stream ends: read the whole response first. ## Evaluating real traffic (`eval_capture`) With the `eval_capture` flag (requires `evals` and the control plane encryption key), each team decides whether to capture a sample of its own chat traffic. The policy (sampling rate, optional models, retention) is configured in **Evals → Captures** or with `PUT /api/v1/admin/evals/capture-policies/{team}`; choosing a team in the form loads its saved policy, and when you have only one team the form loads it for you. **Save policy** stays disabled until the saved policy has loaded, so saving never replaces it with the form's defaults. The Captures tab lists the most recent captures (up to 200), 25 per page. **With `content_capture_evaluation` on, the capture policy is the team's [content capture policy](/docs/features/content-capture/#one-policy-for-audit-and-evaluation-content_capture_evaluation).** An administrator adds the `evaluation` purpose to it under **Governance → Content capture**; the Captures tab shows which teams are captured for evaluation and no longer has a policy form, and `PUT /api/v1/admin/evals/capture-policies/{team}` answers `409 capture_policy_moved`. What changes for evaluation: | | Without the flag | With `content_capture_evaluation` | | --- | --- | --- | | Requests judged | Buffered Chat Completions | Chat Completions, Messages, Responses and generateContent, buffered or streamed, cache hits included | | What the judge reads | The messages after guardrail masking and the answer | The same: the request's **sent view** (after the input guardrails) and the answer; never the request as received | | Who else reads it | People with `evals:manage` in the team | The same people, for every record the policy keeps for evaluation; each read is audited | | Sampling | By `request_id`, in the evaluation policy | The content policy's `sample_rate` (random per request), then its `evaluation.sample_rate` (by `request_id`), then each evaluator's own sampling | | Retention | 1 to 90 days | The content policy's `evaluation.retention_days`, or its `retention_days` | | Encryption | The control plane key | The content key, one data key per record | | A matched request that cannot be judged | No result | A `skipped` result: `content_not_captured` (kept for audit alone, or no text answer) or `content_truncated` (longer than `max_bytes`) | An [evaluator](/docs/features/evaluators/) reads the records the policy keeps for evaluation. Existing evaluation policies are moved for you, and captures already stored stay readable until they expire: see [the upgrade](/docs/features/content-capture/#upgrade-the-evaluation-capture-policies-move-here). The rest of this section applies either way. | Aspect | How it works | |---|---| | **Policy** | A deterministic sampling rate by `request_id`, optional models and retention from 1 to 90 days | | **Content** | The messages **after guardrail masking** and the response, encrypted with the control plane key. They are deleted when they expire. Reading the content requires `evals:manage` and `content_sent:read` of the team ([the content ladder](/docs/features/content-capture/#who-can-read)): the built-in administrator and team administrator hold both | | **What is excluded** | Streaming responses and responses served from the cache. Traffic from the judges and experiments themselves is never captured, so there is no evaluation of evaluation | | **Evaluators** | [Evaluators](/docs/features/evaluators/) judge the captured requests: each owns its scope, its filter, its sampling and its status, and runs as a job of a durable queue in PostgreSQL shared by the replicas with `SKIP LOCKED` (a claimed job carries a five-minute lease; only jobs whose lease expired go back to the queue; a draining replica claims none, and a job it stops before judging returns without spending an attempt) | | **Reasoning for the judge** | An evaluator with `include_reasoning: true` (**Include the model's reasoning** in the evaluator form; `false` by default) also gives its judge the model's reasoning, after the prompt and labelled as not part of the answer. It needs [`content_capture_reasoning`](/docs/features/content-capture/#the-models-reasoning-content_capture_reasoning), which keeps the reasoning as its own part of the record; without it, or for an answer with no reasoning, the judge reads the answer alone. Code evaluators take no reasoning | | **Images for the judge** | With [`content_capture_media`](/docs/features/content-capture/#captured-images-and-audio-content_capture_media) the record keeps images as attachments; an evaluator with `multimodal: true` gets them back in place of their references (up to five) | | **Automatic pause** | An evaluator pauses itself, with the reason, when the judge is refused or becomes invalid (disabled model, quota, budget): see [status and health](/docs/features/evaluators/#status-and-health). Transient failures are retried with backoff and never pause it | | **Annotation queues** | Queue writes take `review_queues:manage` and reviewing takes `reviews:annotate` ([who may do what](/docs/features/human-review/#who-may-do-what)); with `review_multi_annotator` a queue also takes traces and spans, several reviewers per item, assignment, drafts, export and calibration, and `review_automations` fills it from live traffic: see [Human review](/docs/features/human-review/). Fields are the team's score configs, with an optional description. Targets are captured requests, sessions (the reviewer sees the summary and up to 20 captured turns, in order) or experiment items; a target that does not exist or belongs to another team is refused. "Review" locks the next item for the reviewer for 10 minutes, and Ctrl/⌘+Enter saves the form (all or nothing) and opens the next one. A queue with assigned people is worked only by them and by the global admin (`403 not_assigned` for everyone else); without assignments, anyone who can write in the team reviews. "Items" lists items by state, with who locked and who completed them, and removes pending ones; completed items stay, because they record the annotation. The queue can be edited (the team does not change) and deleted, and its scores remain on the targets | | **Corrected output and comments** | During review, "Corrected output" starts with the original response, shows the diff and saves a `correction` score named `output`, one per target. When you send the capture to a dataset, the correction becomes the expected output. Next to it is the target's comment thread: only the author or a global administrator can delete. Registry prompts have the same thread, in the prompt's team. An `@` in a comment mentions someone who can read the thread, and that person sees the comment in the **Mentions** tab. Comments accept Markdown: lists, code, bold, italics and links | | **Open in Playground** | A capture (Captures tab) or the item under review opens in the Playground with the system prompt, the history and the last request in the input box, ready to resend; the one-shot transfer stays in memory for the current tab/session/access generation, is cancelled on reload/logout or a source-page change while loading, and never submits automatically. See [handoff lifecycle](/docs/features/playground/#open-a-captured-conversation) | | **Agreement** | Two scores on the same targets. For numbers: Pearson, Spearman and mean absolute error. For labels: accuracy, Cohen's κ and a confusion matrix. This is how you calibrate a judge against people before you trust it | ## Metrics and monitors With `evaluation_metrics`, evaluation results are also [metrics](/docs/features/evaluation-metrics/) and the Usage screen has a Quality tab. With `evaluation_monitors`, the **Monitors** tab holds the team's [monitors](/docs/features/evaluation-monitors/), and the Evaluators tab shows how many monitors each evaluator has and starts a pass-rate, failure count or judge spend monitor from it. ## Known limits - **A small judge is lenient.** In real validation, a 1.5B Qwen2.5 marked as "correct" answers that did not name the requested city. Use a capable model as the judge, check it with **Test on a sample** and measure its agreement with human annotation. - **Streaming and Responses** are judged only with [`content_capture_evaluation`](/docs/features/content-capture/#one-policy-for-audit-and-evaluation-content_capture_evaluation); without it, live evaluation captures buffered Chat Completions only. - **Request IDs are chosen by the client.** When two teams (with [organization admins](/docs/features/organization-admins/), possibly two organizations) send the same `X-Request-Id`, each keeps its own capture, encrypted for its team, and a rule only ever judges or backfills its own team's. `GET /api/v1/admin/evals/captures/{request}?team=` picks one team's capture when the session reads both. - **Backfill window.** Without `until`, a backfill runs up to the database clock, the clock captures are stamped with. ## Targets after a team moves A request, its capture, its spans and trace, a session, a score or evaluation result, a comment and an experiment run belong to the organization they were recorded in. When a team moves to another [organization](/docs/features/organizations/), it keeps its ID, its datasets, evaluators, score configs, rules and queues, but what it recorded under the former organization stays there. The team, and the readers of its new organization, can neither target it nor read it. The former organization's administrators keep reading it, through the organization recorded on each row and with the permissions they already hold: see [when a team moves](/docs/features/organizations/#when-a-team-moves). **Writes.** - A score, an evaluation result, a comment or a review-queue item on a request, a session, a trace, a span, a run or a run item recorded before the move is refused with `400` ("not found for this team"), and the comment thread of such a target answers `404`. Comments already written stay stored and are no longer served. - Anything the team records after the move is a target as usual. A session or a trace that has requests on both sides of the move stays a target through the requests made after it. - Request IDs are chosen by the client. A request ID (or a session) the team uses again after the move is a target again, with an empty comment thread: the comments, the capture and the results the former organization holds under the same ID do not come back with it. - A review queue holds one item per target. A queue that already holds an item for a request ID (or a session, a trace) from before the move keeps it as the former organization's, listed with `former_organization: true` and never handed out; adding the same ID again after the move answers `200` with `{"added":0,"duplicates":1}` and adds nothing. Queue the reused ID in another queue. (A safe default: the earlier item is never shown as the new one's.) - A result of an experiment is recorded with its run, in the organization the run was created in, even when it is written after the team moved (a run still executing). - A review queue passes over a pending item recorded before the move: **Review** hands out the next item the team can still read. The earlier item stays in the queue's list, where an administrator can remove it. - A live-evaluation backfill judges only captures recorded since the move. - The public API refuses (`409`) a new run under a name a run of the former organization already holds in the dataset: choose another name. **Reads.** Every read made for the team returns only what the team recorded in its current organization: | Read | What a moved team gets | | --- | --- | | Captures (the Captures tab, a capture by request ID, the content records, a reveal, an attachment) | Later captures; an earlier one answers `404` | | Traces, spans and the request's trace, on either span engine | Later ones; an earlier trace or span answers `404` | | The [trace explorer](/docs/features/trace-explorer/): lists, facets, figures, the histogram and the chart | Later traces and spans only, in the rows and in every count | | Scores and evaluation results (lists, one result, its revisions, score analytics, agreement, external evaluators, evaluator health) | Later results only | | Runs (the list, a run, a comparison, the dataset's runs on the public API) | Later runs; an earlier one answers `404` | | Comments (a thread, the mentions inbox, the comment count on a trace) | Comments on later targets | | The request log, a request with its cost, its journey, a session summary, the agent graph, replay links, the recent requests and the totals of Usage and of a team's or key's detail, the daily rollups, the cost report, the [usage query](/docs/features/analytics-experience/) | Later requests only | | Alerts shown on a trace, and the execution log of an evaluator | Those of later requests | For a read made through the team, the organization the team is in now decides, not who is asking: the administrator of its organization and a team role read the same rows of the team. The global administrator stands above organizations: a list that is not narrowed to a team still shows every row, and a read that names one team shows that team's rows of its current organization. **Spend follows the same rule, from both sides.** Usage and Analytics totals, the daily rollups, the cost report and the request log count a request for the organization it ran in: the team and its new organization get what was recorded since the move, and the former organization keeps what was recorded there, which its administrators still read through the organization on the row. Budgets, alert scans and the audit events of a move are described in [when a team moves](/docs/features/organizations/#when-a-team-moves). **Narrowing to one team.** `GET /api/v1/admin/evals/runs`, `/evals/scores` and `/evals/captures` take `team_id` and then list that team's rows alone; score analytics and agreement always take one. For a team of the session it is the team in its current organization. An organization administrator may also name a team that left its organization, and gets what the team recorded there: in the console, **Recorded by team** above the Evals tabs, and the team of **Analytics**, list those teams as " (left on )". A team the session may not name is refused (`403` on the lists, `404` on the statistics). A result's revision history (`GET /api/v1/admin/evaluations/{id}/revisions`) is read by whoever reads the result. An evaluator's execution log and its job counts hold the runs of the team's current organization, and a team's alert list holds the alerts raised in its current organization. **Rows with no organization recorded stay with their team**, wherever the team is now. That is every row written with `organizations` off (a request, a span, a result and a run all record none, so turning the flag on later and moving a team treats them alike) and every row written before the column that names it existed. **Upgrade note.** The first two migrations each add one nullable column with no table rewrite: - **211** adds `organization_id` to `gateway_eval_runs`. A run from before it has none recorded and stays with its team. - **212** adds `organization_id` to `gateway_trace_summaries`, the table the trace explorer lists and counts from. With the analytics store span engine the same column is added to its summary table at start. A summary from before the upgrade has none recorded, so an earlier trace of a team that already moved still appears in the explorer's list (its spans and content do not open). To stamp earlier summaries from their spans, run `POST /api/v1/admin/traces/summaries/rebuild` over the days you keep, 31 days at a time. - **213** and **214** put the organization in the daily rollups and in the analytics store's copy of the request log, **235** and **238** let a very large rollup day be rebuilt in slices, **236** records the organization of an alert and **237** the teams that left an organization; all are described in [when a team moves](/docs/features/organizations/#when-a-team-moves). With the database span engine a trace has one summary per team: a trace that has spans on both sides of a move is listed under the organization of its first spans. ## Admin API routes Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/). | Route | What it does | | --- | --- | | `GET /api/v1/admin/evals/agreement` | Agreement between two score names on the same targets: correlation and error for numbers, accuracy and kappa for labels | | `GET /api/v1/admin/evals/capture-policies` | The per-team capture policies of evaluation traffic | | `GET /api/v1/admin/evals/captures` | Capture metadata only: request, team, model and expiry | | `GET /api/v1/admin/evals/captures/{request}` | The decrypted input and answer of one captured request | | `GET /api/v1/admin/evals/comments` | The comment thread of one target, oldest first | | `POST /api/v1/admin/evals/comments` | Adds a comment to a captured request, a session, a run item or a prompt of the team. A request is looked up by `team_id` and its ID together: when two teams each made a request under the same `X-Request-Id`, each comments on its own and reads only its own thread. See [targets after a team moves](#targets-after-a-team-moves) | | `DELETE /api/v1/admin/evals/comments/{id}` | Removes a comment from its thread | | `GET /api/v1/admin/evals/datasets` | Lists the datasets with their item counts | | `POST /api/v1/admin/evals/datasets` | Creates a dataset, optionally with input and expected-output schemas every item must meet | | `GET /api/v1/admin/evals/datasets/{id}` | Reads a dataset and its items, optionally as of an earlier time | | `POST /api/v1/admin/evals/datasets/{id}/items/from-captures` | Turns up to 100 captured requests of the team into dataset items, in one transaction | | `POST /api/v1/admin/evals/datasets/{id}/items/import` | Imports up to 1,000 items from a CSV; one bad line rejects the whole file | | `GET /api/v1/admin/evals/evaluator-templates` | The ready LLM-as-judge rubrics (correctness, faithfulness, helpfulness and others) | | `GET /api/v1/admin/evals/evaluators` | Lists the LLM-as-judge evaluators | | `POST /api/v1/admin/evals/evaluators` | Creates a judge: score name, judge model, prompt and output type | | `POST /api/v1/admin/evals/evaluators/test` | Runs a judge definition on one sample and returns the score, storing nothing | | `PUT /api/v1/admin/evals/evaluators/{id}` | Changes a judge; a changed definition is a new version | | `DELETE /api/v1/admin/evals/evaluators/{id}` | Deletes a judge | | `GET /api/v1/admin/evals/mentionable` | The console users who can read a target's comments, for mention autocomplete | | `GET /api/v1/admin/evals/mentions` | The session user's mentions inbox, newest first | | `POST /api/v1/admin/evals/mentions/read` | Marks the listed mentions, or all of them, as read | | `GET /api/v1/admin/evals/queues` | Lists the annotation queues with assignees and pending and completed counts | | `POST /api/v1/admin/evals/queues` | Creates an annotation queue with its score fields and assignees | | `PUT /api/v1/admin/evals/queues/{id}` | Replaces a queue's name, description, fields and assignees | | `DELETE /api/v1/admin/evals/queues/{id}` | Hides a queue | | `GET /api/v1/admin/evals/queues/{id}/items` | The queue's items, oldest first, with locks and who completed each | | `POST /api/v1/admin/evals/queues/{id}/items` | Adds up to 500 targets (requests, sessions or run items) to a queue | | `DELETE /api/v1/admin/evals/queues/{id}/items` | Removes a pending item | | `POST /api/v1/admin/evals/queues/{id}/next` | Locks the oldest pending item that still has a seat for the reviewer (ten minutes by default) and returns it | | `POST /api/v1/admin/evals/queues/{id}/complete` | Stores every score of the form, all or nothing, and completes the item | | `GET /api/v1/admin/evals/runs/{id}` | One run with its items, outputs, latency, tokens, errors and scores | | `POST /api/v1/admin/evals/runs/{id}/cancel` | Stops a queued or running run | | `GET /api/v1/admin/evals/runs/{id}/compare/{base}` | Per score, the items improved, regressed or unchanged against a baseline run | | `GET /api/v1/admin/evals/score-configs` | Lists the typed score definitions people and judges share | | `POST /api/v1/admin/evals/score-configs` | Creates a numeric, boolean, categorical or text score definition | | `PATCH /api/v1/admin/evals/score-configs/{id}` | Changes a score definition's description | | `DELETE /api/v1/admin/evals/score-configs/{id}` | Archives a score definition | | `GET /api/v1/admin/evals/scores` | Lists scores newest first, filtered by name, target, run or source, a page at a time (`limit`, `offset`) with `total` and `has_more` | | `POST /api/v1/admin/evals/scores` | Records a score annotated by a console user | | `DELETE /api/v1/admin/evals/scores/{id}` | Deletes one score | | `DELETE /api/v1/admin/evals/datasets/{id}/items/{item}` | Archives a dataset item; earlier versions stay readable with `as_of` | | `DELETE /api/v1/admin/evals/evaluators/{id}` | Deletes a judge; past runs keep their snapshot of it | | `GET /api/v1/admin/evals/runs` | Lists the experiment runs with progress, tokens, latency, score averages and, for categorical scores, the count of each label (`score_aggregates..labels`) | | `GET /api/v1/admin/evals/compare` | Puts 2 to 5 runs of one dataset side by side against a baseline, with item and score filters, tokens and cost | | `DELETE /api/v1/admin/evals/queues/{id}` | Hides an annotation queue; the scores it produced stay on their targets | ## See also - [Evals, prompts and Playground](/docs/features/feature-evals/): overview. - [Evaluation results](/docs/features/evaluation-results/): results on spans, traces and sessions, the `/evaluations` API and OTLP export. - [Experiments as traces and regression suites](/docs/features/experiment-traces/): items as traces, dataset versions, judging past runs again, suites in CI. - [Judge calls as linked, labelled traffic](/docs/features/evaluation-tracing/): each judge run as its own linked trace, the origin of every request, evaluator health and cost, evaluation spend. - [Prompt registry](/docs/features/prompt-registry/) and [Playground](/docs/features/playground/). - [Guardrails](/docs/features/guardrails/): the masking applied before capture. # Evaluators **Last updated:** 2026-11-26T07:53:40-03:00 (UTC-3) An evaluator is a judge the gateway runs for you: a model call (an *LLM judge* or a *decision model*), your own JavaScript function (a *code* evaluator), or a ready deterministic *rule*. It reads a span, a trace or a session and writes an [evaluation result](/docs/features/evaluation-results/) on it. An evaluator owns everything about where it runs: - its **scope**: one span, a whole trace, or a whole session; - its **filter**, written in the gateway's [query language](/docs/features/query-language/), and its **sampling**; - its **status**: draft, active, paused or disabled; - its **versions**: every save is a version with a readable spec, two versions compare side by side, live traffic runs the *published* version, and an old version can be restored; - a **test pane** that runs the judge on real traffic before anything is published, and a **preview** of how much traffic the filter selects and what judging it costs per week; - a **daily cost ceiling**; - with `code_evaluators`: **code evaluators**, a **template library**, and **runs on chosen traffic** (Evaluate selection, a query over past traffic, a run on one trace). ## Turn it on ```yaml features: evaluators: true # off by default code_evaluators: true # off by default; code, the library, runs on chosen traffic ``` Both flags are tenant actions. `evaluators` requires `evaluation_tracing`, `trace_query`, `span_store` and `eval_capture` (and what those require: `evaluation_results`, `evals`, `request_logs`); `code_evaluators` requires `evaluators`. The gateway refuses to start with a flag on and one of its requirements off. With plan entitlements, a team gets each when its plan includes it. With `evaluators` off, the Evaluators tab says so; evaluators defined through the API still judge experiment runs, and nothing runs on live traffic. Before you turn it on, check that **content capture keeps what a judge reads.** A judge reads the captured request and answer. Set the team's [content capture policy](/docs/features/content-capture/) with the purpose `evaluation` for the traffic you want judged. A target whose content was not captured is not judged: it gets a `skipped` result with the reason `content_not_captured`, no judge call and no cost. A code evaluator that reads only span facts (its source names no `input`, `input_text`, `output`, `tools`, `expected`, `traces` or `transcript`) needs no capture. ## Scopes and when a run happens | Scope | One run judges | The filter is a query of | The run starts | |---|---|---|---| | `span` (default) | one span: usually a request (`span.kind:request`), or any other span kind | spans | `evaluation.span_delay` after the span is stored (5 s by default) | | `trace` | the whole trace: `{{input}}` is its first request, `{{output}}` the answer of its last one | traces | once the trace stayed without a new span for `evaluation.trace_idle` (3 min by default) | | `session` | the whole session: its captured turns in order | traces (a session is in scope when one of its traces matches) | once the session stayed without a new span for `evaluation.session_idle` (30 min by default) | A span the store does not keep is not judged: when a trace already holds `spans.max_spans_per_trace` spans, the spans of its later requests are left out of the store (and counted as `dropped_trace_limit`), and no evaluator run is queued for them. A trace or session run **waits**: every new span of the trace or the session pushes the pending run forward by the idle window, counted from when the span is stored. While it waits, the trace detail shows the run as **Pending · up to N min**. A span that arrives **after** the run is not judged again: one run per evaluator version and target. Publishing a new version while runs are waiting hands them to the new version; pausing the evaluator drops them, and the next span of the trace or session after a resume queues the run again. Each evaluator can override its idle window (`trace_idle_seconds`, `session_idle_seconds`, 5 to 86400). With `session_explorer` on, an application that knows a conversation ended calls `POST /v1/sessions/{id}/close` (key with `scores:write`) and the session's waiting runs become due at once; see [sessions and end users](/docs/features/sessions-and-users/#session-evaluators-and-the-idle-window). Only client traffic is judged by default (`runs_on: live`, origin `app`). `runs_on: experiments` judges the traffic of experiment runs, `both` either. A judge run, an evaluator test, a replay, a helper call and a shadow copy are never judged, whatever the filter says. ## The filter and sampling Request tags, the key, the session and the end user are facts of the request span: a filter on another span kind (`span.kind:provider_attempt span.final:true`) selects by that span's own facts. The filter is one query: `span.kind:request tag.env:prod model:chat-default -cache:hit` for a span evaluator, `tag.env:prod trace.errors>=1` or `child.span.kind:tool` for a trace or session evaluator. Every field of the [query language](/docs/features/query-language/#fields) is available except evaluation results and text search. A span evaluator's filter reads the span itself: `child.` and `parent.` terms belong to trace and session evaluators, which see the whole trace. The same query on **Observability → Traces** lists what the evaluator would judge: the editor's **View matching traffic** opens it. ### Evaluators targeted at a topic With [Topics](/docs/features/topics/) on, a filter may hold a topic term: `span.kind:request topic.intent:"Request a Refund"` for a span evaluator, `topic.intent:"Request a Refund" trace.errors>=1` for a trace evaluator. A topic is known only once Topics has read the unit (a trace or a session) and assigned it, minutes after the traffic: such an evaluator queues nothing when a span is stored, and its runs are queued when a live map assigns the unit, due at once. | Scope | Runs queued on an assignment | |---|---| | `span` | each span of the unit's traces its filter matches, with the unit's topics | | `trace` | each trace of the unit; the whole filter, topic term included, is checked when the run starts, and a trace outside it ends `not_in_scope` | | `session` | the unit's session, checked the same way | The topic term reads the live maps of the evaluator's team and of its organization. The preview, the test pane and a backfill read the same assignments, so a backfill reaches the units already assigned. A topic term needs `topics`: an evaluator saved with one while Topics is off is refused. **Create evaluator** on a topic opens the editor with the draft prompt and the topic term added to the default filter; nothing is saved until you save. A judge that calls a model is **never published without a filter**; a code or rule evaluator, which calls none, may run on every span. A new span judge starts with `span.kind:request origin:app capture:evaluation`. `sample_rate` (greater than 0, at most 1) is the share of the matching targets judged. The choice is a keyed hash of the target per evaluator version: every replica decides the same for a target, so a target is never judged twice. ## Variables The prompt reads the target through variables: | Variable | Scope | Value | |---|---|---| | `{{input}}`, `{{output}}` | all | the captured input and answer (span: the request's own; trace: first request's input, last request's answer; session: first turn's input, last turn's answer) | | `{{tools}}` | span, trace | the tools the judged request offered the model: its `tools` field as sent, in the API the client called (a trace: its first request's); empty when it offered none | | `{{expected}}` | experiments | the dataset item's expected output | | mapped names (`variables`) | all | `{from: input|output|expected|metadata, path}` | | `{{span.}}` | span, trace (the root span) | `name`, `kind`, `subkind`, `status`, `origin`, `model`, `provider`, `provider_model`, `request_id`, `trace_id`, `span_id`, `parent_span_id`, `session_id`, `error_code`, `duration_ms`, `started_at`, `http_status`, `input_tokens`, `output_tokens`, `cost_usd`, `attributes.`, `tags.` | | `{{metadata.}}` | span, trace | one request tag of the judged span (the root span of a trace) | | `{{trace.id}}`, `{{trace.spans}}`, `{{trace.errors}}`, `{{trace.duration_ms}}` | span, trace | facts of the trace | | `{{spans[*].}}`, `{{spans[kind:tool].}}`, `{{spans[0].}}` | trace | a field of every span, of the spans of one kind (a JSON list), or of one span by position (negative from the end) | | `{{session.id}}`, `{{session.turns}}`, `{{session.transcript}}` | session | the session's ID, its number of captured turns, and the turns as `User: … / Assistant: …` in order | | `{{session.traces[*].input}}`, `{{session.traces[*].output}}`, `{{session.traces[0].request_id}}` | session | one field of every turn, or of one turn | | `{{prompt.id}}`, `{{prompt.revision}}`, `{{prompt.source}}` | span, trace (its first request) | with [`prompt_tracking`](/docs/features/prompt-registry/#prompt-revision-on-traffic) (refused when saved or published without it; an evaluator saved with it keeps running when it is turned off, and a run that reads the variables is skipped with `prompt_variables_unavailable`): the prompt revision the judged request recorded and how it is known (`rendered`, `declared`, `system`) | | `{{prompt.variables.}}` | span, trace | one variable of that revision, read back from the request's captured content through the revision's template | | `{{prompt.query}}`, `{{prompt.context}}` | span, trace | the variable the prompt marks as the question or the retrieved text (`variable_roles`), else the first conventional name it declares (`query`, `question`, `input`, ... and `context`, `documents`, `passages`, `sources`, ...) | A trace or session prompt must read the answer (`{{output}}`) or the target by path (`{{spans[...]}}`, `{{session.transcript}}`). A path that does not exist for the scope is refused when you save. One variable's value is at most `evaluation.max_variable_bytes` (64 KiB by default). A longer value (a long session, a trace with thousands of spans) **skips the run** with `content_truncated` instead of judging part of the content. A session of more than 50 requests is skipped the same way: a judge never reads the start of a conversation as if it were all of it. A prompt variable is read from what the request actually sent: the template is aligned with the end of the conversation (its last message with the latest message of the same role whose whole text the template matches, each earlier one with an earlier message), and the text where a placeholder stands is the variable's value, kept only when it is the only reading of the text. Nothing new is stored, and the capture policy decides as it does for `{{input}}`. When the request named no revision, its content was not captured for evaluation, its messages do not follow the revision's template (the client edited the text), the prompt is not the evaluator's team's, or the role or variable has no single value (two placeholders with nothing between them, a context that itself contains the text after its placeholder, or a variable used twice with two values), the run is **skipped** with `prompt_variables_unavailable` and the reason, never judged with an empty question or context. This is how a hallucination check reads the question and the context of a RAG prompt whatever its variables are called: mark them once in the prompt. Path variables exist on live traffic, in tests and in backfills. An experiment judges dataset items, which have no span behind them: an evaluator whose prompt reads a path is refused in an experiment run. ## Versions Every save is a new version. A save is a **draft**: it never changes the status or what is published. - **Publish** makes a version the one live traffic runs and activates the evaluator. Results carry the version that produced them. - The **readable spec** of a version lists name, type, judge route, temperature, max tokens, scope, runs on, sampling, filter, tracing, output, pass criteria, the daily cost ceiling, the variables and the prompts. - **Compare** two versions: the line difference of their specs and, per version, results, pass rate, errors, skipped, the judge cost from the ledger, the cost per result and the judge tokens (average and total). - **Restore** writes an older version's spec as a new version. Publish it to put it on live traffic. ```text Name: goal Type: llm_judge Judge route: chat-judge (gateway alias) Temperature: 0 Max tokens: 600 Scope: trace Runs on: live Sampling: 25% Filter: tag.env:prod Tracing: enabled Output: categorical [answered, partially_answered, refused] Pass criteria: answered, partially_answered Model reasoning: not read Images: not sent Daily cost ceiling: US$2.00 ## User prompt Did the assistant complete what the user asked? ... ``` An evaluator's **name** is the name of its results and of the `evaluation.` field of the query language, and is unique in its team. It can be changed: results keep the name they were written with and stay joined to the evaluator by its ID. ## Status and health | Status | Meaning | |---|---| | `draft` | saved, never published: it does not run on live traffic. It can be used in experiments and tested | | `active` | the published version runs on matching traffic | | `paused` | no new run; pending runs end without a result; results stay. Resume returns it to `active` | | `disabled` | as paused, for an evaluator you are retiring | The gateway pauses an evaluator by itself, with the reason, when its judge is refused in a way that will not change by itself, when its definition stops being valid, or when its daily cost ceiling is reached. What the judge route answers decides it: | Judge route answers | What the gateway does | |---|---| | `401`, `403` (credentials or access), `404` (the model or route is gone), `400`, `405`, `413`, `415`, `422` (a request the judge cannot take) | the run ends `skipped` with `judge_refused` and the evaluator **pauses**, with the status and code in its reason: fix the route or the prompt, then resume it | | the team's budget or quota refuses the call (`quota_exceeded`) | the run ends `skipped` with `judge_budget_refused` and the evaluator pauses | | `408`, `429`, `5xx` | retried at once within the run (three calls, a short backoff between them), then the run is retried later like the next row | | any other `4xx` (`409`, `425`, a provider's `402`) | the run is retried later with its own backoff (three attempts in all), then ends `error` with `judge_failed`; the evaluator keeps running | The same rules apply to decision-model judges. A decision route takes no budget quota: a quota with a budget on a decision model refuses its calls with `422 quota_profile_unsupported`, which pauses the evaluator; limit decision judges with the evaluator's daily ceiling instead. Health (`ok`, `degraded`, `blocked`) is a second fact, computed from the results: `degraded` when judge errors reach 5% of the judged runs of the last 24 hours, `blocked` when the gateway paused it. ### The evaluators an alias judges for Before you change or delete a model alias, see which evaluators use it as their judge route. Turn on `alias_evaluator_usage` (an operator flag, off by default; requires `evaluators`): - **Model catalog → Edit routing** shows **Used by evaluators**: each evaluator whose `judge_model` is the alias, with its team, scope and status, linked to its page. Deleting the alias in use warns with the count on the confirm button (*Confirm delete (2 evaluators judge through it)*); deleting it anyway pauses those evaluators at their next run, as the table above says. - `GET /api/v1/admin/models/{id}/evaluators` (`evals:read`) answers `{model, evaluators: [{id, name, team_id, type, status, paused_reason, scope, published_version}], count, truncated}`, by name, at most 200 (`truncated` says there are more). The list is the reader's: only the evaluators of teams you read evaluations of (all of them for a global administrator or viewer), never a count of other teams' or organizations'. A deleted evaluator is not listed. Evaluators declared in the configuration file are listed like the others. With `judge_guardrails` on, the same panel and answer also list the guardrails: `judge_guardrails` are the [judge guardrails](/docs/features/judge-guardrails/) backed by one of the listed evaluators (so their judge runs on this alias), and, for a reader with `guardrails:read`, `guardrails` are every enabled guardrail that checks the alias, each with its type, stages, mode and place in the run order. Deleting the alias warns with the judge guardrails too. An evaluator can also guard traffic as a judge guardrail, and be scored by its pass rate on the two sides of a canary in a [route experiment](/docs/features/route-experiments/). ## Cost: the preview and the daily ceiling A judge is a request of the team through the gateway: it goes through routing, quota and the ledger like any other, under the principal `eval:evaluator:` with origin `evaluation`. The **preview** (the editor shows it under the filter and again before Publish) answers, for the last 24 hours and 7 days, how many targets the filter selects, the weekly volume after sampling, how many of the matching spans have captured content, and the **weekly judge cost**. The cost is *measured* from the evaluator's own judge calls of the last 7 days when there are at least 5, otherwise *estimated* from the judge route's price, the size of the prompt and the mean tokens of the matching targets; it is *unknown* when the route has no price. `max_daily_cost_usd` is the evaluator's own ceiling per UTC day, read from the ledger before each run. Once the day's judge spend reaches it, runs are skipped with `judge_budget_refused` and the evaluator pauses with `cost_ceiling_reached`. Runs already in flight finish, so the day can end a few runs above the ceiling (at most `evaluation.worker_concurrency` per replica). The ceiling needs a priced judge route: publishing an evaluator with a ceiling on a route that has no price is refused (`422 ceiling_needs_price`), since every call would be unvalued. The team's own budgets and quotas apply as well: a judge call they refuse skips the run with `judge_budget_refused` and pauses the evaluator. `tracing: false` stores no judge span for the evaluator's runs; the result, its judge request and the ledger line stay. ## Test before you publish The editor's test pane runs the judge on real traffic. Nothing is stored as a result; each judge call is a request of the team with origin `playground` and its cost in the ledger. - **Auto test** takes the N newest targets the filter selects (1 to `evaluation.test_max_targets`) and shows the batch pass rate, the categories, and per target the verdict, the explanation, the cost and a link to the trace. - **Test manually** takes one target you pick, shows the resolved value of every variable, lets you edit them, and runs once (Ctrl/⌘+Enter): the verdict, the raw answer of the judge and the cost. The explanation, the raw answer, the previews and the resolved variables are content: they are shown to a reader of the team's captured content (`content_sent:read`), and each read is audited. Without it the test still runs and shows verdicts and costs. Testing an evaluator that reads the model's reasoning or the images of the input also takes `content_reasoning:read` or `content_media:read`. The preview's list of matching targets is shown to a reader of the request log (`logs:read`); a filter on a cost field is previewed by a reader of costs (`analytics:read`). ## Backfill Publishing never runs on past traffic. **Backfill** runs the published version over a window of the past (at most 31 days, at most 1,000 targets per call, newest first), without sampling. Live runs go before backfill runs in the worker. A dry run answers how many targets match and what judging them costs, and queues nothing. A target the version already judged is skipped. ## Code evaluators With `code_evaluators`, an evaluator can be your own JavaScript: a source that defines `function evaluate(data)` and returns the verdict. It calls no model and costs nothing; it runs everywhere an evaluator runs (live traffic, the test pane, backfills, runs on chosen traffic and experiment runs). ```javascript function evaluate(data) { // a trace evaluator: data.spans are the trace's spans const errors = data.spans.filter((s) => s.status === "error").length; return { value: errors, assessment: errors ? "fail" : "pass", reasoning: errors + " error spans" }; } ``` `data` is the target as plain JSON: | Scope | `data` holds | |---|---| | `span` | `scope`, `trace_id`, `span_id`, `request_id`, `session_id`, `span` (its fields), `input` (the captured request), `input_text` (the last user message), `output` (the captured answer), `tools` (the request's `tools` field, or `null`), `expected` (`null`), `metadata` (the request tags) | | `trace` | `scope`, `trace_id`, `session_id`, `root` (the root span), `spans` (every span, in order), `input`, `input_text`, `output`, `tools` (the first request's) | | `session` | `scope`, `session_id`, `traces` (each turn's `request_id`, `input`, `input_text`, `output`), `input`, `input_text`, `output` | | experiment item | `scope: item`, `input`, `input_text`, `output`, `expected` (the item's expected output), `metadata` | A span holds the fields of the path variables (`name`, `kind`, `status`, `model`, `duration_ms`, `cost_usd` as a number, …) plus `attributes` and `tags`; never the end user or the customer identity. `input` and `output` are `null` when the content was not captured, or when the source never names them (the run then opens no capture). What `evaluate` returns decides the result: | Return | Result | |---|---| | `true` / `false` | a boolean output's value; a numeric output scores its `max` or `min` | | a number | a numeric output's value, within `min` and `max`; a boolean output takes `0` or `1` | | a non-empty string | a categorical output's label: one of its categories | | `null`, `undefined` or `""` | no result: `skipped` with `code_no_result` | | `{value, assessment, reasoning, metadata}` | `assessment` (`pass`, `fail`, `none`) overrides the pass criteria; a boolean output may answer `assessment` alone; `reasoning` is stored as judge reasoning (encrypted, shown to content readers); `metadata` (an object) is shown by the test pane only | | anything else (an array, an object with other keys, a value outside the range) | `error` with `code_invalid_result` | The source has, beside the language, `console.log` (up to 20 lines of 200 characters, 4 KiB, shown in the test pane, never stored) and three pure built-ins: `similarity(a, b)` (1 minus the token edit distance over the longer length, or Jaccard over token sets above 500 tokens; 0 to 1; at most 50 calls per run and 32,768 characters per string), `jsonPath(value, path)` (`a.b[0].c` or `$.a.b`, from an object or a JSON string) and `countTokensApprox(text)` (about one token per 4 characters). `GET /api/v1/admin/evals/code-builtins` answers them with the fields of `data` and the effective limits; the editor shows them under the code. **The sandbox.** The source runs in the gateway's extension runtime: QuickJS-ng compiled to WebAssembly, pinned by digest, on wazero, a fresh instance per run. There is no host operation at all: no network, file system, environment, process, real clock or randomness, and nothing survives a run. The source is compiled when it is saved (a syntax error is refused) and limited by `evaluation.code`: | Setting | Default | Bounds | Past it | |---|---|---|---| | `evaluation.code.timeout_ms` | `500` | 50 to 10000 | `error` `code_timeout` | | `evaluation.code.memory_pages` | `256` (16 MiB) | 64 to 4096 | the run's WebAssembly memory ceiling | | `evaluation.code.heap_bytes` | `8388608` (8 MiB) | 1 MiB to 128 MiB, plus 1 MiB within `memory_pages` | `error` `code_memory_limit` (a deep recursion too) | | `evaluation.code.max_program_bytes` | `16384` | 1 KiB to 256 KiB | the save is refused | | `evaluation.code.max_input_bytes` | `262144` | 4 KiB to 4 MiB | `skipped` `content_truncated` | | `evaluation.code.max_result_bytes` | `16384` | 1 KiB to 256 KiB | `error` `code_output_limit` | | `evaluation.code.team_concurrency` | `2` | 1 to 64 | a further run waits for a free slot, up to four times `timeout_ms` plus a second; past that it ends `code_busy`, and a live job is tried again | A throw is `error` `code_error`. What the program threw (and a key or a label it returned that the output does not take) can hold captured content, so it is never stored on the result, the job or the span: the test pane shows it, after the reason, to a reader of the sent view only. A code run's error or skip is final: the same source on the same data answers the same, so it is not retried. A code run is traced like a judge: a judge span of type `code`, linked to what it judged, under the principal `eval:evaluator:`; the source is in the version, never on the span. A code evaluator takes no judge route, prompt, rule, variables, messages, images, reasoning, temperature, max tokens or cost ceiling. ## The template library With `code_evaluators`, **New evaluator** opens the library: start from scratch as an LLM judge, a decision model, code or a rule, or pick one of more than 60 templates by category (Quality, Safety and security, Agents and tools, Retrieval, Conversations, Classification, Gateway signals, Images, Rules and checks), with a search and the example output of each. **Your evaluators** lists the team's own evaluators: starting from one makes a copy (a new evaluator at version 1 with the same definition and filter). An empty Evaluators page recommends three starting points. A template only fills the editor: every field stays editable, and nothing runs until you publish. A template with a placeholder (`<>`) is saved as a draft and cannot be published until the placeholder is replaced (`422 placeholder_unfilled`). Each template carries its fixtures: the documented cases it is tested against (`fixtures` in `GET /api/v1/admin/evals/evaluator-templates`): code and rule templates are run on them, judge and decision templates have their prompt rendered with them and the documented verdict mapped by their pass criteria. A fixture documents the behaviour; it is not a claim of accuracy. | Category | Templates | |---|---| | Quality | correctness, faithfulness, hallucination, helpfulness, relevance, conciseness, completeness, equivalence, fluency, summarization, rule_adherence, language_match, failure_to_answer, sentiment, tone | | Safety and security | safety, toxicity, prompt_injection, pii_leakage, out_of_scope, topic_relevancy, decision_out_of_scope, pii_patterns (code) | | Agents and tools | goal_completeness and agent_task_completion (trace), tool_selection, tool_argument_correctness, tool_call_efficiency (trace), engineering_task_type, empty_tool_result and repeated_tool_calls (code) | | Retrieval | answer_groundedness, context_precision, context_recall, retrieval_sufficiency | | Conversations | user_frustration, conversation_completeness, conversational_coherence (session), decision_customer_frustration, session_turn_summary and all_caps_frustration (code) | | Classification | chat_intent, input_topic, decision_input_topic | | Gateway signals (code) | trace_error_spans, latency_budget, fell_back, attempt_count, served_from_cache, guardrail_flagged, cost_over_budget | | Images (multimodal judges) | explicit_content_image, sensitive_imagery | | Rules and checks | exact_match, mentions_expected, similarity_to_expected, keyword_overlap, valid_json, json_required_fields, regex_match, response_length, user_input_contains (code); the seven rules (`rule_exact_match`, `rule_contains`, `rule_not_contains`, `rule_regex`, `rule_json_valid`, `rule_json_field_equals`, `rule_length_between`) | With `code_evaluators` off the gallery is the eight judges it always had. ## The decision model's question A decision-model evaluator sends the model a **state** and one **question**. The editor builds the state from the fields you tick (the request, the answer, the model, the status, the duration, the tags) as one JSON object of variables, and says how many fields and characters it sends. `output.question` is the question (up to 1,000 characters; name the state's fields in backticks); for a categorical output, `output.options` says what each category covers (up to 300 characters each). Without them the gateway asks its own question. The result keeps the probabilities in `value_json`: `{"probability": 0.91}` for a yes/no question, `{"probabilities": {...}, "confidence": 0.86}` for a choice; the test pane shows them as bars. One evaluator asks one question and writes one result. ## Run on chosen traffic With `code_evaluators`, an evaluator's published version can be run on traffic you choose, as **on-demand runs**: - **Evaluate selection**: on **Observability → Traces**, select traces (or spans) of one team and choose **Evaluate**, then one or more of the team's published evaluators; - **Evaluate** on a trace: the same for the open trace (or the selected span); - **Runs → Run over a query**, on the evaluator's page: a query of the Traces screen over the last 24 hours, 7 or 30 days, up to a limit, with **Count and cost** first. A run judges what was chosen, whatever the evaluator's filter and sampling say: a span evaluator judges the root span of a chosen trace (or the chosen span), a trace evaluator the trace, a session evaluator the trace's session. A target already judged is judged again, and its result replaced. A run takes at most `evaluation.max_run_targets` targets (1,000 by default, at most 1,000) and only targets in the evaluator's team's span store: another team's trace, or one gone, is left out. An active or a paused evaluator runs; a draft or a disabled one does not (`409 not_published`). Each target is a job of kind `on_demand` with the run's ID, in the execution log beside the live ones. The evaluator's **Runs** tab lists the runs with their progress (waiting, running, judged, failed, cancelled and the outcome of each target); it reads again every 3 seconds while a run is open, and the run goes on on the server when you leave the page. **Cancel** ends the targets not started yet (`cancelled`); a running one finishes. Running and cancelling take `evaluators:publish`, and a run also `logs:read`; each is an audit action (`eval.evaluator.run`, `eval.evaluator.run_cancel`) and an event of the evaluator. **Create evaluator from this span**, on a trace, opens the editor with the span as the test pane's first manual target. ## Evaluators declared in the configuration file `evaluation.evaluators` declares evaluators as code, beside the ones made in the console. The list is applied when the gateway starts (and its evaluation worker with it): each entry is checked by the same rules as a save, stored as a new version when its definition changed (version source `yaml`), published at once and set to its status. An evaluator the file declares is **managed by the configuration file**: the console shows it with a *Declared in the configuration file* mark and offers no edit, publish, status change or delete, and the API refuses those writes with `409 managed_by_configuration`. Tests, runs on chosen traffic and results work as for any other evaluator. An entry removed from the list leaves its evaluator **disabled**, with its versions and results kept. **Evaluations → Evaluators → Settings** and `GET /api/v1/admin/evaluation/settings` (`evaluation.evaluators`) list the declared evaluators the reader may see, with their kind, scope, sampling and status. ```yaml evaluation: evaluators: - id: ev_trace_errors team_id: team-a name: trace_error_spans code: | function evaluate(data) { return { value: data.spans.filter((s) => s.status === "error").length }; } output: {data_type: numeric, min: 0, max: 10000, pass: {op: eq, value: 0}} scope: trace filter: "origin:app" - id: ev_helpful team_id: team-a name: helpfulness judge_model: judge-default prompt: "Request: {{input}}\nAnswer: {{output}}\nWas the answer helpful?" output: {data_type: boolean} filter: "span.kind:request capture:evaluation" sample_rate: 0.1 ``` | Field | Default | Meaning | |---|---|---| | `id` | required | 1 to 64 letters, digits, `_` or `-`, unique in the list; the evaluator's ID | | `team_id` | required | the team that owns the evaluator | | `name` | required | the evaluator's name (results and metrics are named after it), unique in the team | | `description` | empty | shown on the evaluator's page | | `judge_model`, `prompt` | | an LLM judge or decision model: the judge route and the prompt; exactly one of `judge_model` and `code` | | `code` | | a code evaluator's JavaScript (needs `code_evaluators` in the team's plan) | | `output` | required | the output, as in the API: `data_type` (`boolean`, `numeric`, `categorical`), `min`/`max`, `categories`, `pass`, `question`/`options` | | `scope` | `span` | `span`, `trace` or `session` | | `filter` | empty | the query-language filter; a judge evaluator needs one | | `sample_rate` | `1` | (0, 1] of the matching targets | | `runs_on` | `live` | as in the API | | `status` | `active` | `active`, `paused` or `disabled` | At most 200 evaluators are declared. A malformed list (an ID twice, a missing team or name, both or neither of `judge_model` and `code`, no output) stops the gateway at startup with the field named. An entry that is well formed but does not pass the checks of a save (an unknown judge route, an invalid filter, a template placeholder not filled, `code_evaluators` off) is left out and logged (`declared_evaluator_invalid`), and the others are applied; if an earlier start had applied it, its evaluator is disabled until the entry passes again, so a broken edit never leaves the old version judging; an entry whose ID or name is taken by an evaluator the console made is logged as `declared_evaluator_conflict` and left alone. Declared evaluators need the `evaluators` feature. ## Settings The `evaluation` block of the configuration file is read at startup: change it and restart the gateway. **Evaluations → Evaluators → Settings** and `GET /api/v1/admin/evaluation/settings` show the effective values and where each comes from (`default` or `configuration`). The same block also holds `evaluation.metrics` and `evaluation.monitors`, described in [evaluation metrics](/docs/features/evaluation-metrics/) and [evaluation monitors](/docs/features/evaluation-monitors/); one endpoint answers the whole block. ```yaml evaluation: trace_idle: 3m session_idle: 30m span_delay: 5s worker_concurrency: 4 test_max_targets: 10 max_variable_bytes: 65536 job_retention_days: 30 max_run_targets: 1000 # code_evaluators code: {timeout_ms: 500, memory_pages: 256, heap_bytes: 8388608} # code_evaluators metrics: {max_evaluations: 200} # evaluation_metrics monitors: {tick: 30s, items: []} # evaluation_monitors ``` | Setting | Default | Bounds | Meaning | |---|---|---|---| | `evaluation.trace_idle` | `3m` | 5 s to 24 h | a trace stays this long without a new span before a trace evaluator judges it | | `evaluation.session_idle` | `30m` | 5 s to 24 h | the same wait for a session evaluator | | `evaluation.span_delay` | `5s` | 0 to 5 min | wait before a span evaluator judges a span, so the captured content is stored first | | `evaluation.worker_concurrency` | `4` | 1 to 64 | judge runs one replica makes at a time | | `evaluation.test_max_targets` | `10` | 1 to 50 | targets of one automatic test | | `evaluation.max_variable_bytes` | `65536` | 1024 to 1048576 | bytes of one variable of a prompt | | `evaluation.job_retention_days` | `30` | 1 to 365 | days finished runs stay in the execution log | | `evaluation.max_run_targets` | `1000` | 1 to 1000 | targets of one on-demand run (`code_evaluators`) | | `evaluation.code.*` | see [code evaluators](#code-evaluators) | | the limits of one code run (`code_evaluators`) | | `evaluation.evaluators` | `[]` | at most 200 | evaluators declared in the file, see [above](#evaluators-declared-in-the-configuration-file) | ## Permissions | Permission | Who has it | What it allows | |---|---|---| | `evals:read` | every member, for its teams | read evaluators, versions, results, health, the execution log and the preview | | `evals:manage` | team administrators, for the teams they administer | save a draft, restore a version, delete | | `evaluators:publish` | team administrators, for the teams they administer; admin | publish, pause, resume, disable, backfill, and run on chosen traffic and cancel a run: what reaches traffic | | `evaluators:test` | the same | run the test pane: judge calls on real traffic | A [custom role ceiling](/docs/features/custom-roles/) of a team administrator can withhold `evaluators:publish` and `evaluators:test`. Every publish, restore, status change, automatic pause, backfill and delete is an audit action (`eval.evaluator.*`) and an event of the evaluator with the status and version before and after (the **Health** tab). ## The console **Evaluations → Evaluators** lists each evaluator with its type, scope, status, filter and sampling, results of the last 7 days, pass rate, judge route, 7-day cost and health. An evaluator's page has four tabs (five with `code_evaluators`, which adds **Runs**): **Results** (pass rate, the series with a marker at each version, categories, the results with their traces, filtered by All, Pass, Fail, Errors or Skipped and by version), **Configuration** (the readable spec), **Versions** (compare, restore, publish) and **Health** (errors and skips by reason, the history of changes and the execution log with pending runs). With [evaluation monitors](/docs/features/evaluation-monitors/) or [review automations](/docs/features/human-review/#automations) on, the page has a fifth tab, **Automations & monitors**: - **Monitors** (`evaluation_monitors` and `monitors:read`): the monitors that watch the evaluator, and, with `monitors:manage` for its team, a **Pass-rate monitor**, a **Failure count monitor** or a **Judge spend monitor** (not for a rule evaluator, which makes no judge call) to start from it, with the evaluator and its team filled in. The list also has a **Monitors** column: how many monitors watch each evaluator and the worst of their states. When the monitors cannot be read, the column says *Unavailable* and the tab says so; it never shows "none". - **Automations** (`review_automations` and `evals:read`): the automations of the evaluator's team whose query reads its results (`evaluation.…`), and, with `review_queues:manage`, **Review failing results**, which opens the automation form of Review with `evaluation..assessment:fail` over traces filled in: choose the queue or dataset, the share and the caps there. An evaluator whose name holds characters the query language cannot write (anything but letters, digits, `_` and `-`) cannot be named by an automation; rename it first. The editor has the form on the left and the test pane on the right, with **Save draft**, **Publish** and **Cancel**. On a screen narrower than 768 px the configuration is read-only; pause, resume, results, versions and health work at any width. ## API Every request takes a console session; writes take the CSRF token. | Request | Purpose | |---|---| | `GET /api/v1/admin/evals/evaluators` | Evaluators with their live configuration, status, list figures (`figures`) and what each published version runs (`live`) | | `GET /api/v1/admin/evals/evaluators/{id}` | One evaluator: definition, status, `published_version`, `draft_ahead` | | `POST /api/v1/admin/evals/evaluators` | Create: a draft at version 1 | | `PUT /api/v1/admin/evals/evaluators/{id}` | Save a draft: a new version; live traffic keeps the published one | | `DELETE /api/v1/admin/evals/evaluators/{id}` | Delete; results and versions stay | | `GET /api/v1/admin/evals/evaluators/{id}/versions` | The versions, newest first | | `GET /api/v1/admin/evals/evaluators/{id}/versions/{version}` | One version with `spec` and `spec_text` | | `GET /api/v1/admin/evals/evaluators/{id}/compare` | Two versions (`?a=&b=`): the line diff and the figures of each | | `POST /api/v1/admin/evals/evaluators/{id}/publish` | Publish `{"version": n}` (the latest when omitted) and activate | | `POST /api/v1/admin/evals/evaluators/{id}/restore/{version}` | Write an older version's spec as a new version | | `POST /api/v1/admin/evals/evaluators/{id}/status` | Pause, resume or disable: `{"status": "paused", "reason": "..."}`, `"active"` or `"disabled"` | | `GET /api/v1/admin/evals/evaluators/{id}/preview` | Matches, weekly volume and cost of the saved definition (`?version=` for an older one) | | `POST /api/v1/admin/evals/evaluators/preview` | The same for a definition that is not saved yet: `{"evaluator": {...}}` | | `POST /api/v1/admin/evals/evaluators/{id}/test` | `{"mode": "auto", "n": 5}` or `{"mode": "manual", "target": {...}, "variables": {...}, "dry_run": false}`, with `evaluator` for unsaved edits; `{id}` is `draft` for a definition not saved yet | | `GET /api/v1/admin/evals/evaluators/{id}/results` | The Results tab: summary, series, categories, version markers and the results (`from`, `to`, `assessment`, `status`, `version`, `limit`, `cursor`) | | `GET /api/v1/admin/evals/evaluators/{id}/health` | The Health tab: health, errors and skips by reason, run counts, events, judge latency, today's spend | | `GET /api/v1/admin/evals/evaluators/{id}/jobs` | The execution log (`status`, `limit`) | | `POST /api/v1/admin/evals/evaluators/{id}/backfill` | Run the published version over past traffic: `{"since": "...", "until": "...", "limit": 500, "dry_run": true}`; a dry run answers the count and the cost and queues nothing | | `GET /api/v1/admin/evaluation/settings` | The effective `evaluation` block (these settings, `metrics` and `monitors`) and the source of each value; `features` says which of `evaluators`, `evaluation_metrics` and `evaluation_monitors` are on. Needs `config:read` and one of the three flags | | `POST /api/v1/admin/evals/evaluators/{id}/run` | `code_evaluators`: run the published version on `{"targets": [{"trace_id": "…", "span_id": "…"}]}` or `{"query": {"scope": "traces", "q": "…", "from": "…", "to": "…", "limit": 100}}`; `dry_run` counts and costs; `202` with the run | | `GET /api/v1/admin/evals/evaluators/{id}/runs` | `code_evaluators`: the on-demand runs with their progress | | `GET /api/v1/admin/evals/evaluators/{id}/runs/{run}` | `code_evaluators`: one run, for polling | | `POST /api/v1/admin/evals/evaluators/{id}/runs/{run}/cancel` | `code_evaluators`: end the targets not started | | `GET /api/v1/admin/evals/evaluator-templates` | The template library and its categories (`code_evaluators`), else the eight judges | | `GET /api/v1/admin/evals/code-builtins` | `code_evaluators`: the signature, returns, built-ins, fields of `data` and limits of code evaluators | Example: a trace evaluator, saved, previewed and published. ```bash curl -s -X POST "$GW/api/v1/admin/evals/evaluators" -b cookies -H "X-CSRF-Token: $CSRF" -H 'Content-Type: application/json' -d '{ "team_id": "platform", "name": "goal", "judge_model": "chat-judge", "scope": "trace", "filter": "tag.env:prod", "sample_rate": 0.25, "max_daily_cost_usd": "2.00", "prompt": "Did the assistant complete what the user asked?\nFirst request: {{input}}\nLast answer: {{output}}\nTools used: {{spans[kind:tool].attributes.tool}}", "output": {"data_type": "boolean", "pass": {"op": "eq", "value": 1}} }' # {"id":"ev_…","version":1,"status":"draft","draft_ahead":true,"effective_idle_seconds":180,…} curl -s "$GW/api/v1/admin/evals/evaluators/ev_…/preview" -b cookies # {"unit":"traces","matches":{"24h":412,"7d":2950},"sampled_weekly":738, # "cost":{"basis":"estimated","per_run_usd":"0.000142","weekly_usd":"0.104796",…}, # "matching_query":"origin:app tag.env:prod","query_scope":"traces","warnings":[]} curl -s -X POST "$GW/api/v1/admin/evals/evaluators/ev_…/publish" -b cookies -H "X-CSRF-Token: $CSRF" -d '{}' # {"status":"active","published_version":1,"draft_ahead":false,…} ``` A result of this evaluator has `scope: trace`, the trace's ID, `evaluator_version: 1`, the judge request `evaluator.ev_….v1..`, the judge trace and the judge cost. `evaluation.goal.assessment:fail` on the Traces screen lists the traces it failed, and `evaluation.goal.version:1` those one version judged. ## Result reasons | Status | Reason | Meaning | |---|---|---| | `skipped` | `content_not_captured` | the target has no content captured for evaluation (or its capture expired) | | `skipped` | `content_truncated` | the capture was cut at the policy's `max_bytes`, or a variable passed `evaluation.max_variable_bytes` | | `skipped` | `prompt_variables_unavailable` | the prompt reads `{{prompt.query}}`, `{{prompt.context}}` or `{{prompt.variables.}}` and the judged request's value could not be read (the reason says why) | | `skipped` | `judge_budget_refused` | the evaluator's daily ceiling was reached, or the team's budget or quota refused the judge call | | `skipped` | `judge_refused` | the judge route answered `400`, `401`, `403`, `404`, `405`, `413`, `415` or `422`, or the gateway refused the call (the route is not allowed or is gone); the evaluator pauses | | `error` | `output_unparseable` | the judge's answer was not the requested JSON (a `max_tokens` too low cuts it) | | `error` | `judge_failed` | the judge route failed after the retries (`408`, `429`, `5xx`, or another `4xx` such as `409`) | | `error` | `content_unreadable` | the capture could not be decrypted | | `skipped` | `code_no_result` | a code evaluator returned `null`, `undefined` or `""` | | `error` | `code_timeout`, `code_memory_limit`, `code_output_limit` | a code run passed `evaluation.code` | | `error` | `code_error` | the code threw (the message is the cause) | | `error` | `code_invalid_result` | the code returned what its output cannot take | | `error` | `code_busy` | the team's code runs stayed full through every attempt | A target outside the filter gets **no result**: the run ends as `not_in_scope` in the execution log. ## Limits and upgrade notes - A decision-model judge is an alias whose model has the `systemone` capability and not `chat` (with `systemone_decisions` on). The rendered prompt is the decision's state and the result one question: a yes/no probability for a boolean output (pass at 0.5 or more), the most probable category for a categorical one. Numeric and JSON outputs need an LLM judge. - **Upgrading from live rules.** The live rules of earlier releases (`/api/v1/admin/evals/rules`) are converted into evaluators once, at the first start, whatever the flags say: each rule becomes an evaluator with the rule's filter and sampling, and the rule row keeps `migrated_to`. There is no separate rule worker any more, so a converted rule judges live traffic again only once `evaluators` is on, with what it requires (`span_store`, `trace_query`, `evaluation_tracing`, `eval_capture`) and in the team's plan. A start that converts rules while `evaluators` is off logs `evaluator_rules_folded_while_off` with the count. A deployment that stored overrides or plan grants under the earlier id `evaluators_v2` has them renamed to `evaluators` at boot. - A rule evaluator's scope is `span`; a code evaluator takes any scope. - One run of a code evaluator writes one result: a source cannot write several named results (write one evaluator per result). - Code runs share the gateway's process and CPU: timing side channels between runs are not prevented, and a run may spend its whole limit. A team that needs physical isolation needs its own replicas. - The judges use the gateway alias you choose: they inherit that provider's terms and data handling, and no provider key is ever stored for an evaluator. - Migration 240 adds the columns and tables; every existing definition becomes version N of its evaluator, and definitions that experiment runs had snapshotted are recovered as older versions. Migration 260 adds the code column, the run of an on-demand job and the runs table. # Evaluation results on spans, traces and sessions **Last updated:** 2026-11-24T13:32:58-03:00 (UTC-3) With **evaluation results** on, every score the gateway stores, whether an LLM judge wrote it, a code evaluator, a reviewer, your application through the API or your end users as feedback, becomes an **evaluation result** attached to what it judged: a span, a whole trace or a session. Each result carries a normalized verdict (`pass`, `fail` or `none`), a typed value, a run status, the evaluator and the exact version that produced it, who submitted it, and the same key, principal, team and organization as the traffic it judged. Results show on the request log, in the trace drawer and on the session, become events on the trace's spans, and leave over OTLP with the trace and span IDs of what they judged, so your tracing backend joins them to the request too. Nothing changes for the request path: results are written by the judge workers, the review screens and the API, never while a request is served. ## Turn it on ```yaml storage: provider_encryption_key_env: GATEWAY_PROVIDER_ENCRYPTION_KEY # judge reasoning is stored encrypted features: evals: true evaluation_results: true span_store: true # recommended: results attach to the exact span ``` | Flag | Default | What it turns on | | --- | --- | --- | | `evaluation_results` | `false` | Evaluation results: the new fields on every score, the `/evaluations` API, span, trace, session and feedback targets on `POST /v1/scores`, results on the request log, the trace drawer and sessions, OTLP export, and the background migration of older scores. Requires `evals` and `storage.provider_encryption_key_env`. A tenant action: with `feature_plan_entitlements` a team's plan must include it. Changeable at runtime from **Settings → Features** or `PUT /api/v1/admin/features/evaluation_results` | With `feature_plan_entitlements`, a write whose team plan cannot be read fails (503 `entitlement_unavailable`, or a judge retries) rather than guessing. The gateway refuses to start with `evaluation_results` on and no `storage.provider_encryption_key_env`: a judge's reasoning is content and is never stored in clear. With the flag off the gateway stores scores exactly as before, and `POST /v1/scores` accepts exactly the payloads it accepted before. The same holds, with the flag on, for a team whose plan does not include `evaluation_results`: its scores, judges and reviews keep the old behavior, and the migration leaves its scores alone. ### What happens when you turn it on 1. New results are written with all the fields below. 2. The gateway builds the result indexes on the score table without blocking writes (`CREATE INDEX CONCURRENTLY`), then a background migration converts older scores, 500 every two seconds, until none is left. It is resumable (a restart continues where it stopped) and safe with several replicas. Follow it with `GET /api/v1/admin/evaluations/backfill` (global roles: it counts every team): ```json {"started_at":"2026-11-23T14:00:02Z","finished_at":"2026-11-23T14:00:09Z","migrated":1840,"batches":4,"remaining":0} ``` Each older score gets its scope from its target, its trace ID from the latest request log row of the same request ID and team (a reused request ID names its latest request, as the request journey does), its span from the span store when it holds the request, its evaluator and version from its metadata, and an assessment from the evaluator's **current** pass criteria (`none` without them). Every migrated row is marked `assessment_backfilled: true`, so you can tell a derived verdict from one recorded when it was judged. A judge's explanation moves from the clear-text comment to encrypted reasoning; human comments stay where they are. ## What a result holds | Field | Values | Meaning | | --- | --- | --- | | `scope` | `span`, `trace`, `session`, `run_item`, `run` | What was judged. A request is its own span (`scope: span`). | | `trace_id`, `span_id` | W3C hex | The judged span; a trace result has only the trace (it judges the whole trace and shows on its root span) | | `request_id`, `session_id` | | The judged request and its session | | `assessment` | `pass`, `fail`, `none` | The verdict. From the evaluator's pass criteria, or what the API or a reviewer said | | `metric_type` | `boolean`, `score`, `categorical`, `json`, `text` | The kind of value | | `value`, `string_value`, `value_json` | | A number (boolean as 0 or 1), a label (with its mapped number when the label defines one), a JSON value of at most 8 KiB, or a text | | `status` | `ok`, `error`, `skipped` | Whether the evaluator could judge. Only `ok` results are counted, averaged or included in a pass rate | | `status_reason`, `error` | lowercase code; `{type, message}` | Why a result is `error` or `skipped`: `judge_failed`, `judge_refused`, `output_unparseable`, `content_not_captured` (the request's capture expired, or [the team keeps it for audit alone](/docs/features/content-capture/#one-policy-for-audit-and-evaluation-content_capture_evaluation)), `content_truncated` (the request or its answer is longer than the capture policy's `max_bytes`), `content_unreadable`, or your own code from the API | | `source` | `llm`, `code`, `human`, `api`, `feedback` | Who produced it | | `evaluator_id`, `evaluator_version` | | The evaluator and the exact version that produced it | | `submitter`, `join_key` | | For feedback: who gave it, and the external key it was joined on | | `origin` | `app`, `experiment` | Tells experiment results apart from results on production traffic | | `judge_trace_id`, `judge_request_id`, `judge_cost_usd`, `judge_cost_state` | | The judge run that produced the result and what it cost, filled with [evaluation tracing](/docs/features/evaluation-tracing/#the-judge-fields-of-a-result) | | `key_id`, `principal`, `team_id`, `organization_id`, `model` | | The judged traffic's identity, from its request log row | | `valid`, `revision`, `edited`, `updated_at`, `updated_by` | | Edit state; see [Edit a result](#edit-a-result) | | `reasoning`, `reasoning_state` | `shown`, `reader_grant_required`, `expired` | The judge's reasoning. A judge writes it from the sent view of what it judged, so it is shown to readers with `content_sent:read` of the result's team ([the content ladder](/docs/features/content-capture/#who-can-read)): administrators, organization admins and team administrators by role, anyone else with a `content:read` grant. `reader_grant_required` means the session lacks that permission. Showing explanations writes one audit row per team and answer (`evaluation.reasoning.read`) before any is decrypted; if it cannot be written, none is shown | A failed judgement is no longer silent: when an evaluator's judge fails for good, is refused (budget, quota, model), or finds the request's capture expired, the request gets an `error` or `skipped` result with the reason, visible next to the others and left out of every count. A later successful judgement of the same rule replaces it and keeps it as an earlier revision. ### Pass criteria on an evaluator Give an evaluator's output a `pass` rule and each of its results gets `pass` or `fail`: ```json {"data_type": "numeric", "min": 0, "max": 1, "pass": {"op": "gte", "value": 0.7}} {"data_type": "boolean", "pass": {"op": "eq", "value": 1}} {"data_type": "categorical", "categories": ["good", "neutral", "bad"], "pass": {"labels": ["good"]}} ``` `op` is `gte`, `gt`, `lte`, `lt` or `eq`. Without `pass` the assessment is `none`. ## Send results from your application `POST /v1/scores` with a key of scope `scores:write` keeps accepting the payloads it always did. With the flag on it also accepts: ```bash curl -s https://gateway.example.com/v1/scores \ -H "Authorization: Bearer $GATEWAY_KEY" -H "Content-Type: application/json" \ -d '{"name":"thumbs","metric_type":"boolean","value":0,"assessment":"fail", "trace_id":"5bf92f3577b34da6a3ce929d0e0e4736","span_id":"00f067aa0ba902b7", "source":"feedback","submitter":"user-123"}' ``` Name exactly one target: | Target | Fields | Notes | | --- | --- | --- | | A span | `span_id` with `trace_id` | W3C hex, exactly as the gateway returns them in `traceparent` and OTLP (no decimal conversion; uppercase is read as lowercase). The span must be one of the team's; a span the span store does not hold (an application's own span) is accepted when its trace contains a request of the team, and a span another team's request holds never is | | A trace | `trace_id` | The trace must contain a request of the team | | A request | `request_id`, or `target: {"type":"request","id":…}` | The request's own span | | A session | `session_id`, or `target: {"type":"session","id":…}` | The team must have requests in the session | | An external entity | `join_key` | Every request of the team that carried `X-Gateway-Feedback-Key` with that value (see [Feedback keys](#feedback-keys)), the 100 newest: one result on each. Only when no request carried the header, the requests tagged with the usage tag `feedback_key` (compatibility, same bound). A key on no request is refused (400) | | An experiment item or run | `target` as before | | An unknown target, or another team's, is refused with 400: results never attach to traffic the key cannot see. ### Feedback keys To attach feedback to requests by your own ID (a support ticket, an incident, an order), send it on the requests: ```bash curl -s https://gateway.example.com/v1/chat/completions \ -H "Authorization: Bearer $GATEWAY_KEY" -H "X-Gateway-Feedback-Key: INC-2026/42" \ -d '{"model":"chat-default","messages":[{"role":"user","content":"My order is late"}]}' ``` and later send the feedback with the same value as `join_key`: ```bash curl -s https://gateway.example.com/v1/scores -H "Authorization: Bearer $GATEWAY_KEY" \ -d '{"id":"csat-INC-2026-42","name":"csat","metric_type":"score","value":2,"join_key":"INC-2026/42","source":"feedback","submitter":"support-bot"}' ``` - `X-Gateway-Feedback-Key` takes one value of 1–200 printable ASCII characters without spaces; anything else answers 400 `invalid_feedback_key` before the request is sent. It is read whenever `evaluation_results` is on for the gateway, whatever the team's plan (with the flag off the header is ignored). A request answered by a semantic fallback alias keeps it. - It is stored on the request log row (`feedback_key`, also sent with the record to [log destinations](/docs/features/observability/)) and on the request span (attribute `feedback_key`, in the database or the analytics store, whichever holds spans). It is never a usage tag, a metric label or an analytics dimension, and needs no entry in `usage_tags.allowed_values`. Browser apps may send it: it is in the built-in CORS request headers. - A `join_key` matches only requests of the writer's team (and so of its organization): the same key in another team or organization is never joined. When several requests carried it, the result is written on each of the 100 newest and the answer is `{"data":[...]}`, one result per request; a key joins only rows of the team's current organization. With a client `id`, each result gets `-<10 hex>` derived from its request (the first 117 characters of the `id` are kept), however many requests match, so a replay never duplicates. Other fields: `metric_type` (or the older `data_type`), `value`, `string_value`, `value_json`, `assessment`, `status` (`ok`, `error`, `skipped`; an `error` needs `error: {"type", "message"}`), `status_reason`, `source` (`api` by default, or `feedback`, which needs `submitter`), `evaluator_id`, `evaluator_version`, `comment` (≤2000 characters, stored in clear), `reasoning` (≤8000 characters, stored encrypted and never echoed), `metadata` (≤4 KiB) and `id` (a client ID makes retries safe). A name that has a label (score configuration) is validated against it: its type, range or categories. Send up to 1000 results in one call as `{"scores": [ … ]}`. The batch is validated whole before anything is stored; an invalid item answers 400 naming it (`scores[3]: …`). ## Read and edit results The console session API, with `evals:read` to read and `evals:manage` to write, always within the session's teams: | Method and path | Purpose | | --- | --- | | `GET /api/v1/admin/evaluations` | Results, newest first. Filters: `scope`, `trace_id`, `span_id`, `request_id` (up to 200, comma-separated), `session_id`, `name`, `source`, `assessment`, `status`, `evaluator_id`, `metric_type`, `join_key`, `run_id`, `ids`, `team_id`, `lens=feedback`, `include_invalid=true`. A value outside the set of `scope`, `source`, `assessment`, `status` or `metric_type` answers `400 invalid_request` with the set. `limit` 1–200 (50); page with the returned `next_cursor` | | `GET /api/v1/admin/evaluations/{id}` | One result | | `POST /api/v1/admin/evaluations` | A reviewer's result (`source: human`), with `team_id` and a target as above | | `PATCH /api/v1/admin/evaluations/{id}` | Edit a result | | `GET /api/v1/admin/evaluations/{id}/revisions` | The earlier values of an edited result | | `GET /api/v1/admin/evaluations/backfill` | Progress of the migration of older scores | `GET /api/v1/admin/evals/scores` keeps answering for one minor version with the same rows, a `Deprecation: true` header and a link to `/evaluations`. `GET /api/v1/admin/evals/evaluators` also lists, under `external`, the result names your applications send without an evaluator, with their scopes, sources and pass rate (`pass / (pass + fail)` over `ok` results). ### Edit a result `GET` and `PATCH /api/v1/admin/evaluations/{id}` read and edit one result of the session's teams; another team's result answers 404. ```bash PATCH /api/v1/admin/evaluations/score_6e00c3cc62819318f4ae5895 {"value": 0.5, "assessment": "fail", "reason": "too generous", "revision": 0} ``` Send any of `value`, `string_value`, `value_json`, `assessment`, `comment` and `valid`, with an optional `reason` (≤500 characters). The earlier values are kept as a revision, the result reads `edited: true` and the console marks it **edited** with its history, and the edit is in the audit log (`eval.result_edit`). Pass the `revision` you read to refuse an edit that raced another one (409 `revision_conflict`). `"valid": false` withdraws a result: it leaves lists and counts (read it with `include_invalid=true`) and its values stay in the history. A result produced again by the same evaluator on the same target (a resumed run, a rule judging again) replaces its value the same way and keeps the previous one as a revision, so a target never has two results of the same evaluator; a withdrawn result stays withdrawn. ## In the console - **Request log:** each request shows chips for its results (name, value, pass in green, fail and **ERROR** in red, **SKIPPED** in amber, *edited*). - **Trace drawer:** a span with results has an eval count in the tree; the span's panel lists its results with their source, scope, evaluator version, reason, reasoning (for readers with `content_sent:read`) and, for an edited result, its history. - **Session:** filtering the request log by a session shows the session's results, on the session itself and on its requests. Every view works at phone width: chips wrap under the request ID and lists stack. ## On spans and over OTLP When you read a trace, each result appears as a `gen_ai.evaluation.result` event on the span it judged (its own span, else its request's span, else the trace's root), and the span gains `gateway.evaluation.count` and `gateway.evaluation.fail_count`. With an [OTLP trace exporter](/docs/features/observability/#logs-and-traces-otlp) configured, every stored or edited result with a trace is also exported as a short `evaluation ` span, a child of the span it judged (a trace result is a span of the trace without a parent), carrying the same event. Both use one bounded set of attributes: `gen_ai.evaluation.name`, `gen_ai.evaluation.score.value` (numbers and booleans), `gen_ai.evaluation.score.label` (labels, at most 128 characters), `gateway.evaluation.id`, `gateway.evaluation.assessment`, `gateway.evaluation.status`, `gateway.evaluation.status_reason`, `gateway.evaluation.source`, `gateway.evaluation.scope`, `gateway.evaluation.metric_type`, `gateway.evaluation.evaluator.id`, `gateway.evaluation.evaluator.version`, `gateway.evaluation.revision`, `gateway.evaluation.valid` (only when false), plus `request.id` (empty for a trace result) and the identity attributes (`gateway.key.id`, `gateway.principal`, `gateway.team.id`, `gateway.organization.id`). Text and JSON values, comments and reasoning never become attributes: they may hold what a person wrote. A session result has no trace and is not exported as a span. An edit exports the result again with its new `revision`. The exporter is bounded and never waits: a full queue drops and counts (`gateway_otel_dropped_total{signal="traces"}`). ## Where results are stored Results follow the [span store engine](/docs/features/traces/#where-spans-are-stored): - `spans.engine: database` (and whenever no analytics store is configured): every result is in PostgreSQL, in `gateway_eval_scores`, with its revisions in `gateway_eval_score_revisions`. - `spans.engine: analytics_store`: results from judges, code evaluators, the API and feedback on a span, trace or session are written straight to the analytics store (`gateway_evaluation_results_v1`, a versioned ReplacingMergeTree, with `gateway_evaluation_revisions_v1`). Human results and experiment results stay in PostgreSQL, because annotated-trace retention, review queues, corrections and experiment runs read them there. A result in the database before the switch stays there and is still read and edited there, and an ID the analytics store holds stays in the analytics store; every read answers from both, each result once. If the analytics store cannot be read, results answer `503 analytics_store_unavailable`, never an empty list. Switching back to `spans.engine: database` stops reading the analytics store: results written there are no longer shown (as for spans); move back only after exporting them if you need them. In both cases judge reasoning stays in PostgreSQL (`gateway_eval_reasoning`), encrypted with the provider encryption key and included in key re-encryption; an end-user or customer erasure removes their results and reasoning in both engines. With the analytics store engine, edits of one result are serialized within a replica; two replicas editing the same result at the same instant can both succeed: the later edit wins, and the history keeps the value both edits replaced, not the first edit's value. Pass `revision` and edit from one place when that matters. ## Limits | Limit | Value | | --- | --- | | `value_json` | 8 KiB | | `comment` / `reasoning` | 2000 / 8000 characters | | `submitter`, `join_key` | 200 characters | | Batch | 1000 results | | List page | 200 results; `request_id` and `ids` filters 200 values | | Results shown on one trace | 500; events on one span 20 (more are counted in `gateway.evaluation.events_dropped`) | | Encrypted reasoning | the capture's retention for live judgements, 90 days otherwise (also for reasoning the migration moved); deleted with its result | ## Upgrade notes - Migration 201 adds columns, constraints (`NOT VALID`) and tables only; no existing row is rewritten or scanned by it. The indexes and the background migration start when the flag is turned on. - During a rolling upgrade an older replica keeps writing scores the old way; the migration converts them as it finds them. - Source names change from `eval` and `annotation` to `llm`/`code` and `human`; filters by either name return both. - Before downgrading, turn `evaluation_results` off: older versions ignore the new columns. # Judge calls as linked, labelled traffic **Last updated:** 2026-11-26T03:21:52-03:00 (UTC-3) A judge is a model call the gateway makes for you. With **evaluation tracing** on, that call stops being an anonymous request among your application's: - every request log row says **how the request entered** the gateway (its *origin*): your application, the console Playground, a judge, an experiment, an evaluator test, one of the gateway's own feature calls (a *helper* call, with its sub-kind) or a shadow copy; - every **judge run is its own trace**, with a judge span linked both ways to the span it judged, in the stored spans and over OTLP; - every [evaluation result](/docs/features/evaluation-results/) carries the **judge trace**, the **judge request** and **what the judgement cost**, read from the ledger; - every evaluator reports its **health** (ok, degraded, blocked) and its **cost over the last 7 days**; - **Cost** and **Usage** split spend and volume by origin, so evaluation, Playground and helper spend are their own lines, each billed to the team and organization that caused it; - each client request **counts once**: helper calls and fallback attempts are linked to the request they were made for and stay out of request, success and latency counts, while their tokens and cost are counted. The trace of the request that was judged is never touched: its duration, its spans and its cost stay its own. Nothing is added to the request path beyond naming the origin on the row the request already writes. ## Turn it on ```yaml features: evals: true evaluation_results: true # the judge fields live on evaluation results evaluation_tracing: true span_store: true # recommended: stores the judge spans and the links ``` | Flag | Default | What it turns on | | --- | --- | --- | | `evaluation_tracing` | `false` | Everything on this page. Requires `evaluation_results` (the gateway refuses to start otherwise). A tenant action: with `feature_plan_entitlements` a team's plan must include it for its judge runs to be traced and for its readers to see the judge links, health and cost. Changeable at runtime from **Settings → Features** or `PUT /api/v1/admin/features/evaluation_tracing`; a console override wins over YAML and can be reverted. | What each neighbouring flag adds: | With | You also get | | --- | --- | | `span_store` | The judge span and the judge's request and attempt spans are stored, so **View judge trace** opens a trace. Without it the result still carries the judge trace ID and cost, the request log still shows the judge request with its origin and what it judged, and OTLP still receives the spans. | | An OTLP trace exporter ([observability](/docs/features/observability/#logs-and-traces-otlp)) | The judge span and both links reach your OpenTelemetry backend. | | `usage_valuation` and the `analytics:read` permission | Judge cost on results, evaluator cost, and spend by origin. Without them the links and the health are shown, never the amounts. | | `alert_channels` | The `evaluator_health_changed` alert. | With the flag off the gateway behaves exactly as before: a judgement writes the result it wrote before, no judge span exists, request log rows carry no origin, and the `origin` filter is refused. ### What happens when you turn it on 1. New request log rows are stamped with their origin as they are written. 2. A background pass gives **older rows** an origin (see [older rows](#older-rows)). It runs a batch at a time, can be interrupted and resumes where it stopped. 3. From the next judgement on, each judge run is traced and its result carries the judge fields. Results written before keep empty judge fields; nothing is rewritten. ## The origin of a request | Origin | The request is | | --- | --- | | `app` | A client's request made with a key: your application, an SDK, a batch line (it keeps the submitter's identity and names its batch), the console Playground with a typed key | | `playground` | A console Playground request sent with your console session (see [the session Playground](#the-session-playground)), or an evaluator test (**Test** on the evaluator editor) | | `evaluation` | A judge's model call, of an evaluator on live traffic or of an experiment | | `experiment` | An experiment item's model call | | `helper` | One of the gateway's own feature calls, with a sub-kind (see [helper calls](#helper-calls)) | | `shadow` | A shadow copy of a request | | `replay` | A stored request an operator sent again with [request replay](/docs/features/trace-explorer/#replay-a-request) (flag `request_replay`); it runs as the operator and names the request it replays | The gateway decides the origin from **its own call path**: only a call the gateway makes to itself in process, or a request the console's session route made for an authenticated console user, can be anything but `app`. No header, body field, key name, token name or `X-Request-Id` a client sends is read for it (an `X-Gateway-Origin` header or a `metadata.origin` field is ignored), so a client cannot label its traffic as a judge's or the Playground's, or hide a judge's among its own. ### Fallback attempts and batch lines A request-level **fallback** (a [semantic fallback](/docs/features/resilience/) after a context-window or content-policy refusal, or a customer allowance fallback) is a second request the gateway makes for the client's. That attempt: - keeps the **caller's origin** (`app` for an application, `playground` for the Playground, and so on) and the caller's identity; - names the request it was made for in `parent_request_id`, a stored field (not a suffix of its request ID); - is **counted in cost**: whatever the provider billed for it is in Cost, also when a later attempt is the one that answered; - is **not a request of its own**: it stays out of request, success, error and latency counts, so the client's request counts once, with the status and latency the client saw. A **batch line** is the submitter's own request: origin `app`, the submitter's key, team and organization, `batch_id` naming its batch, and counted as a request. Lines are priced at the model's standard rate: a provider's batch discount is not modelled. ### Helper calls `helper` is only for the gateway's **own feature calls**. Each carries a closed sub-kind (`helper_kind`), set by the gateway: | Sub-kind | The call | | --- | --- | | `guardrail` | A moderation guardrail's check of a request or of its answer | | `classifier` | The router's classification: the complexity classifier's call, and the embeddings of a semantic auto-route (the route index the first request builds, and each query) | | `summary` | A context-overflow summary of the turns it replaces | | `ask_ai` | A model call of **m7 ai** (the console's assistant; `ask_ai` is its machine identifier) | | `cache_embedding` | The embedding of a semantic cache lookup | | `tool_search` | The embeddings of an MCP tool search | | `vector_store` | A vector store's embeddings (file ingestion, search) and OCR | | `model_test` | An administrator's model connection test (**Test** on a model); it has no team and is a gateway-level cost | Every helper call: - is **billed to the team and organization that caused it**: it runs as the caller's key (narrowed to the helper's model), so its cost line is the caller's team's, under the same organization isolation as the request. m7 ai's calls are billed to the team the asker chose (`team` in the request, among the teams the asker may use as in [the session Playground](#the-session-playground)) or, when the asker has exactly one team, to that team; an asker with several teams and no choice, or none, pays at the gateway level (no team), and so does an administrator's model test; - names the request it was made for in `parent_request_id` (m7 ai: the console request that asked); - stays **out of the client's request counts**, and appears in **Cost** as its own line by sub-kind. ### How requests are counted Usage's requests, successes, errors, average and p95 latency, the daily rollups and the structured query's `requests`, `success`, `errors`, `error_rate` and latency metrics count **client requests**: every row except a helper call or a row with a `parent_request_id`. Token sums and cost count **every** row. The **By origin** ranking and the `calls` metric count calls (every row), so a helper sub-kind and an origin's fallback attempts show what they did. Rows written before this release, or with the flag off, have neither field and are counted as before. ### The session Playground With `playground` and `evaluation_tracing` on, the console Playground offers **Send with: My console session** (the default) or **Typed key**: - **My console session** sends the request to `POST /api/v1/admin/playground//` with your session cookie, the CSRF token and the team you chose (`X-Gateway-Playground-Team`). The gateway checks the session as for any console write, then runs the request as **you in that team** (its key ID is `playground::`, so nothing bound to a key, such as a key-scoped semantic cache entry or a stored response, crosses from one team to another): principal and owner are your console user, the team and organization are the chosen team's, and the models and routes are what the team's policy and its organization's ceiling allow. It then goes through the ordinary inference route: team policy, plan, attribution requirements, concurrency, rate limits, budgets, guardrails, capture, logs, metrics, ledger and cost apply as for any request, and the row is `playground`. Playground traffic is real traffic: it has its log, its request count, its latency, TTFT and tokens like any other request. - **Typed key** sends with the key you paste, to the bearer routes, as before; its requests are `app`. Which teams you may choose: a team you are a member of; for an organization admin, any team of its organization; for the global administrator role (without a custom role), any stored team. Operators and other roles choose among their own teams. Viewers, team viewers, customer credentials and the admin bearer token cannot send with the session (403 `role_forbidden`); any other team, or a team that is missing, deleted or disabled, answers 403 `team_forbidden`. The models and providers are the ones configured in the gateway, called with the gateway's own provider credentials. The session route serves one request, one answer: `chat/completions`, `responses`, `messages`, `embeddings`, `images/generations`, `audio/speech`, `audio/transcriptions`, `decisions`, `systemone`, `moderations` and `rerank` (and `v1beta/decisions`). Features bound to a key's stored objects (realtime, published prompts, MCP tools and code, vector store context, files and batches) still need a typed key; with the session the Playground says so. ### Where you read it - **Request log**: an origin tag on rows that are not `app` (a helper row reads `helper · guardrail`), **For …** or **Attempt of …** naming the parent request, an **Origin** filter with each helper sub-kind, and `origin`, `helper_kind`, `parent_request_id` and `batch_id` on each row of `GET /api/v1/admin/logs` (`?origin=helper&helper_kind=guardrail`). - **Usage**: an **Origin** filter and a **By origin** panel with the helper sub-kinds under `helper` (`by_origin` and `by_helper_kind` on `GET /api/v1/admin/analytics`, counted in calls). - **Cost**: **Spend by origin** (`by_origin` and `by_helper_kind` on `GET /api/v1/admin/valuation`, `?origin=`, `&helper_kind=`): evaluation, experiment, playground and helper spend beside the application's, each helper sub-kind its own line, each with its known amount. The amounts add up to the ledger total of the selection. - **What guardrails and judges cost**: the spend of model-backed checks is its own line, never mixed into the application's. A guardrail check that calls a model is the `guardrail` line under `helper` (`by_helper_kind`; `?origin=helper&helper_kind=guardrail` reads it alone), and an evaluator's judge calls are the `evaluation` line (`by_origin`). A moderation call has no price model, so a moderation check reads as unknown in that line's coverage, never as zero. - **Structured queries**: `origin` and `helper_kind` are dimensions and filters of `GET /api/v1/admin/analytics/query` (`group_by=origin,helper_kind&metrics=requests,calls,cost_usd`). - **Spans**: every stored span has had its request's origin since the span store. A row with no origin reads as `app` everywhere, and so does a row of a team whose plan does not include the feature (on the request log and the journey alike). The `origin` filter accepts one value of the table; anything else, or the filter with the flag off, answers 400 `invalid_origin`. `helper_kind` needs `origin=helper` and one sub-kind of the table, else 400 `invalid_helper_kind`. The filter and the rankings follow the gateway's flag and count every team you may read; a team whose plan lacks the feature still has its rows classified there, though its rows and journeys show no origin. While an origin filter is set, daily rollups are not used (they are not split by origin) and the report reads the request log directly. ### Older rows Rows written before the flag was on have no origin. The background pass classifies the gateway's own evaluation traffic among them, and only from the **pair** of identifiers the gateway mints for its own calls: the in-process caller (`eval:rule:`, `eval:`, `evaltest:`) together with the request ID it gave the call (`evalrule.…`, `eval..`, `….judge…`). A client request that happens to use a similar request ID keeps no origin and reads as `app`. Helper and shadow calls of before cannot be told apart from their rows and also stay `app`. `GET /api/v1/admin/usage/origin-backfill` (a global role) reports the progress: ```json {"cursor": 184220, "target": 184220, "started_at": "2026-11-23T14:02:11Z", "finished_at": "2026-11-23T14:02:19Z", "classified": 3120, "batches": 10, "done": true} ``` It covers 20,000 request log rows per pass, up to 25 passes every 2 seconds, and stops at the newest row that existed when the flag came on (later rows are stamped as they are written). If the flag is turned off and on again, it resumes from its stored position. ## Judge traces Each run of an evaluator on one target is a trace of its own: ```text judge helpfulness v3 judge span (root) ── evaluates ──▶ the judged span └─ POST /v1/chat/completions the judge's request, origin evaluation └─ provider.chat gpt-4o-mini provider attempt, with its cost ``` - The **judge span** is the root. It has no cost of its own: the cost is on the judge's request and attempt spans, as for any request. A judge that retries (an invalid answer, a provider error) has one request span per call, all in the same trace. A code evaluator, which calls no model, is a judge span alone. - The judge span carries a stored link `{trace_id, span_id, relation: "evaluates"}` to the span it judged. When the judged request's span is not stored (span store off for it, sampled out), the stored link names the trace only, and no OTLP link is exported (an OTLP link needs a span). - The judged span shows the other side, `relation: "evaluated_by"`, pointing at the judge span. It is derived from the result when the trace is read; a stored span is never rewritten. - The judge span's ID is the first 16 characters of the judge trace ID, so a result's `judge_trace_id` is enough to address it. - Judge traces are **always kept** by the span store's sampling: a result never links to a trace that was sampled out. - A failed run that the worker will retry leaves **no result**, but it leaves its judge span (status `error`), because it was traffic and may have cost money. - An **experiment** judge links to its item's request span. The item and its judges are separate traces. The judge span holds identifiers, status and numbers, never the prompt, the judged content or the reasoning: | Attribute | Meaning | | --- | --- | | `gen_ai.evaluation.name` | The evaluator's name | | `gateway.evaluation.evaluator.id`, `.version`, `.type` | The evaluator, the exact version that ran, and `llm_judge`, `decision` or `code` | | `gateway.evaluation.id`, `.status`, `.status_reason`, `.assessment`, `.scope` | The result the run produced | | `gateway.evaluation.target.trace_id`, `.span_id`, `.request_id`, `.session_id` | What was judged | | `gateway.evaluation.run_id` | The experiment run, for an experiment judge | | `gateway.evaluation.judge.request_id`, `.requests`, `.cost_usd`, `.cost_state` | The judge's own requests and what they cost | | `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens` | The judge alias and the tokens of all its calls | | `gen_ai.evaluation.score.value` or `.label` | A numeric, boolean or categorical verdict; text and JSON values stay on the result | Like every span it also carries the key (the judge's internal principal), the team and the organization. ### Over OTLP With a trace exporter configured, the judge span is exported as the root of its trace with an OTLP **span link** to the judged span, and the exported result span (a child of the judged span) carries a span link back to the judge span. Each link has the attribute `gateway.link.relation` (`evaluates` or `evaluated_by`). The judge's request and attempt spans are exported as its children with their usual GenAI attributes. No content leaves. ### In the console - A result on a trace or a session has **View judge trace**, and shows the judge cost. - A judge trace says **Judge of …** with **View evaluated trace** and the evaluator and version, and its type reads *Judge trace*. - The judged span lists **Evaluated by** under *Links*; the judge span lists **Evaluates**. - In the request log, a judge's own request has the `evaluation` tag and, under its ID, **Judge of …** naming the request (or trace or session) it judged; its journey says the same with the evaluator and a way to open what it judged. A failed run that will be retried has no result yet, so its row names nothing until it does. `GET /api/v1/admin/traces/{trace_id}` returns `judge_of` on a judge trace, and `GET /api/v1/admin/requests/{id}/journey` returns it on a judge's request: ```json {"judge_of": {"evaluation_id": "rule_5f0c…", "evaluator_id": "ev_19ab…", "evaluator_name": "helpfulness", "evaluator_version": 3, "scope": "span", "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "span_id": "00f067aa0ba902b7", "request_id": "req-42", "status": "ok"}} ``` ## The judge fields of a result | Field | Meaning | | --- | --- | | `judge_trace_id` | The trace of the judge run that produced the result | | `judge_request_id` | The judge request that produced the verdict; for an error result, the last one the judge tried | | `judge_cost_usd` | The exact known cost of **every** request of the run's trace, summed from the ledger: retries, and any call a judge request makes itself (a fallback, a guardrail). Absent when unknown | | `judge_cost_state` | `known` (every call is valued), `partial` (some amount is known) or `unknown`. A call with no ledger row (usage writes off or failed) makes the run `partial` or `unknown`, never a complete amount. Unknown is never zero | `GET /api/v1/admin/evaluations?judge_trace_id=` lists the results a judge run produced; it takes up to 200 comma-separated trace IDs (the request log reads a page's judge rows in one call), and any value that is not a 32-character hex trace ID answers 400. A result whose judge fields are hidden from you (its team's plan lacks the feature) is not returned by this filter. The amounts are shown only to readers who may see costs. ## Evaluator health and cost `GET /api/v1/admin/evals/evaluators` returns `health`, by evaluator ID, and the **Evaluators** list shows it: ```json {"health": {"ev_19ab…": {"state": "degraded", "reason": "judge_errors", "window_hours": 24, "results": 28, "errors": 2, "skipped": 0, "error_rate": 0.0667, "cost_window_days": 7, "results_7d": 196, "errors_7d": 2, "skipped_7d": 3, "cost_7d": {"state": "known", "known_usd": "0.004312", "requests": 201, "unvalued_requests": 0}, "cost_per_result_usd": "0.000021777777"}}} ``` | State | When | What to do | | --- | --- | --- | | `ok` | None of the below | Nothing | | `degraded` | In the last 24 hours, at least 5% of the judged results (ok and error; a skipped target was not judged) ended as an error | Open the error results: the reason says whether the judge model failed or its answer could not be read | | `blocked` | The worker paused the evaluator by itself: the judge was refused (model not allowed, budget or quota exhausted), its definition is no longer valid (its judge alias was removed) or its daily cost ceiling was reached; `reason` says which | Fix the cause, then resume the evaluator | The **7-day cost** is the ledger cost of the evaluator's judge requests (live runs and experiment judges, retries and failed runs included), with the tokens and the cost per judged result. It is read from the ledger each time, so it is current as soon as a job completes, and it does not depend on span retention: expired judge spans leave the spend where it is. `cost_7d` and the token counts are returned only to readers who may see costs, and the judge span's own cost attributes follow the same rule. An evaluator that calls a model and judged in the window but has no ledger rows (usage writes off or failed) reads `unknown`, never zero; `cost_per_result_usd` is given only when the amount is complete (`known`). ### Alert Subscribe a [channel](/docs/features/alerting/) to `evaluator_health_changed` to be told when a judge run leaves an evaluator **blocked** or **degraded**. The alert names the team, the evaluator, the state and the reason (for a block, the worker's pause reason; for degraded, the error code); one per evaluator and state per clock hour. Never content. ## Both span engines Everything here works with [`spans.engine`](/docs/features/traces/#where-spans-are-stored) `database` and `analytics_store`: the judge span is written by the same writer to the same engine as every other span, and the health counts read results from wherever they are. The request log and the ledger stay in the transactional database; the [analytics store copy](/docs/features/analytics-store/) of the request log carries `origin`, `helper_kind`, `parent_request_id` and `batch_id` (the columns are added to an existing table on start; rows copied before read as `app` and counted, until the backfill updates them and the copy follows), and its reports count requests and calls by the same rule. ## Who sees what - The judge span, the judge's requests and the results belong to the **evaluator's team**; every read is filtered by the reader's teams and organization, as for any trace. A reader of another team or organization gets 404 on the judge trace and on the judge's request, and no `evaluated_by` link on spans they can see in a shared trace. - A team whose plan lacks `evaluation_tracing` has no traced runs, and its readers see no judge link, health or cost. ## Limits and notes - One judge span per run; at most 8 links on a span. - A result that is judged again (a retried job, a re-run experiment item) names its **latest** judge run and that run's cost; the earlier runs keep their traces and their ledger rows. - The judge's request IDs are built from the judged request's ID (`evalrule...`, `eval...judge..`). A request ID is at most 128 characters: when the built ID would be longer the gateway gives the judge request a random ID instead. The result's judge trace and judge cost are unaffected (they follow the trace), but `judge_request_id` then names no request, and that request is missing from the evaluator's 7-day cost and from the origin backfill. Keep your own request IDs under 80 characters and dataset item IDs under 50 to stay clear of it. - The 7-day cost counts experiment judges of runs created in the last 37 days. A judge's calls are recognised by how they were made, not by their request ID; older rows (before the flag) are recognised by the request ID's end (`.judge..`), so a dataset item ID that itself ends that way can be misread there. Avoid `.judge.` in dataset item IDs. - While several replicas run the background pass, its `finished_at` can read empty for a moment after one replica finished its share; `done` settles once the newest target is reached. - The judge span is written by the span writer's bounded queue: when it is full the span is dropped and counted (`gateway_span_store_spans_total{kind="judge"}`, a series that appears with the first judge span). The result and its judge fields do not depend on it. - Migration 203 adds `gateway_usage_events.origin` and the backfill's state table; migration 204 adds `helper_kind`, `parent_request_id` and `batch_id`. Neither rewrites or scans the request log. Rows written before either keep no sub-kind and no link: older helper rows read as `app` (the backfill cannot tell them apart) and older fallback attempts are counted as requests. - A judge's own retries (a decision judge retried after a 429 or 5xx) are separate `evaluation` calls of the judge, not fallback attempts. - Daily rollups built before migration 204 counted every row as a request; days rebuilt afterwards use the rule above. ## See also - [Evaluation results](/docs/features/evaluation-results/) · [Traces](/docs/features/traces/) · [Evals](/docs/features/evals/) · [Alerting](/docs/features/alerting/) # Experiments as traces and regression suites **Last updated:** 2026-11-26T03:19:02-03:00 (UTC-3) An experiment item is one trace: the item's model call and every judge that scored it, nested, with the cost of each from the request log. Datasets keep a version history you can read, compare and restore; a past run can be judged again; a regression suite turns a dataset into a gate a CI job passes or fails. | Flag | What it turns on | Requires | | --- | --- | --- | | `experiment_traces` | Traced experiment runs, dataset version history with diff, notes and restore, item provenance and **Add to dataset** from a span, a run on an older version, judging a past run again with an estimate, the `experiment_finished` alert event and the alert rules of the `experiments` signal, the experiments an alias serves | `evaluation_tracing` (and `span_store` to store the spans) | | `regression_suites` | Suites of assertions over a dataset with trials, a pass threshold and a minimum pass rate, and their CI verdict through the public API | `experiment_traces` (and `evals_public_api` for the CI routes) | | `remote_experiments` | Runs whose items the team's own endpoint executes, signed and behind the outbound URL guard | `experiment_traces` | | `experiment_summaries` | A generated summary of compared runs through the chat alias each team chose | `experiment_traces` | With `experiment_traces` on, runs also take trials, sessions and per-session judges, split their cost into task and judges, and two item traces compare side by side. Both flags are off by default and are tenant flags: with [plan entitlements](/docs/features/feature-access/) a team gets them only when its plan includes them. With a flag off nothing of what it adds is computed or stored, and its routes answer `404 feature_disabled`. ## An item is one trace A run created while `experiment_traces` is on for the dataset's team is **traced** (`traced: true` on the run): - each item's model call (request ID `eval..`, origin `experiment`) is the root of its own trace; - each evaluator that judges the item is a `judge` span, a **child** of the item's request span, and the judge's own requests are children of that judge span: a 4-item run with two evaluators is 4 traces, not 12; - the run item records `trace_id`, `span_id` (its request span) and `item_version` (the version of the dataset item it ran); - the item's request span carries `experiment_run_id`, `experiment_dataset_id`, `experiment_item_id`, `experiment_dataset_version` and `experiment_item_version` (and `experiment_suite_id` for a suite run, `experiment_ci_traceparent` for one a CI started) as attributes, so the trace joins its dataset item; - the trace page shows an **Experiment item** box with the run, the dataset item, the dataset and item versions and the expected output, and links to the run and the item; - each result keeps the item's trace and span as its target and the same trace as its judge trace; its judge cost is read from the ledger rows of its own judge requests. Runs created before the flag, or with it off, keep one trace per call, as they were; they are never rewritten. Sampling never drops part of an item: the span store keeps or drops the whole trace. The experiments list shows, per run, its items and errors, its average latency, its cost and one column per evaluator (pass rate with pass criteria, else mean, else its labels), and a **chart across runs** of an evaluator, the cost or the latency (line or bars; a categorical evaluator as stacked bars with a legend). A comparison adds the **configuration** of each run (model, prompt revision with a link, dataset version, evaluator versions; **Differences only**), and a **Score matrix** layout. In a run's detail, select items and **Run evaluator** judges only those. From a run, **Traces of this run** opens Traces with `origin:experiment request_id:"eval.."*`, and `GET /api/v1/admin/evals/runs/{id}/traces` lists the item traces and that query. Each item of the run detail and of a comparison links to its trace. **Cost.** The run's and each item's cost are read from the request log, as before: an item's cost is its model call plus its judge calls, and the run's is the sum. A traced item's trace totals include its judges (they are its spans). ## Dataset versions With the flag, every write of a dataset is **one version**: an item saved in the console, a CSV import, items added from captures, by a review automation or from spans, an archive, a restore. A write of many items is one version, at one instant; writes made before this release opened one version per item they wrote. (Since this release a batch write takes one instant whatever the flag, so a read as of any instant sees all of a batch or none of it.) The dataset page shows the version chip (`v7 latest`, or `as of …` while you view an older one) and: - **Version history**: each version, newest first, numbered from the oldest, with `+added ~changed −removed`, the number of items after it, who made it, through what (`manual`, `csv`, `capture`, `span`, `restore`) and its note. **Diff with v6** lists each item added, changed or removed, with the fields that changed and both values. **View items** shows the dataset as of that version; **Run experiment** opens a new experiment on it; **Add note** names a version (a tag such as `golden-2026-11`, or what changed; at most 500 characters). - **History** of an item: its versions with source, author and the source span, **Restore this version** (writes it as a new current version: history is never rewritten), and the runs that ran it, each with its trace. - Items show their source and, for an item added from a span, a **Source span** link. A search finds items by content, or by a metadata value (`metadata.region:eu`); one line per metadata key shows up to six keys. - The datasets list adds **Versions**, **Experiments** and **Last run**; **Experiments** on the dataset page lists the experiments of that dataset. A note travels with the write: `note` in the body of `PUT /api/v1/admin/evals/datasets/{id}/items/{item}`, `?note=` on the CSV import, `note` on Add from spans. **Run an older version.** `dataset_as_of` in `POST /api/v1/admin/evals/runs` (an instant of the history, as `versions[].at` gives it) runs the items valid then; the run's `dataset_as_of` is that instant and each item records the version it ran. The **Dataset version** picker of **New experiment** sets it. Without the flag the field is refused (`400`). **Default names.** With the flag a run may be created without a name: it is named after its dataset and the UTC time (`capitals · 2026-11-26 03:10:00`). **New experiment** shows a review of what will run (prompt revision or item input, alias, dataset version and its item count, evaluators with their version and health, name) before **Start**, and **Check items** (`dry_run: true` on `POST /api/v1/admin/evals/runs`) counts the items whose input renders with the prompt's variables, lists the others (they would fail without calling the model) and estimates the judges' spend. **Export and import.** The dataset page exports the items shown (the latest, or a version you are viewing) as CSV or JSON; the import takes a CSV or a JSON array of `{id, input, expected_output, metadata}` (the export's format: a round trip writes the same items), up to 1,000 items, one bad item rejecting the whole file. ## Add to dataset from a span **Add to dataset** on a trace (and on the selected traces of the Traces list) adds the captured request of the selected span to a dataset of the span's team. With the flag, the dialog maps the fields and previews the first item: | Field | Options | | --- | --- | | Input | The conversation (`messages`, the default) or the text of its last user message (`last_user`) | | Expected output | The captured answer (default), or nothing | The capture is read exactly as **Add from captures** reads it: the sent view, audited, only for readers with `content_sent:read` of the team, and only a capture meant for evaluation. The item is `span-`, with `source: span`, `source_trace_id` and `source_span_id`, and its metadata names the request, trace, span and model. `POST /api/v1/admin/evals/datasets/{id}/items/from-spans` takes up to 100 spans; `dry_run: true` answers the items without writing them. ## Judge a past run again Select finished runs and choose **Run evaluator** (or **Run evaluator** in a run's detail) to judge their completed items with evaluators of the run's team: 1. Pick the evaluators. **Estimate** shows, for every run, the items and judge calls and the expected spend, from each evaluator's average judge cost of the last 7 days in the request log; an evaluator with no priced history makes the estimate partial or unavailable. Code evaluators cost nothing. 2. **Run evaluation** starts a background job per run, leased like a run, so a restart or another replica resumes it. Each result keeps the deterministic ID of its run, item and evaluator: judging again **replaces** the earlier result of that evaluator, so each item ends with one valid result per evaluator. The judge calls are the run's own (principal `eval:`), with request IDs `.judge..r.` apart from the first judge's, and count in its cost and in the evaluator's 7-day cost. A run evaluation resumed after a restart judges only the pairs it had not judged yet: no judge call is paid twice. In a traced run the new judges nest in the item's trace. The evaluators join the run's evaluator list. Experiments are judged in full: an evaluator's live sampling rate never applies to an experiment or a run evaluation, and the run shows how many results each evaluator produced. ## Experiment finished alert With the flag, a run that reaches `completed`, `failed` or `canceled` records **`experiment_finished`** once (the run is the deduplication key) when an enabled alert channel subscribes to it. Its detail carries `run_id`, `name`, `team`, `organization`, `status`, `dataset_id`, `dataset_as_of`, `dataset_version`, `model`, `prompt_id` and `prompt_revision`, `items`, `done`, `failed`, `duration_ms`, `scores` (each evaluator's mean, pass count and results) and, for a suite run, `suite_id` and `verdict`. Alert rules of the **`experiments`** signal (realtime only, no backtest) match each finished run of their own team or organization, filtering on `team`, `status`, `dataset_id`, `model`, `suite_id`, `verdict`, `items`, `failed` and `duration_ms`. See [alert rules](/docs/features/alert-rules/). ## Experiments of an alias With `alias_evaluator_usage` and `experiment_traces`, the model editor's **Used by experiments** lists the runs whose target or one of whose judges is the alias, in the teams you read evaluations of, beside the evaluators that judge through it. ## Trials `trials` on `POST /api/v1/admin/evals/runs` (1–10, the **Trials per item** field of New experiment) runs each item that many times; an item's `metadata.trials` overrides it (only when the run sets `trials`, so a dataset that happens to carry the key runs as before). Each trial is a run item `:t`, its own trace. The run detail shows, per item, each evaluator's mean and spread (standard deviation) over the trials, its passing trials, **pass@k** (at least one trial passed) and **pass^k** (every trial passed), and per evaluator the share of items passing at least once and every time (`GET /api/v1/admin/evals/runs/{id}/trials`). A trial that errored has no score: it counts as failing for pass^k and is left out of the mean and the spread, which is the population standard deviation of the scored trials. A comparison pairs the same trial of each run. ## Sessions When the run asks for sessions (**Run sessions as conversations**, `sessions: true`, implied by `session_evaluator_ids`), items that carry `metadata.session_id` (1–64 letters, digits, `.`, `-` or `_`) form a session: they run in turn order (`metadata.turn`, then the item ID) as one conversation, through the run's prompt when it has one, each call carrying the turns before it (the earlier items' messages and answers), with `X-Gateway-Session-Id: exp--`, so Traces → Sessions shows each conversation. With trials, each trial is its own session (`:t`). **Judge each session** (`session_evaluator_ids`) runs evaluators on each session as a whole: `{{input}}` is the conversation, `{{output}}` its last answer, `{{expected}}` the last item's expected output; the result targets the session (`exp::`) and its judge calls count in the run's cost. A session is judged once all its items ran; a run resumed after its items finished still judges the sessions not judged yet. A remote run takes no sessions: its endpoint receives each item's `session_id` and keeps the conversation itself. The run detail and `GET /api/v1/admin/evals/runs/{id}/sessions` list the sessions, their items in order and their results. ## Task cost and judge cost The run and each item show their cost in two parts beside the total: **Task** (the item calls) and **Judges** (every judge call, per-session judges included), in the experiments list (Task cost, Judge cost), the run detail, the comparison (Task · judges) and the API (`task_cost` and `judge_cost`, with the same `state`, `known_usd`, `requests` and `unvalued_requests` as `cost`), under the same visibility as the cost. ## Two traces side by side In a comparison, **Compare traces** on an item opens the traces of two runs side by side: their spans aligned by kind and name in order (the longest common sequence, so an extra span on one side leaves the rest paired), each with its duration and tokens (a span only one trace has stays on its side), and each side's results. ## Comparison summaries With `experiment_summaries`, **Summarize the comparison** generates a few sentences on 2–5 compared runs through the chat alias the team chose (`PUT /api/v1/admin/evals/summary-settings/{team}`; there is no default, and a team without one is asked to choose). The estimate (input tokens, and the maximum cost when the alias is priced) comes first; then **Generate summary** makes one `experiment_summary` helper call of the team, recorded and priced like every call (`POST /api/v1/admin/evals/compare-summary`, `dry_run` for the estimate). The call carries only the runs' figures (items, failures, latency, each evaluator's mean, pass rate, the labels of categorical and boolean scores and its improved and regressed items against the baseline), never an item's input, output or captured content, and the summary is not stored. ## Remote experiments With `remote_experiments`, a run can be **Executed by** one of the team's remote endpoints instead of a model alias: the gateway sends each item (or a batch) to the team's own service, which runs its application and returns the output; each output becomes the item's trace (a root span `remote ` with the judges nested) and is judged like a model's answer. An endpoint (**Remote endpoints** on the Experiments tab, `POST /api/v1/admin/evals/remote-endpoints`) has a URL (absolute, with no credentials, query or fragment: the signature authenticates the gateway), a mode, how many items one call carries, its timeout, retries and concurrency. The calls are `POST` with `{run_id, run_name, dataset_id, mode, items: [{item_id, input, expected_output, metadata, session_id, trial}]}` and the headers `X-Gateway-Signature: t=,v1=.">` (the endpoint's signing secret, shown once when it is created or rotated, stored encrypted), `X-Gateway-Run-Id` and `Idempotency-Key`. A call answered 408, 429 or 5xx, or not answered, is retried with backoff up to the endpoint's retries; the `Idempotency-Key` is the same for the same items of the run. A run executes the endpoint as it was when the run started (URL, mode and bounds), signed with its current secret; removing the endpoint, or the team losing `remote_experiments` or `experiment_traces`, stops the run. An empty output with no error counts as an error. - **sync**: the endpoint answers `{"outputs": [{"item_id", "output", "error", "latency_ms"}]}`. - **callback**: it answers 2xx at once and later posts the outputs to `POST /v1/eval-remote/runs/{run}/items` with `Authorization: Bearer ` (answered once when the run is created); items with no output within `callback_wait` fail. Only items already sent are accepted, each once; a run resumed after a restart does not send again the items sent within `callback_wait`. Every call goes through the outbound URL guard: https only (plain http only to loopback with `allow_loopback_http`), each DNS answer checked and the checked address dialed, no private address outside `allowed_private_cidrs`, no redirect followed. The bounds live in the configuration file: | Key | Default | What it is | | --- | --- | --- | | `evaluation.remote_experiments.timeout_ms` | 30000 | The deadline of one call when the endpoint sets none (1000–600000) | | `evaluation.remote_experiments.max_timeout_ms` | 120000 | The longest deadline an endpoint may set | | `evaluation.remote_experiments.max_retries` | 2 | The most retries an endpoint may set (0–10) | | `evaluation.remote_experiments.max_concurrency` | 8 | The most calls one run makes to its endpoint at a time (1–64) | | `evaluation.remote_experiments.max_batch_items` | 20 | The most items one call carries (1–100) | | `evaluation.remote_experiments.callback_wait` | 10m | How long a callback run waits for posted-back outputs (1m–24h) | | `evaluation.remote_experiments.allowed_private_cidrs` | none | Private prefixes an endpoint may resolve to; every other private address is refused | | `evaluation.remote_experiments.allow_loopback_http` | false | Lets an endpoint on localhost use plain http, for local tests | ## Regression suites A suite runs a dataset of its team against an enabled chat alias (optionally a prompt revision) and asserts what every item must keep passing. | Field | What it is | Default | | --- | --- | --- | | `assertions` | 1–20 assertions: an evaluator of the team with pass criteria (`evaluator_id`; it passes when its result is assessed pass), or a sentence (`text`) judged true or false by `judge_model` | — | | `judge_model` | The chat alias that judges sentence assertions | — | | `runs_per_item` | Trials per item, 1–5 | 1 | | `pass_threshold` | Trials that must pass every assertion for the item to pass | `runs_per_item` | | `min_pass_rate` | The share of passing items the suite needs, 0–1 | 1 | An item adds up to five assertions of its own, and may override the trials, in its metadata: ```json {"assertions": [{"name": "names a city", "text": "The answer names a city"}, {"name": "exact", "evaluator": "exact-match"}], "execution_policy": {"runs_per_item": 3, "pass_threshold": 2}} ``` A suite run is a traced experiment run that names the suite (`suite_id`) and keeps a snapshot of it; with more than one trial each trial is a run item `:t`. Its verdict: | Verdict | Exit code | When | | --- | --- | --- | | `passed` | 0 | The run completed and its pass rate reached `min_pass_rate` | | `failed` | 1 | The run completed below `min_pass_rate` | | `error` | 2 | The run failed or was canceled | | `running` | none | Still running: poll again | The verdict lists each assertion's passes over its judged results and each failing item with its passing trials and the assertions it failed. The **Suites** tab of Evals creates and edits suites, runs one and shows each run's verdict. Edits bump the suite's version; earlier runs keep the snapshot they ran. ### In CI With `evals_public_api`, a key of the suite's team runs it: ```sh run=$(curl -fsS -X POST "$GATEWAY/v1/eval-suites/$SUITE/runs" \ -H "Authorization: Bearer $KEY" -H "traceparent: $TRACEPARENT" | jq -r .run_id) while :; do v=$(curl -fsS "$GATEWAY/v1/eval-suites/runs/$run" -H "Authorization: Bearer $KEY") code=$(echo "$v" | jq -r '.exit_code // empty') [ -n "$code" ] && { echo "$v" | jq .; exit "$code"; } sleep 5 done ``` `POST /v1/eval-suites/{id}/runs` needs `evals:write`; `GET /v1/eval-suites/runs/{run}` needs `evals:read`. A suite or run of another team answers `404`. A valid `traceparent` on the start is recorded on every item's request span as `experiment_ci_traceparent`: each item keeps its own trace, and the CI job's trace finds them by that attribute, with no agent. A suite run's results are its verdict: it is not judged again (run the suite again), and only each judge's own result decides an assertion, never another result of the same name (a reviewer's, an API score). ## Permissions and tenancy Reads need `evals:read`; dataset writes, restores, version notes, judging a past run again and managing or running suites need `evals:manage` over the team. Datasets and suites belong to their team; runs, their items, run evaluations and `experiment_finished` belong to the organization the run was recorded in: another organization reads none of them, and an alias lists only the runs of your teams. ## Admin API routes | Route | What it does | | --- | --- | | `GET /api/v1/admin/evals/datasets/{id}/versions` | The dataset's versions, newest first, with what each changed, who made it and its note; `limit` (1–500, default 500) bounds how many are listed | | `POST /api/v1/admin/evals/datasets/{id}/version-notes` | Names a version with a note; an empty note removes it | | `GET /api/v1/admin/evals/datasets/{id}/diff` | The items added, changed or removed between two versions (`from`, optional `to`) | | `GET /api/v1/admin/evals/datasets/{id}/items/{item}/history` | An item's versions and the runs that ran it, with their traces | | `POST /api/v1/admin/evals/datasets/{id}/items/{item}/restore` | Writes an earlier version of an item as its new version | | `POST /api/v1/admin/evals/datasets/{id}/items/from-spans` | Adds the captured requests of spans to the dataset, with the field mapping and a dry run | | `GET /api/v1/admin/evals/runs/{id}/traces` | The traces of a traced run's items and the query that lists them | | `GET /api/v1/admin/evals/runs/{id}/evaluations` | The run's evaluations again, newest first | | `POST /api/v1/admin/evals/runs/{id}/evaluations` | Judges the run's completed items again with evaluators, or answers the estimate with `dry_run` | | `POST /api/v1/admin/evals/runs/{id}/evaluations/{evaluation}/cancel` | Stops a run evaluation; results already written stay | | `GET /api/v1/admin/models/{id}/experiments` | The runs whose target or judge is the alias | | `GET /api/v1/admin/evals/suites` | Lists the regression suites of your teams | | `POST /api/v1/admin/evals/suites` | Creates a regression suite with its assertions, trials and thresholds | | `GET /api/v1/admin/evals/suites/{id}` | A suite and its last runs with their verdicts | | `PUT /api/v1/admin/evals/suites/{id}` | Changes what a suite runs and asserts; its version goes up | | `DELETE /api/v1/admin/evals/suites/{id}` | Removes a suite; its runs stay | | `POST /api/v1/admin/evals/suites/{id}/runs` | Starts a run of a suite | | `GET /api/v1/admin/evals/suite-runs/{run}` | The verdict of a suite run | | `GET /api/v1/admin/evals/runs/{id}/trials` | Per item, its trials' mean, spread, pass@k and pass^k per evaluator | | `GET /api/v1/admin/evals/runs/{id}/sessions` | The run's sessions, their items in order and their session results | | `GET /api/v1/admin/evals/remote-endpoints` | Lists the remote endpoints of your teams and the configured bounds | | `POST /api/v1/admin/evals/remote-endpoints` | Creates a remote endpoint and answers its signing secret once | | `PUT /api/v1/admin/evals/remote-endpoints/{id}` | Changes a remote endpoint's URL, mode and bounds | | `DELETE /api/v1/admin/evals/remote-endpoints/{id}` | Removes a remote endpoint; its runs keep a snapshot | | `POST /api/v1/admin/evals/remote-endpoints/{id}/rotate-secret` | Answers a new signing secret once; the old one stops at once | | `GET /api/v1/admin/evals/summary-settings` | The summary alias each of your teams chose | | `PUT /api/v1/admin/evals/summary-settings/{team}` | Chooses the team's summary alias, an enabled chat alias | | `DELETE /api/v1/admin/evals/summary-settings/{team}` | Removes the team's summary alias, and summaries with it | | `POST /api/v1/admin/evals/compare-summary` | Estimates or generates the summary of compared runs | The full contract is in the [API reference](/docs/api/). ## Known limits - A judge nested in an item's trace is costed from its own judge requests; a call a judge request makes itself under another request ID (a guardrail, a summary) is in the trace and in the run's cost, but not in that result's judge cost. - Versions written before this release are one version per item they wrote, and have no author or note; an edit made then shows as two versions, the old row's removal and the new row's addition. - The console reads at most 500 versions of a dataset and 200 runs of an item. ## See also - [Evals](/docs/features/evals/): datasets, evaluators, experiments and comparison. - [Sessions and users](/docs/features/sessions-and-users/): the sessions page the experiment sessions appear on. - [Judge calls as linked, labelled traffic](/docs/features/evaluation-tracing/): judge spans, origins and judge cost. - [Evaluation results](/docs/features/evaluation-results/) and [alert rules](/docs/features/alert-rules/). # Agent evaluations **Last updated:** 2026-11-27T14:39:27-03:00 (UTC-3) An agent evaluation answers one question with numbers: which agent configuration or model solves your tasks most often, and at what cost per solved task. You write the tasks once, with the checks that decide whether each attempt succeeded; the runner in the Python client runs every task against every target a few times, checks each outcome on your machine, and records it in the gateway. The gateway reads the cost, tokens and model calls of each attempt from its own request log and answers a scorecard per target. The runner executes **on the client**, in your environment. No agent code and no check runs in the gateway, and the runner never runs a command that came from the gateway: command checks come only from your own task file. | Flag | What it turns on | Requires | | --- | --- | --- | | `agent_evaluations` | `POST /v1/agent-evals`, `POST /v1/agent-evals/{id}/results`, `GET /v1/agent-evals/{id}`, the console scorecard on each of the evaluation's runs, and an attempt's trace named as its experiment item | `experiment_traces` and `evals_public_api` (and `span_store` to store the traces) | The flag is a tenant resource, off by default, with a plan right of the same name: with `feature_plan_entitlements` on, a team runs agent evaluations only when its plan includes both `agent_evaluations` and `experiment_traces`. No new permission: the key needs the scopes `evals:read` and `evals:write` (and `evaluators:read` for judge checks that use a team evaluator), and a console reader needs `evals:read` over the team. ## Turn it on 1. Turn on the flags in `features` (YAML, `PUT /api/admin/settings/features` or **Settings → Features**): ```yaml features: evals: true evals_public_api: true evaluation_results: true evaluation_tracing: true experiment_traces: true span_store: true agent_evaluations: true # Recommended when a target streams (the Claude Agent SDK always does): stream_usage: true ``` `stream_usage` lets the gateway read the token counts a provider reports at the end of a streamed answer. Without it a streamed call is recorded with unknown tokens and unknown cost, and the scorecard says so (never zero). 2. Create a key of the team that will own the results, with the scopes `route:chat` (or `route:*`), `evals:read`, `evals:write` and, for judge checks through a team evaluator, `evaluators:read`; allow it the model aliases your targets and judges call. 3. Install the Python client (Python 3.11 or later; no dependency of its own) and, only for the targets that use them, the agent SDKs: ```bash pip install ./clients/python # m7gtw_prompts pip install claude-agent-sdk==0.2.189 # targets of kind claude_agent_sdk (the version tested) pip install openai-agents==0.26.0 # targets of kind openai_agents_sdk (the version tested) ``` ## Write the tasks A task file is TOML or JSON. It names the evaluation, the dataset the tasks are kept in, the number of trials, the targets and the tasks with their checks. ```toml name = "support agent" # the run names start with it; --name sets the whole name dataset = "agent-tasks" # a dataset of the team that the runner keeps trials = 3 # 1-10 attempts of every task on every target max_concurrency = 4 # trials at once (1-64) [[targets]] label = "small" # 1-40 letters, digits, dot, dash, underscore kind = "model" model = "gpt-small" # a model alias of the gateway [targets.settings] max_turns = 6 [[targets]] label = "claude-agent" kind = "claude_agent_sdk" model = "claude-fast" [targets.settings] max_turns = 8 allowed_tools = ["Read", "Write", "Edit"] [[tasks]] id = "capital" prompt = "What is the capital of France? Answer in one word." expected = "Paris" [[tasks.checks]] kind = "predicate" op = "contains" value = "Paris" [[tasks.checks]] kind = "judge" model = "judge" criteria = "The answer names the capital and nothing else." [[tasks]] id = "write-file" prompt = "Write the word done into answer.txt." timeout_s = 120 files = { "README.md" = "Write your answer in answer.txt." } [[tasks.checks]] kind = "command" argv = ["grep", "-qx", "done", "answer.txt"] timeout_s = 10 ``` ### Targets | `kind` | What runs | Settings (all optional) | | --- | --- | --- | | `model` | The model alias through `POST /v1/chat/completions`, with a tool loop over three workspace tools: `read_file`, `write_file`, `list_files` | `max_turns` (8), `tools` (true; false sends no tools), `instructions` (a system message), `temperature` | | `claude_agent_sdk` | An agent of the Claude Agent SDK, its every model call through the gateway's Messages API: `ANTHROPIC_BASE_URL` is the gateway, the key goes as a bearer token, the trial's `traceparent` as a custom header; your own Claude settings and configuration directory are not loaded | `max_turns` (8), `allowed_tools` (`Read`, `Write`, `Edit`, `Glob`, `Grep`), `permission_mode` (`acceptEdits`), `instructions` (system prompt), `small_model` (the alias for the harness's own short calls; default the target's model) | | `openai_agents_sdk` | An agent of the OpenAI Agents SDK over the gateway's chat completions, with the same three workspace tools; the SDK's own trace export is turned off | `max_turns` (8), `tools` (true), `instructions`, `api` (`chat`; `responses` uses the Responses API) | | `custom` | Your own function, from Python only: `run(ctx)` gets the task, the workspace and `ctx.headers`, which it must send on every model call | — | The model alias of a `claude_agent_sdk` target serves the `messages` capability; the others serve `chat`. Only the settings named in the table are sent to the gateway with the plan, for the comparison; anything else in `settings` stays on your machine. ### Checks Every check of a task runs after the attempt, in the attempt's own workspace (a fresh directory, with the task's `files`, removed at the end unless `--keep-workspaces`). | `kind` | Fields | Passes when | | --- | --- | --- | | `predicate` | `op`, `value`, `path` | `contains`, `not_contains`, `equals` (after trimming), `regex` on the final answer; `file_exists`, `file_contains`, `file_equals` on the workspace file `path`; `tool_called` (a tool of that name was called); `max_tool_calls` (at most `value` calls). From Python, `Predicate(fn=...)` takes any function of the outcome | | `judge` | `model` and `criteria`, or `evaluator` | The judge alias answers `{"pass": true}` for the criteria (with the task and its `expected` answer), or the team's evaluator, read with `GET /v1/evaluators/{name}`, scores the answer past its pass rule. The judge calls go through the gateway in a trace of their own, so their cost stays apart | | `command` | `argv` (a list; no shell), `timeout_s` (60), `expect_exit` (0), `stdout_contains` | The command exits with `expect_exit` (and prints `stdout_contains`) within the timeout. It runs in a process group of its own, killed whole at the timeout, with your environment minus every variable whose name looks like a credential (`API_KEY`, `..._KEY`, `KEY_ID`, `TOKEN`, `SECRET`, `PASSWORD`, `CREDENTIAL`, an `AUTH` word such as `..._AUTH_...`; `GIT_AUTHOR_*` is kept) and any whose value holds the gateway key; only the last 64 KiB of its output are read (`stdout_contains` is looked for there), and whatever it left running in its group is killed when it ends | A check that cannot run (a judge that does not answer, a command that is not installed, a path outside the workspace) gives no verdict: the attempt is an `error` with class `check_error`, not a fail. ## Run it ```bash export GATEWAY_URL=https://gateway.example.com export GATEWAY_API_KEY=... # read from the environment, never from the command line python -m m7gtw_prompts.agent_eval run tasks.toml ``` | Option | Effect | | --- | --- | | `--name NAME` | The evaluation's name (default: the file's `name` and the UTC time). A name the team used before is refused | | `--trials N`, `--concurrency N` | Override the file | | `--target LABEL`, `--task ID` | Run only these (repeatable) | | `--no-report` | Run locally: no plan and no results in the gateway (the model calls are still recorded as usual); the scorecard has no costs | | `--no-details` | Do not send check details (the tail of a failing command's output, a judge's reason) | | `--json FILE` | Write the whole report: the plan, the scorecard and every outcome | | `--min-pass-rate R` | Exit 1 when a target's pass rate is below `R` (default 0: report only) | | `--keep-workspaces` | Keep each attempt's directory | | `--allow-insecure-http` | Allow plain HTTP to a gateway that is not on loopback | Exit codes: `0` every target reached `--min-pass-rate`, `1` one did not, `2` the plan or the run was refused. The command prints one line per attempt as it ends and then the scorecard as a Markdown table. A Ctrl-C records every attempt not yet run as an `error` of class `interrupted`, so an interrupted run never looks better than it was. Attempts already running finish before the process exits, and their workspaces are kept (the path is printed). From Python: ```python from m7gtw_prompts.agent_eval import AgentEvalRunner, Task, Target, Predicate, Command, Judge runner = AgentEvalRunner("https://gateway.example.com", key, max_concurrency=4) report = runner.run( name="nightly-2026-11-27", dataset="agent-tasks", trials=3, tasks=[Task("capital", "What is the capital of France?", expected="Paris", checks=[Predicate("contains", "Paris"), Judge(criteria="Names Paris", model="judge")])], targets=[Target("small", "model", "gpt-small"), Target("agent", "openai_agents_sdk", "gpt-small")], ) print(report["scorecard"]["recommended"]) ``` `run_agent_eval(base_url, key, name=..., dataset=..., tasks=..., targets=..., trials=...)` is the same in one call. The client methods `create_agent_eval`, `record_agent_results` and `get_agent_eval` of `ObservabilityClient` call the API directly, for a runner of your own. ## What the gateway records - **The plan.** `POST /v1/agent-evals` opens one experiment run per target, all at one instant of the dataset, named ` ·