Reference
REST API reference
The management API under /admin/api and the OpenAI-compatible client API under /v1: authentication, the role each endpoint needs, examples and the error envelope.
Updated:
Ragmux exposes four HTTP surfaces:
| Prefix | Audience | Authentication |
|---|---|---|
/v1/… |
your applications (OpenAI-compatible, plus the Anthropic Messages API at /v1/messages) |
Authorization: Bearer sk-proj-… or x-api-key: sk-proj-…: a project key, or a user’s sk-user-… key |
/mcp |
MCP clients (Claude Code, IDE agents) | gateway key with the retrieve scope, see MCP endpoint |
/admin/api/… |
dashboard and management scripts | session cookie, bearer session token, or a user’s sk-mgmt-… key |
/healthz |
load balancers, container healthchecks | none |
All request and response bodies are JSON unless noted. /admin/ (without api) serves
the embedded dashboard.
Authentication
Management API
POST /admin/api/login with {"username": "...", "password": "...", "bearer": true}
returns
{"token": "…", "user": {"id": 1, "username": "admin", "role": "admin", "is_active": true,
"last_login_at": "2026-09-18T10:00:00Z", "created_at": "…"}}
and sets the ragmux_session cookie (HttpOnly, SameSite=Lax, Secure on HTTPS or
with SECURE_COOKIES=true). The token field is only included when the request sets
"bearer": true; the dashboard omits it and relies on the cookie alone. Every other
/admin/api route accepts either that cookie or Authorization: Bearer <token>; the
bearer header wins when both are present. Sessions expire after SESSION_TTL (default
24 h) and are revoked by POST /admin/api/logout, a password change (all other
sessions of the account), a password reset, a session revoke or deactivation of the
account.
An account that has switched on two-factor authentication (TOTP, see
Two-factor authentication) does
not get a session from that call, with bearer: true or without. A right password
answers
{"mfa_required": true, "challenge_token": "…", "expires_at": "2026-09-18T10:05:00Z",
"methods": ["totp", "recovery_code"]}
with no cookie and no token. The challenge lives five minutes, answers once and
closes after five wrong codes. POST /admin/api/login/mfa with
{"challenge_token": "…", "code": "123456"} (or "recovery_code": "abcde-fghjk"
instead of code) then answers like the one-step login: {user}, the cookie and,
when the first step asked for bearer: true, token. A wrong code is
401 {"error":{"code":"mfa_invalid_code","attempts_left":3}}, an expired, spent or
unknown challenge 401 {"error":{"code":"mfa_challenge_invalid"}}. Scripts that need
to run without a second factor use a management key.
TOKEN=$(curl -s localhost:8765/admin/api/login -H 'Content-Type: application/json' \
-d '{"username":"admin","password":"YOUR_PASSWORD","bearer":true}' | jq -r .token)
AUTH="Authorization: Bearer $TOKEN"
Requests authenticated by the cookie are subject to two browser-oriented checks
that bearer requests skip: state-changing methods (POST, PUT, DELETE) must come
from the same origin (Sec-Fetch-Site: same-origin/none, or an Origin whose host
equals the request Host; otherwise 403 {"error":{"message":"cross-site request rejected","type":"forbidden"}}), and JSON bodies must be sent as
Content-Type: application/json (otherwise 415). The login request itself always
needs the JSON content type. Scripts should use the bearer token.
A management key (sk-mgmt-…, see API keys) authenticates the same
routes, but only from the Authorization header. One pasted into the ragmux_session
cookie is refused 401 without even being looked up. That is deliberate and is what
keeps the bearer exemption above sound for keys: a browser attaches cookies to
cross-site requests on its own, whereas it cannot attach an Authorization header
cross-origin without a CORS preflight, and Ragmux only answers preflights for the
origins in CORS_ORIGINS (empty by default). The premise behind the existing exemption
therefore holds identically for management keys, and nothing about the cookie path is
loosened.
These routes refuse an api-key principal outright with
403 {"error":{"code":"session_required"}} — POST /me/password,
POST /users/{id}/reset-password, POST /users/{id}/totp/reset, the four
/me/totp/* routes and creating a kind=management key — so a leaked key
cannot take over the account it belongs to.
What that guard assumes. It treats a session as a person at a keyboard and an api
key as a stored credential, and grants the account-takeover routes only to the first.
"bearer": true weakens the premise: the session token leaves the browser as a string
in a JSON body, and a string can be pasted into a script, a CI secret or a chat window,
at which point a “session” is doing exactly what the guard withholds from keys. The
difference that remains is lifetime and revocation, not interactivity: a session token
expires after SESSION_TTL (24 h by default), dies with a logout, a password change, a
password reset, a session revoke or a deactivation, and cannot be listed, named or
scoped — an api key outlives all of that until someone revokes it. Treat a bearer
session token as a short-lived credential, keep it out of anything durable, and use a
sk-mgmt-… key for automation that is supposed to persist; if a script genuinely needs
one of the routes above, it needs a human to sign in for it.
Every /admin/api response carries Cache-Control: no-store and an X-Request-Id;
unexpected failures answer 500 {"error":{"message":"internal error (request id …)"}}
and log the detail under that id.
Login failures answer
401 {"error":{"message":"invalid username or password","type":"Unauthorized","attempts_remaining":4}},
where attempts_remaining is how many more failures the username may record this
minute before the per-user limit triggers (absent when that limit is disabled). It is
derived from the recorded attempts alone, so an unknown username and a wrong password
get identical answers. Too many failures answer
429 {"error":{"message":"too many login attempts, try again later","type":"rate_limited","locked":false}}
with a Retry-After header; locked is true when the username/address lockout
triggered rather than a per-minute budget (see
Users, roles and limits). Usernames are matched
case-insensitively.
Client API
/v1 routes require Authorization: Bearer <key>, which is one of two things:
sk-proj-…— the project’s default key, returned once when a project is created or its key is rotated. It selects exactly that project, and with it the model connection, system prompt, RAG store and limits. It has no owner, no scopes and no expiry, and can only be rotated, not revoked.sk-user-…— a user-owned gateway key (see API keys). It carries a set of granted projects, its own scopes and its own limits under the project’s, and can be revoked or given an expiry.
The key goes in Authorization: Bearer <key> or, as the Anthropic SDKs send it, in
x-api-key: <key>. Both headers are read on every /v1 route and on /mcp. A request that
carries both is accepted when they hold the same key, which is what Claude Code sends, and
answered 401 when they differ: a credential check does not pick one of two keys. A sk-mgmt-…
management key is no gateway key under either header and is answered like an unknown one.
PRD rule 2 says a management key is accepted from the Authorization header only. It binds
management keys and the admin API, not the header a gateway key arrives in. The admin
API still reads Authorization alone, so x-api-key never opens it, and the cross-site
reasoning behind the rule is unchanged there.
Missing or unknown keys answer 401 with type invalid_request_error (no key header)
or invalid_api_key. An unknown key’s body is exactly
{"error":{"message":"invalid project api key","type":"invalid_api_key","code":null}}
whatever its shape. A key that is known but no longer resolves carries a code on top
— key_revoked, key_expired or key_owner_inactive — so the extra detail only ever
reaches a caller who already holds the key bytes.
A key with a network allowlist that the request does
not satisfy answers 403 {"error":{"type":"permission_error","code":"ip_not_allowed"}} (the
client address is in no listed network) or code: "origin_not_allowed" (the key lists origins
and the request has no Origin header, or one no entry matches). The check runs once the key
has resolved, so an unknown, revoked or expired key keeps its 401; it runs before a project is
chosen, writes no request log row and counts in ragmux_gateway_key_denied_total. It applies
to every /v1 route, to POST /v1/messages with x-api-key and to /mcp alike.
Choosing a project
A sk-user-… key may grant several projects, so each request resolves one, in this
order:
- the
X-Ragmux-Projectrequest header, matched against the granted project names, or against their ids when the value is numeric; - the key’s
default_project_id; - the single grant, when the key has exactly one.
If none of those settles it, POST /v1/chat/completions answers
400 {"error":{"code":"project_required"}} with an X-Ragmux-Projects response header
listing the valid values (prod,staging). A header naming a project the key does not
grant answers 403 {"error":{"code":"project_not_granted"}} with a fixed message that
does not distinguish “no such project” from “not granted”, so a key holder cannot probe
for project names. A key whose last grant was deleted has an empty grant set and gets the
same 403: it fails closed rather than falling back to anything.
GET /v1/models is the exception: with several grants and no header it lists one entry
per granted project’s connection, deduplicated by model name, and GET /v1/models/{id}
then has to name one of them.
There is deliberately no "project/model" convention in the model field.
model_name legitimately contains slashes (org/model-1.5:latest@v2_x is a valid model
name), so the split would be ambiguous and would silently reroute clients that already
send such a name. Use the header.
The grants on the key, not the owner’s project memberships, are what /v1 enforces.
Membership is checked once, when the key is created or updated; after that an admin
editing a member list cannot break a running key.
Roles
The Role column in the tables below is the minimum role required (viewer <
editor < admin). member means the caller must be an admin or a member of the
project; non-members get 404 so project ids are not enumerable. Requests below the
required role answer 403 {"error":{"message":"insufficient role","type":"forbidden"}};
requests without a valid session answer
401 {"error":{"message":"authentication required","type":"unauthorized"}}.
Error envelope
Management endpoints answer errors as
{"error": {"message": "chunk_size must be between 200 and 20000", "type": "Bad Request"}}
where type is the HTTP status text: Bad Request (validation), Not Found,
Conflict (duplicate name, or an item still referenced by a project, RAG store or route),
Forbidden, Internal Server Error. Login limiting and the auth middleware use the
lower-case types shown above.
The client API uses the OpenAI shape with a code field:
{"error": {"message": "invalid project api key", "type": "invalid_api_key", "code": null}}
POST /v1/messages answers in Anthropic’s shape instead, with the same
code carried inside error.
Error codes added in 0.8
These code values are new in 0.8. Each is also described where the endpoint is; this list is
where to look one up by name. type is as in the envelope above; on the management API it is
the HTTP status text.
code |
Status, type |
Where | Meaning |
|---|---|---|---|
guardrail_blocked |
400, invalid_request_error |
/v1/chat/completions, /v1/messages, /v1/retrieve, the MCP tool (as a tool error) |
A block guardrail rule matched at pre_request, or at pre_retrieval on an endpoint with no request to continue. The message names the stage, never the rule |
guardrail_unavailable |
503, server_error |
the same endpoints and /v1/moderations |
The project’s guardrail webhook failed under fail_closed, or the stored guardrail configuration cannot be used. No Retry-After |
invalid_end_user |
400, invalid_request_error |
every /v1 endpoint and the MCP search |
An X-Ragmux-End-User header that is not 1 to 128 bytes of A-Z a-z 0-9 . _ : @ + = / -, or is sent twice. A bad body value is not an error; it is dropped with a Warning |
invalid_tags |
400, invalid_request_error |
chat and messages | X-Ragmux-Tags or ragmux.tags with more than 8 tags, or a tag outside 1 to 64 bytes of A-Z a-z 0-9 . _ : / - |
ip_not_allowed |
403, permission_error |
/v1 and /mcp |
The key’s CIDR list does not admit the client address (see Network allowlists) |
origin_not_allowed |
403, permission_error |
/v1 and /mcp |
The key lists origins and the request has none, a null one, or one that matches no entry |
request_not_found |
404, not_found_error |
POST /v1/feedback |
The key’s project has no request log row with that request_id; another project’s id answers the same. Retry once after a short pause if the answer was only just sent |
session_required |
403, Forbidden |
management API | The action needs a signed-in session and the caller used an API key: anonymisation, two-factor management, password changes, minting a management key |
totp_already_enabled |
409, Conflict |
POST /me/totp/setup, /me/totp/enable |
Two-factor authentication is already on; disable first to change device |
totp_not_set_up |
409, Conflict |
POST /me/totp/enable |
No secret is pending; call setup first |
totp_not_enabled |
409, Conflict |
POST /me/totp/disable, /me/totp/recovery-codes |
Two-factor authentication is not on for the account |
mfa_invalid_code |
401, Unauthorized on sign-in, 403 where the caller has a session |
POST /login/mfa, /me/totp/* |
A wrong code or recovery code. On sign-in the body also has attempts_left |
mfa_challenge_invalid |
401 |
POST /login/mfa |
The sign-in step expired, was used, or was closed by five wrong codes; sign in again |
mfa_locked |
429 |
POST /login, /login/mfa, /me/totp/* |
Five wrong codes in 15 minutes locked the account’s second factor; Retry-After says how long. A right code is refused too |
mfa_busy |
429 |
the same | Another code check of the account is running; Retry-After: 1, not counted as a failure |
wrong_password |
403 |
/me/totp/*, POST /me/password |
The password asked for with the action is wrong; it spends one of the session’s five tries |
password_attempts_exhausted |
401 |
/me/totp/*, POST /me/password |
The session already used its five wrong passwords and is ended; sign in again |
invalid_feedback |
400, invalid_request_error |
POST /v1/feedback |
A missing or malformed request_id, score or label, an unknown field, or a body over 4 KiB |
already_anonymized |
409, Conflict |
POST /users/{id}/anonymize, PUT /users/{id} with is_active: true, POST /users/{id}/reset-password |
The account was anonymised and stays closed |
Management endpoints
All paths are relative to /admin/api.
First-run setup
Unauthenticated by design; both refuse as soon as any user exists.
| Method | Path | Role | Purpose |
|---|---|---|---|
| GET | /setup |
— | While the users table is empty: {"needs_setup": true, "migrations_version": N, "secret_key_source": "env", "database_role": "ragmux", "has_connections": false, "has_projects": false} — the facts after needs_setup let the setup page confirm which database and key the gateway runs on (secret_key_source is env, file, vault_transit or aws_kms, database_role the connected PostgreSQL role, N the applied migration version, whatever this build has reached) and let the wizard resume at the right step. Once any user exists the answer is {"needs_setup": false} and nothing else: the endpoint is unauthenticated, and after setup an anonymous request has no business knowing the migration version, the database role or how far the install got |
| POST | /setup |
— | {username, password, bearer?} creates the first user with the admin role and logs it in (session cookie; token in the body when bearer is true) → 201 {user}. Username: 3–64 characters of a-z 0-9 . _ -; password: at least 12 characters and at most 72 bytes. 409 setup already completed once a user exists, also for a concurrent request that lost the race. Failed attempts count against the per-address login limit (429 with Retry-After). Audited as setup.complete. |
ADMIN_PASSWORD pre-creates the account on start for unattended installs, in which
case setup is already complete (see Configuration).
The dashboard’s first-run wizard has three steps, but only this first one is
unauthenticated. Step 2 (a model connection) and step 3 (a project) are ordinary
authenticated calls to POST /api/models and POST /api/projects made with the session
the first step established, so they are role-gated and audited like any other write and
add no new unauthenticated surface. Both are skippable. A reload during step 2 or 3
picks the step back up from GET /api/models, which the session can already read —
not from GET /setup, which by then answers needs_setup alone.
Session and account
| Method | Path | Role | Purpose |
|---|---|---|---|
| POST | /login |
— | {username, password, bearer?} → {user} plus token when bearer is true; 400 when the username (1–64 characters) or password (1–1024) is missing or too long; the username is matched case-insensitively. For an account with two-factor authentication on, a right password answers 200 {mfa_required, challenge_token, expires_at, methods} instead and issues no session (see Authentication); 429 while that account’s second factor is locked |
| POST | /login/mfa |
— | {challenge_token, code} or {challenge_token, recovery_code} → the same answer as a one-step login; 401 for a wrong code (mfa_invalid_code) or a dead challenge (mfa_challenge_invalid); 429 (mfa_locked, Retry-After) while the account’s second factor is locked, even for a right code; 429 (mfa_busy, Retry-After: 1) while another check of the account is running |
| POST | /logout |
viewer | Ends the session → {"ok": true} |
| GET | /me |
viewer | Current user {id, username, role, is_active, last_login_at, created_at} plus session_expires_at (RFC 3339, empty for a key without an expiry), session_bearer (true when the request carried an Authorization header rather than the cookie), session_kind ("session" or "api_key"), totp_enabled (true when the account has two-factor authentication on) and, for a key, its scopes |
| POST | /me/password |
viewer | {current_password, new_password} (at least 12 characters, at most 72 bytes) → {"ok": true}; 403 when the current password is wrong; every other session of the account is revoked. Session-only: an api key gets 403 session_required. A session may try five wrong passwords here and on the /me/totp/* routes below; the fifth ends it, and a request after that is 401 (code: password_attempts_exhausted while the session still resolves, otherwise the plain unauthorized) |
| POST | /me/totp/setup |
viewer | {password} → {secret, otpauth_uri}: a new base32 secret and the otpauth:// URI an authenticator app imports. 403 wrong_password; 409 totp_already_enabled when two-factor authentication is on (the secret in place is never replaced). Until enable the login stays one-step; another call replaces the pending secret. Session-only |
| POST | /me/totp/enable |
viewer | {password, code} → {"ok": true, "recovery_codes": [...]}: switches two-factor authentication on, returns ten recovery codes once and ends the account’s other sessions. 409 totp_already_enabled / totp_not_set_up; 403 for a wrong password (wrong_password) or code (mfa_invalid_code); 429 while locked. Session-only |
| POST | /me/totp/disable |
viewer | {password, code} or {password, recovery_code} → {"ok": true}: deletes the secret and the recovery codes. 409 totp_not_enabled; errors as enable. Session-only |
| POST | /me/totp/recovery-codes |
viewer | {password, code} → {"ok": true, "recovery_codes": [...]}: ten new codes, shown once; the old ones stop working. 409 totp_not_enabled; errors as enable. Session-only |
| GET | /provider-types |
viewer | Supported provider types with type, label, default_base_url, supports_embeddings, requires_api_key, supports_tools, supports_streaming, and a capabilities object (chat, streaming, embeddings, tools, tool_streaming, vision, remote_images, prompt_caching, cached_token_usage, rerank, plus the model-level native_json_schema, forced_tool_choice, thinking, thinking_off, effort_levels and thinking_prefix_bound, reported for the provider’s current generation) — see Capabilities |
| GET | /provider-presets |
viewer | Ready-made custom_openai setups for hosted OpenAI-compatible providers (Mistral, xAI, Groq), each with id, label, provider_type, base_url, suggested models, an optional embedding_model and requires_api_key. A preset is not stored: create the connection with POST /models using its provider_type and base_url. No preset carries a price — see Presets |
GET /provider-types answers an array with one object per type:
[{"type": "anthropic", "label": "Anthropic", "default_base_url": "https://api.anthropic.com",
"supports_embeddings": false, "requires_api_key": true,
"supports_tools": true, "supports_streaming": true,
"capabilities": {"chat": true, "streaming": true, "embeddings": false, "tools": true,
"tool_streaming": true, "vision": true, "remote_images": true,
"prompt_caching": true, "cached_token_usage": true, "rerank": false,
"native_json_schema": true, "forced_tool_choice": false,
"thinking": "adaptive", "thinking_off": "none",
"effort_levels": ["low", "medium", "high"], "thinking_prefix_bound": true}}]
GET /provider-presets answers an array:
[{"id": "mistral", "label": "Mistral AI", "provider_type": "custom_openai",
"base_url": "https://api.mistral.ai/v1",
"models": ["mistral-large-latest", "mistral-small-latest"],
"embedding_model": "mistral-embed", "requires_api_key": true}]
Model connections
| Method | Path | Role | Purpose |
|---|---|---|---|
| GET | /models |
viewer | List connections |
| POST | /models |
editor | Create → 201 connection |
| GET | /models/{id} |
viewer | Read one |
| PUT | /models/{id} |
editor | Update; an empty api_key keeps the stored key |
| DELETE | /models/{id} |
editor | Delete → {"ok": true}; 409 while a project, RAG store or route target uses it |
| POST | /models/{id}/test |
editor | {mode?}, where mode is "chat" (default) or "embedding"; spends provider quota, so it is a write; the outcome is recorded on the connection |
| POST | /models/test |
editor | Test an unsaved connection: the create body plus mode and optionally connection_id (reuse that connection’s stored key when api_key is empty); nothing is recorded |
Request body for create and update:
{"name": "claude", "provider_type": "anthropic", "api_key": "sk-ant-...",
"model_name": "claude-sonnet-4-5", "base_url": ""}
provider_type is one of openai, anthropic, gemini, deepseek, ollama,
custom_openai, azure_openai, cohere_rerank or voyage_rerank. azure_openai needs
a base_url (the resource endpoint, which may carry an api-version query parameter) and
model_name is its deployment name, see Azure OpenAI; the
two rerank types can serve only rerank targets and RAG store reranking, see
Rerank providers. base_url
must be an http:// or https:// URL with a host and without credentials or fragment
(and without a query string, except the api-version of azure_openai), and is required
for custom_openai and azure_openai; a
host that resolves only to private or local addresses is rejected with 400 unless
allowed by PRIVATE_UPSTREAM_ALLOWLIST / ALLOW_PRIVATE_UPSTREAMS (see
Configuration). model_name may contain letters,
digits and . _ : / @ - (up to 128 characters, no leading /, no ..). The response
never contains the key:
{"id": 1, "name": "claude", "provider_type": "anthropic", "base_url": "",
"api_key_masked": "sk-ant-…abcd", "model_name": "claude-sonnet-4-5", "private_upstream": false,
"last_test_at": "2026-09-18T10:05:00Z", "last_test_ok": true, "last_test_latency_ms": 812, "last_test_error": "",
"created_at": "2026-09-18T10:00:00.000Z", "updated_at": "2026-09-18T10:00:00.000Z"}
private_upstream is true when base_url points at localhost, a loopback, private or
link-local address, or a hostname that resolved only to such addresses when the
connection was saved (it is computed on create and update, never on read; the provider
default URL counts as public). last_test_* describe the most recent
POST /models/{id}/test: all null / empty until the connection has been tested.
POST /models/{id}/test always answers 200 and reports the outcome in the body:
{"ok": true, "reply": "pong", "usage": {…}, "latency_ms": 812} for chat (the model is asked to reply
with the word pong, max_tokens 256), {"ok": true, "dimensions": 1536, "latency_ms": 240}
for embeddings, or {"ok": false, "error": "...", "latency_ms": …}. The result is stored on
the connection as last_test_at, last_test_ok, last_test_latency_ms and
last_test_error (credentials redacted, at most 512 characters).
POST /models/test runs the same test on a connection that has not been saved:
{"provider_type": "custom_openai", "base_url": "http://vllm:8000/v1", "api_key": "",
"model_name": "llama-3", "mode": "chat", "connection_id": 4}
base_url, provider_type and model_name are validated exactly like create (including
the private-address check → 400); name is not required. With connection_id set and
api_key empty the stored key of that connection is used, so an edit form can try a
changed URL or model without re-entering the key. The response has the same shape as
/models/{id}/test; nothing is recorded.
RAG stores and documents
| Method | Path | Role | Purpose |
|---|---|---|---|
| GET | /rag-stores |
viewer | List stores (with document_count, bytes_used, chunk_count, dimensions, vector_index) |
| POST | /rag-stores |
editor | Create → 201 store |
| GET | /rag-stores/{id} |
viewer | Read one |
| PUT | /rag-stores/{id} |
editor | Update → store plus reprocess_recommended; changing language starts a background full-text rebuild |
| DELETE | /rag-stores/{id} |
editor | Delete the store, its documents and vectors; projects linked to it lose the link |
| GET | /rag-stores/{id}/documents |
viewer | List documents, newest first |
| POST | /rag-stores/{id}/documents |
editor | Upload (multipart/form-data, one or more file fields and an optional metadata field with a JSON object for all of them) → 202 document or array of documents, each with deduplicated (and duplicate_of); 400 for invalid metadata; 422 with code: "store_quota" when the store’s max_documents / max_bytes or the instance ceiling would be exceeded |
| POST | /rag-stores/{id}/search |
viewer | Retrieval test; the rerank_backend and rerank_connection_id overrides need editor (Search endpoint) |
| POST | /rag-stores/{id}/reprocess |
editor | Re-parse, re-chunk and re-embed every document → 202 {"ok": true, "documents": n} |
| POST | /rag-stores/{id}/reindex |
admin | Build the vector index of the store’s embedding width in the background → 202; 409 with code: "already_indexed", "not_indexable" or "not_bound" (see below) |
| GET | /documents/{id} |
viewer | Document status |
| PATCH | /documents/{id} |
editor | Replace the document’s metadata ({"metadata": {...}}) → the document; one row update, no reprocessing |
| DELETE | /documents/{id} |
editor | Delete document and its chunks → {"ok": true} |
| POST | /documents/{id}/reprocess |
editor | Re-chunk and re-embed one document → 202 {"ok": true} |
Store body (all fields except name and embedding_connection_id optional; the
retrieval semantics are explained in Retrieval (RAG)):
{"name": "handbook", "embedding_connection_id": 2,
"chunk_size": 1000, "chunk_overlap": 200, "top_k": 5,
"search_mode": "hybrid", "search_backend": "pgvector", "language": "simple",
"rerank": false, "rerank_backend": "llm", "rerank_connection_id": null,
"rerank_candidates": 15, "max_distance": 0, "contextual_chunks": true,
"max_documents": 0, "max_bytes": 0}
Validation: chunk_size 200-20000, chunk_overlap ≥ 0 and smaller than chunk_size,
top_k ≤ 50, search_mode vector or hybrid, search_backend pgvector or
pg_search (400 when this server cannot run it, see
Search backends), language simple or an ISO 639-1 code with a
text search configuration on this server (400 otherwise, see
Store language); a body that omits it keeps the store’s language
(simple on create). fts_config is deprecated: send language instead. A request
that still sends only fts_config has a known configuration name (english) translated
to its language (en); an unknown name, or one that contradicts a language in the same
body, is 400. rerank_backend llm, cohere or voyage
(cohere and voyage need a rerank_connection_id of the matching cohere_rerank /
voyage_rerank type; llm may name a chat connection, see
Reranking), rerank_candidates 1-100, max_distance 0-2,
max_documents and max_bytes ≥ 0 (0 = unlimited, see
Unlimited (0)). The embedding
connection must be of a type that supports embeddings, must produce vectors of at most
4000 dimensions (400 when the probe at save time can tell; otherwise the first ingest
fails the document, see Embedding width) and
cannot be changed while the store has chunks (400). Binding a store to a width of 2001 to
4000 dimensions whose table has no vector index yet is 409 with code: "index_missing":
reindex that width first. Responses carry the usage the
quotas are checked against: document_count and bytes_used.
A store as the API returns it:
{"id": 1, "name": "handbook", "embedding_connection_id": 2,
"chunk_size": 1000, "chunk_overlap": 200, "top_k": 5,
"search_mode": "hybrid", "search_backend": "pgvector", "language": "tr", "fts_config": "turkish",
"fts_language_applied": "tr", "fts_status": "ready", "language_applies_to_search": true,
"rerank": false, "rerank_candidates": 15, "rerank_backend": "llm", "rerank_connection_id": null,
"max_distance": 0, "contextual_chunks": true, "max_documents": 0, "max_bytes": 0,
"dimensions": 1536, "document_count": 3, "bytes_used": 3145728, "chunk_count": 126,
"created_at": "2026-09-18T10:00:00.000Z", "vector_index": "hnsw"}
dimensions is the width of the store’s vectors (0 until the first ingest), and
chunk_count the number of chunks across its documents. vector_index is the state of the
vector index of that width: hnsw, hnsw_halfvec, building, missing or
not_indexable (absent while dimensions is 0), and vector_index_progress is the
percentage while it is building (see Embedding width).
language is the store language, fts_config its deprecated configuration name (derived,
never stored independently), fts_status not_needed, rebuilding or ready,
fts_language_applied the language the full-text column was last built for (null while
pending, and for simple), and language_applies_to_search is false when the store’s
lexical search runs on pg_search, which ignores the language (see
Store language). PUT adds
reprocess_recommended to the object: true when a changed setting only takes effect
for documents after they are re-chunked or re-embedded.
Documents look like
{"id": 7, "rag_store_id": 1, "filename": "handbook.pdf", "mime": "application/pdf",
"size_bytes": 1048576, "status": "ready", "error": "", "chunk_count": 42,
"page_count": 12, "progress_percent": 100, "attempts": 1,
"metadata": {"lang": "tr", "product": "gateway", "tags": ["faq", "billing"]},
"created_at": "…", "updated_at": "…"}
with status moving pending → processing → ready (or failed with error set).
progress_percent follows ingestion: 10 once parsed, 20 once chunked, then the share
of embedding batches completed, 100 when ready; a failed document keeps the value it
reached. page_count is the number of pages of a PDF and null for other formats (and
until the document has been parsed). attempts counts how often a replica claimed the
document for ingestion since it was last queued; a document past the cap is skipped
rather than retried forever.
metadata is the document’s filterable attributes, {} when it has none. It is a flat
object of strings, numbers, booleans and arrays of those, written with the upload’s optional
metadata form field (a JSON string, applied to every file of the request) or replaced
later with PATCH /documents/{id} and {"metadata": {...}} ({} clears it). Limits and
the filter that reads it are in Metadata and filters; an
invalid object is 400, and the audit log records the key names only.
An upload answers each document with two extra fields, deduplicated and, when it is
true, duplicate_of (the id of the twin whose embeddings are expected to be reused):
{"id": 9, "rag_store_id": 1, "filename": "handbook.pdf", "mime": "application/pdf",
"size_bytes": 1048576, "status": "pending", "error": "", "chunk_count": 0,
"page_count": null, "progress_percent": 0, "attempts": 0, "metadata": {"lang": "tr"},
"created_at": "…", "updated_at": "…", "deduplicated": true, "duplicate_of": 7}
It is a forecast made at upload time and is not stored, so a later GET of the document
does not carry it; see Duplicate uploads.
Accepted extensions: .pdf, .docx, .html, .htm, .md, .markdown, .txt; the
request body is limited to MAX_UPLOAD_MB. Upload and reprocess answer
503 the ingestion backlog is full (MAX_PENDING_DOCUMENTS), retry later when the queue
of pending documents is at MAX_PENDING_DOCUMENTS (1024); the documents concerned are
marked failed with that message. The backlog is counted across every replica, not per
process.
Search request and response:
POST /admin/api/rag-stores/1/search
{"query": "vacation policy", "top_k": 3, "mode": "hybrid", "rerank": true, "max_distance": 0.6,
"filter": {"lang": "tr"}}
{"mode": "hybrid", "backend": "pgvector", "language": "tr", "fts_config": "turkish",
"fts_status": "ready", "language_applied_to_search": true,
"reranked": true, "rerank_backend": "llm", "rerank_fallback": false, "latency_ms": 412,
"retrieval_latency_ms": 180, "rerank_latency_ms": 230,
"hits": [{"chunk_id": 8, "document_id": 2, "filename": "handbook.pdf", "index": 3,
"section": "Leave > Vacation", "page": 12, "content": "…",
"distance": 0.18, "score": 0.0325, "vector_rank": 1, "fts_rank": 2,
"lex_score": 7.43}]}
lex_score is the raw BM25 score under the pg_search backend and is absent under
pgvector (Search endpoint).
Everything but query is optional and overrides the store setting for this call only
(mode, backend, rerank, rerank_backend, rerank_connection_id, max_distance
and top_k; the full list and the meaning of the response fields are in
Search endpoint); filter limits the search to the documents
whose metadata matches (Metadata and filters; a filter outside
the grammar is 400); top_k is clamped to 1-50 (0 or absent
uses the store’s top_k). latency_ms is the whole call, retrieval_latency_ms covers
embedding the query and the database search, and rerank_latency_ms the reranker
(null when rerank is off or was skipped; a number, often 0, when the reranker was
tried and fell back, with rerank_fallback: true).
When rerank is on but the store has no rerank_connection_id (and so nothing to rerank
with), the search runs unreranked and the response says so with "rerank_skipped": true
and a rerank_skipped_reason; both are false / "" otherwise.
A 502 is returned when the embedding call fails.
POST /rag-stores/{id}/reindex (admin only) builds the vector index of the store’s
embedding width. The index belongs to the width, so every store of that width gains it. It
answers 202 straight away and builds in the background with
CREATE INDEX CONCURRENTLY; watch vector_index (and vector_index_progress) on the store:
{"dimensions": 2560, "vector_index": "building", "vector_index_progress": 0,
"affected_stores": [{"id": 1, "name": "handbook"}, {"id": 4, "name": "faq"}]}
Errors are 409: already_indexed (the width is 2000 or fewer, or its index is valid),
not_indexable (wider than 4000 dimensions, or wider than 2000 on a pgvector older than
0.7.0) and not_bound (the store has no embeddings yet). The action is written to the audit
log as rag_store.reindex. See Embedding width.
Projects
| Method | Path | Role | Purpose |
|---|---|---|---|
| GET | /projects |
viewer | Projects the caller is a member of (admins: all) |
| POST | /projects |
editor | Create → 201 {"project": …, "api_key": "sk-proj-…"} (key shown once; the creator becomes a member) |
| GET | /projects/{id} |
member | Read one |
| PUT | /projects/{id} |
member + editor | Update (full replace of the fields below) |
| DELETE | /projects/{id} |
member + editor | Delete with its request logs → {"ok": true} |
| POST | /projects/{id}/rotate-key |
member + editor | New key → {"project": …, "api_key": "sk-proj-…"}; the old key stops working immediately |
| GET | /projects/{id}/members |
member | [{id, username, role, added_at}] |
| PUT | /projects/{id}/members |
member + editor | {user_ids} (an array such as [1, 4]) replaces the member set; an editor cannot remove themselves |
| GET | /projects/{id}/metrics?window=24h |
member | Metrics for one project (see below; takes the same compare, days and by_project options as the summary) |
| GET | /projects/{id}/metrics.csv?window=24h |
member | The project’s request logs in the window as a CSV download (see below) |
| GET | /projects/{id}/usage |
member | Live rate-limit and budget counters with a budget forecast |
| GET | /projects/{id}/sessions?limit=50&offset=0 |
member | The project’s sessions, most recently active first (limit defaults to 50, larger values are cut to 500) |
| GET | /projects/{id}/sessions/{sessionId}?limit=100 |
member | One session’s totals and its request log rows, newest first (limit defaults to 100, larger values are cut to 1000); 404 for an unknown session |
| GET | /projects/{id}/feedback/summary?days=30 |
member | The project’s feedback over the last days days (default 30, at most 365): positive, negative, total, ratio (positive / total, null with no feedback), the labelled breakdown and the daily series; counts only (see below) |
| GET | /projects/{id}/guardrails |
member | The project’s guardrails: rules, stream window and webhook settings, every default filled in |
| PUT | /projects/{id}/guardrails |
member + editor | Replace the guardrails as a whole; a rule that cannot work is a 400 naming it |
Project body:
{"name": "support-bot", "model_connection_id": 1, "rag_store_id": 1,
"system_prompt": "You are the company support assistant.",
"member_user_ids": [4],
"rate_limit_rpm": 0, "rate_limit_tpm": 0, "budget_daily_tokens": 0, "budget_monthly_tokens": 0,
"context_placement": "system", "retrieval_policy": "always", "query_strategy": "last_user",
"history_turns_for_query": 3, "query_model_connection_id": null,
"tool_allow": [], "tool_deny": ["mcp__github__*"], "session_token_cap": 0,
"extra_allow": [], "extra_deny": ["store", "service_tier"],
"key_allowed_cidrs": [], "key_allowed_origins": [],
"end_user_rpm": 0, "end_user_tpm": 0, "end_user_daily_tokens": 0, "end_user_monthly_tokens": 0}
rag_store_id may be null or 0 for no store; limits are 0 for unlimited (see
Zero means unlimited).
The last five fields are the project’s RAG behaviour:
| Field | Values | Default |
|---|---|---|
context_placement |
system, before_last_user (Context placement) |
system |
retrieval_policy |
always, auto, off (Retrieval policy) |
always |
query_strategy |
last_user, condense (Query strategy) |
last_user |
history_turns_for_query |
1 to 10 turns sent to condense |
3 |
query_model_connection_id |
a chat connection that condenses the query, or null for the first route target’s |
null |
Unlike the rest of the body, a RAG field left out keeps its current value on update (and
takes the default on create), so a script that does not know them never resets them by
saving the project; query_model_connection_id: null clears that one explicitly. An unknown
value is 400, and so is a query_model_connection_id that is not an existing chat
connection. A connection a project names there cannot be deleted (409). A change is
written to the audit log on the project.update entry, under details.rag_settings_changed
(from and to for each field that changed).
The next three govern tools and sessions
(Users, roles and limits):
| Field | Values | Default |
|---|---|---|
tool_allow |
up to 64 patterns; when not empty, only tools whose name matches one are offered to the model | [] (every tool) |
tool_deny |
up to 64 patterns; a tool whose name matches one is removed from the request, and deny wins over allow | [] |
session_token_cap |
prompt plus completion tokens one session may spend; 0 is unlimited |
0 |
A pattern is 1 to 128 characters of A-Z a-z 0-9 _ . : - and * (any run of characters, the
only wildcard; matching is case sensitive), so mcp__github__* covers a whole MCP server.
Like the RAG fields, these three left out keep their current value on update and take
the default on create; [] clears a list. A pattern that is not of that shape, a list of
more than 64 and a negative cap are 400. A change is written to the audit log on the
project.update entry, under details.tool_settings_changed.
The next two govern the request fields the gateway does not read itself
(POST /v1/chat/completions, POST /v1/messages):
| Field | Values | Default |
|---|---|---|
extra_allow |
up to 64 patterns; when not empty, only an unknown request field whose name matches one is forwarded upstream | [] (every field) |
extra_deny |
up to 64 patterns; an unknown request field whose name matches one is removed from the request, and deny wins over allow | [] |
A pattern has the same shape and the same matching as a tool pattern above, and these two left
out keep their current value on update and take [] on create. A pattern of another shape and a
list of more than 64 distinct patterns are 400. A change is written to
the audit log on the project.update entry, under details.extra_settings_changed. With both
lists empty, which is what every project has until an operator sets them, nothing changes:
the protection exists only where the operator’s lists say so.
The next two restrict where the project’s own sk-proj-… key may be used from
(Users, roles and limits):
| Field | Values | Default |
|---|---|---|
key_allowed_cidrs |
up to 32 networks, IPv4 or IPv6; a bare address is stored as /32 or /128 |
[] (any address) |
key_allowed_origins |
up to 32 browser origins: https://app.example.com or https://*.example.com |
[] (any origin, none needed) |
They are the same lists a user key carries (allowed_cidrs, allowed_origins, see
API keys), with the same validation (400 for anything that is not a network
or an origin, for a network with bits set to the right of its mask, for a lone * and for
more than 32 entries), and the same rule for a field left out: it keeps its current value on
update and takes [] on create. Rotating the key leaves them alone. The response of a save
that leaves a CIDR list in place carries "warnings": [...] when the instance runs
TRUST_PROXY_HEADERS=true with an empty TRUSTED_PROXY_CIDRS, because the list can then be
walked around with a forged X-Forwarded-For; the save is not refused. A change is written to
the audit log on the project.update entry, under details.key_network_changed.
The last four fields are the project’s per-end-user ceilings
(Users, roles and limits): what one end user, named
by X-Ragmux-End-User or by the request body’s own field, may make in a UTC minute and spend
in a UTC day and month.
| Field | Values | Default |
|---|---|---|
end_user_rpm |
requests per minute for one end user | 0 (unlimited) |
end_user_tpm |
prompt tokens per minute for one end user | 0 |
end_user_daily_tokens |
prompt plus completion tokens per UTC day | 0 |
end_user_monthly_tokens |
prompt plus completion tokens per UTC month | 0 |
These four left out keep their current value on update and take 0 on create, like the
fields above; a negative value is 400. A change is written to the audit log on the
project.update entry, under details.limits_changed with the other limits. They bind only a
request that names an end user: a request without one is not held to them (they are a
guardrail, not a security check).
member_user_ids is only read on create (use the members endpoint afterwards). The
full key is never returned again. The project object:
{"id": 3, "name": "support-bot", "model_connection_id": 1, "rag_store_id": 1,
"api_key_prefix": "sk-proj-ab12", "system_prompt": "You are the company support assistant.",
"rate_limit_rpm": 0, "rate_limit_tpm": 0, "budget_daily_tokens": 0, "budget_monthly_tokens": 0,
"context_placement": "system", "retrieval_policy": "always", "query_strategy": "last_user",
"history_turns_for_query": 3, "query_model_connection_id": null,
"tool_allow": [], "tool_deny": ["mcp__github__*"], "session_token_cap": 0,
"extra_allow": [], "extra_deny": ["store", "service_tier"],
"key_allowed_cidrs": [], "key_allowed_origins": [],
"end_user_rpm": 0, "end_user_tpm": 0, "end_user_daily_tokens": 0, "end_user_monthly_tokens": 0,
"member_ids": [4], "created_at": "…", "updated_at": "…"}
api_key_prefix holds the first characters of the key for identification.
GET /projects/{id}/usage:
{"project_id": 3, "generated_at": "2026-09-18T12:00:30Z",
"minute": {"period_start": "2026-09-18T12:00:00Z", "resets_at": "2026-09-18T12:01:00Z",
"requests": 2, "prompt_tokens": 20, "completion_tokens": 4, "tokens": 24,
"request_limit": 2, "request_percent": 100, "token_limit": 0, "token_percent": 0},
"day": {"…": "…", "tokens": 12, "token_limit": 5, "token_percent": 100, "resets_at": "2026-09-19T00:00:00Z"},
"month": {"…": "…"},
"forecast": {"daily_exhausted_at": "2026-09-18T15:40:00Z", "monthly_exhausted_at": null}}
forecast extends the tokens consumed in the last 60 minutes linearly and reports when
each budget would run out at that pace. A value is null when the budget is not set,
nothing was consumed in the last hour, or the projection lands after the window resets
(resets_at); an already exhausted budget projects to generated_at.
GET /projects/{id}/sessions lists the sessions the project’s requests carried in
X-Ragmux-Session; it reads one running total per session, not the request logs:
[{"project_id": 3, "session_id": "agent-run-42", "requests": 18, "prompt_tokens": 91000,
"completion_tokens": 7400, "tokens": 98400,
"first_seen": "2026-10-31T09:12:00Z", "last_seen": "2026-10-31T09:41:10Z"}]
tokens is prompt_tokens + completion_tokens, the figure session_token_cap is compared
with. GET /projects/{id}/sessions/{sessionId} returns {"session": {…}, "requests": […]}:
the same object, and the session’s request log rows in the shape of
recent below. The roles are those of the request logs: any member can read them.
GET /projects/{id}/feedback/summary counts the scores clients sent through
POST /v1/feedback, by the day each was first received (UTC):
{"days": 30, "positive": 41, "negative": 9, "total": 50, "ratio": 0.82,
"labels": [{"label": "helpful", "positive": 30, "negative": 0},
{"label": "wrong_answer", "positive": 0, "negative": 6}],
"daily": [{"day": "2026-11-03", "positive": 12, "negative": 2}]}
labels covers the labelled feedback only, the busiest 50 labels first; feedback sent without
a label is in the totals. daily lists the days that have feedback. There is no content to
show: the endpoint never receives any. The roles are those of the request logs.
Guardrails
A project can screen what goes into the model and what comes back (ADR-034). The rules live on the project; this endpoint reads and replaces them as a whole.
{"rules": [
{"id": "citizen-id", "type": "tckn", "action": "redact", "stages": ["pre_request", "post_response"]},
{"id": "card-words", "type": "keywords", "action": "block", "stages": ["pre_request"], "keywords": ["card number", "cvv"]},
{"id": "ticket", "type": "regex", "action": "flag", "stages": ["post_response"], "pattern": "TKT-[0-9]{6}"}],
"stream_window_chars": 128,
"webhook": {"enabled": true, "timeout_ms": 2000, "failure_mode": "fail_closed"},
"warnings": []}
warnings is only in the answer (a PUT body may send it; it is ignored): what is allowed
but risky, for instance a window too small to hold a whole tckn or iban match, a
regex that can match more than the window, or a webhook that is enabled while the project
has no guardrail webhook endpoint yet.
| Field | Meaning |
|---|---|
rules[].id |
^[a-z0-9_-]{1,32}$, unique in the project. It names the rule in the request log, the placeholder and the moderation categories |
rules[].type |
tckn (11 digits whose checksum holds), iban (mod-97 and the country’s length; spaces between groups of four are read), regex (RE2, at most 512 bytes, must not match the empty string) or keywords (at most 500 words of at most 64 bytes; case-insensitive, whole words, Turkish and other Unicode letters respected) |
rules[].action |
block, redact (the match becomes [REDACTED:<id>]) or flag (counted, nothing changes) |
rules[].stages |
one or more of pre_request, pre_retrieval, post_response |
rules[].pattern / keywords |
for regex / keywords only |
stream_window_chars |
32 to 2048, default 128: how much of a streamed answer is held back to catch a match split across chunks |
webhook.enabled |
consult the project’s guardrail webhook at pre_request and pre_retrieval, after the local rules |
webhook.timeout_ms |
100 to 10000, default 2000 |
webhook.failure_mode |
fail_closed (default) or fail_open |
At most 32 rules. A PUT is audited as project.guardrails_update with the rule ids,
never the patterns or words.
What each stage reads.
| Stage | Reads | A block |
A redact |
|---|---|---|---|
pre_request |
on /v1/chat/completions: every message’s content (a string, or every part except an image, audio or a file, whatever the part’s type is called), its name, the reasoning_content of an earlier assistant turn, the name and arguments of tool calls, tool results, and the text of a prediction; a content or an argument in a shape the schema does not allow (one object where a list belongs, a list of bare strings, arguments as an object) is read all the same. On /v1/messages: system and every content block: text, document, search_result, tool_result (and the blocks nested in it), tool_use name and input, and any block type the gateway does not know, whose strings are all read, URLs and names included, except ids, signatures, encrypted payloads, settings and base64 data. Not images, not the contents of a base64 document (a PDF is not searched for text), not tool definitions, not the project’s own system prompt, not the signed thinking blocks of earlier turns, not user, stop, response_format, metadata or any other request field: those are the application’s settings, not text a person wrote, and the tool lists and the policy for extra request fields (ADR-041) are the operator’s instruments for what a request may carry, not a content scan |
400, code: "guardrail_blocked"; nothing is sent upstream and no retrieval runs |
|
pre_retrieval |
the retrieval query, after a condense strategy has rewritten it. Applies to chat, POST /v1/retrieve and the MCP tool. The retrieved passages are not scanned (they are the operator’s corpus) |
in chat the search is skipped (x-ragmux-rag-skip: guardrail) and the request goes on without context; /v1/retrieve and MCP answer 400 guardrail_blocked |
the search runs with the redacted query; the model still sees the client’s own text |
post_response |
the answer: content, refusal, tool call arguments, annotations and citations (cited_text, annotations[].url_citation.title), the results a server tool returned, and thinking. Not the RAG context |
the answer is replaced by an empty one with finish_reason: "content_filter" (stop_reason: "refusal" on /v1/messages); the JSON answer carries x-ragmux-guardrail: blocked. The tokens were spent and are counted |
the match is replaced. Thinking can only be flagged (see below) |
All rules of a stage run, in the order they are listed: a redact changes the text the
rules after it read, and a block anywhere wins. (One limit in a stream: a block rule written against text that an earlier redact rule has already replaced sees the replacement, because the window rewrites as it goes. The text the redact rule hid never leaks, but that block can fail to fire where it would on the whole answer, and the rest of the text it would have matched is then written. Write such a rule against the text a client would send, not against what the rules leave.) An empty rule list, or one with no rule
for a stage, leaves that stage out entirely: no scan, no window, no latency, and a native
/v1/messages stream stays a byte-for-byte copy of the upstream’s.
Streams. post_response on a stream holds back the last stream_window_chars - 1
characters until it can tell they are not the start of a match, so the first text reaches the
client later: about 0.3 to 0.6 s with the default 128 characters, at the speed of a typical
model (an estimate; it is the time the model needs to write the window). A block stops the
stream with a final chunk (content_filter / refusal) and the upstream call is cancelled;
nothing of the match, or after it, is written. The Warning header and x-ragmux-guardrail
cannot be set once a stream has begun. On /v1/messages against an Anthropic connection the SSE
events are rewritten when the project has a post_response rule.
Tool call arguments are read as JSON when they are JSON: every key, every string and every number in them. A match in a number ({"id": 10000000146}) or a key is replaced by a string placeholder, so the arguments stay valid JSON, and a block rule sees it. The JSON is also read once as a whole text, for block rules only, so a pattern that spans a key and its value ("password": "…") stops the request too; a redact or flag rule of that shape is matched only in a streamed answer. Arguments that are not JSON are read as text. In a stream the arguments arrive in pieces and cannot be parsed as they come, so they are scanned as text: a block is caught, a redact hides the match, but a redacted number leaves [REDACTED:<id>] unquoted in the stream and the client’s JSON parse of the finished arguments can fail. Use block on a rule meant for tool arguments if that matters.
What the webhook is sent. The project’s own rules read every key, string and number of tool call arguments. The guardrail webhook is sent the keys and the string values, one texts entry each, and never a number, nor the arguments as one text: a numeric value is not text a person wrote, and a receiver that is sent every 7 and 1 of a tool’s input gets a body made mostly of noise. A webhook that must see a number in tool arguments cannot; a local rule can.
Names. A tool’s name and a participant’s name are letters, digits, _ and -. A redact rule writes REDACTED-<id> there instead of [REDACTED:<id>] (refresh-token becomes refresh-REDACTED-tok), so the call stays well formed and the request acceptable. A redacted name no longer matches the name in the client’s own tool table, so the call is not executed under it: that is the price of hiding it. block and flag act on names as they do on text.
Duplicate keys. A JSON key that appears twice is read as the first value by one parser and as the last by another. Tool arguments and inputs with a repeated key go on with the last value only, so a value the rules did not read does not travel with them.
Placeholders. [REDACTED:<id>] is let alone by the rules after the one that wrote it only where the gateway wrote it. A client that types one gets no exemption: a rule reads that text like any other.
Token log-probabilities. logprobs spell the answer out one token at a time and a token cannot be redacted, so a project with a post_response rule that blocks or redacts does not return them: logprobs and top_logprobs are removed from the request before it goes upstream, the answer carries none, and the response has Warning: 299 ragmux "logprobs was dropped: …" (set before the first byte, so a stream has it too). A project whose post_response rules only flag hides nothing and is not affected, and neither is one without a post_response rule.
Thinking. A thinking block is signed by its provider, and an edited block would be refused
when the client sends it back. post_response therefore scans thinking text, applies block
and flag, and treats redact as flag; the signature is never touched. pre_request does not
scan the thinking blocks of earlier turns.
What is recorded. The request log row gets guardrail_blocked_stage (the stage that refused
something), guardrail_redactions, guardrail_flags, guardrail_rules (the ids of the rules that
matched, at most 16) and guardrail_webhook (ok, error, timeout or skipped_fail_open).
The counters are ragmux_guardrail_events_total and ragmux_guardrail_webhook_total.
The matched text, its hash and its position are stored and logged nowhere. A blocked request is a
request: it takes a slot of the request limit.
Webhook endpoints. With webhook.enabled, the gateway posts the request to the project’s
guardrail webhook endpoint after the local rules ran, signed as every Ragmux webhook is:
{"version": "2026-11-01", "stage": "pre_request", "request_id": "req_…", "project_id": 3,
"endpoint": "chat.completions",
"texts": [{"index": 0, "role": "system", "text": "…"}, {"index": 1, "role": "user", "text": "…"}]}
stage is pre_request or pre_retrieval (then a single text with role: "query"); there is no
call at post_response. The receiver answers 200 with
{"action": "allow"|"block"|"redact"|"flag", "reason": "<a-z0-9_.-, up to 32>", "texts": […]};
texts is only read for redact and must have the same length and index values as the request.
The call is synchronous, has no retry, and a request body over 1 MB is not sent. A timeout, a
transport error, a status outside 2xx, a redirect, a reply that is not this shape, or texts that do
not line up all count as a failure: fail_closed answers 503 with code: "guardrail_unavailable" (no
Retry-After; the guardrails are down, not busy), fail_open serves the request and counts
skipped_fail_open. The reason is recorded as webhook:<reason> in guardrail_rules.
A stored configuration this version cannot read or compile is treated like a failed closed
webhook: the project’s requests are refused with guardrail_unavailable rather than served
unguarded.
Routes
A route is a named entry point inside a project: the client’s model field selects it,
and the route spreads requests over its targets. A project without chat routes works as
before (see Model field echo). Adding the first chat route
changes what an unknown model string gets: read
Before your first chat route first.
| Method | Path | Role | Purpose |
|---|---|---|---|
| GET | /projects/{id}/routes |
member | List the project’s routes with their targets |
| POST | /projects/{id}/routes |
member + editor | Create → 201 route |
| GET | /projects/{id}/routes/{routeId} |
member | Read one |
| PUT | /projects/{id}/routes/{routeId} |
member + editor | Replace the route and all of its targets in one transaction |
| DELETE | /projects/{id}/routes/{routeId} |
member + editor | Delete → {"ok": true} |
Route body:
{"name": "smart", "kind": "chat", "strategy": "weighted",
"targets": [
{"connection_id": 1, "model": "gpt-4.1", "weight": 3, "priority": 0},
{"connection_id": 2, "weight": 1, "priority": 0}]}
nameis 1 to 256 characters without control characters and is unique within the project (409otherwise).kindischat(default),embeddingsorrerank.strategyisweighted(default), the only one.targetsholds 1 to 8 entries.connection_idmust exist and its provider type must support the route’skind.modelis optional: when set it replaces the connection’s model name for calls through that target.weightis 1 to 1000 (default 1) andpriorityis 0 to 100 (default 0, lower first). The same connection andmodelpair may appear only once per route.- Invalid input is
400. The response liststargetsordered bypriority, thenid, each withconnection_nameandprovider_typenext to the stored fields.
A route as the API returns it (model is null for a target that keeps the
connection’s model name):
{"id": 5, "project_id": 3, "name": "smart", "kind": "chat", "strategy": "weighted",
"targets": [
{"id": 11, "connection_id": 1, "connection_name": "openai-main", "provider_type": "openai",
"model": "gpt-4.1", "weight": 3, "priority": 0},
{"id": 12, "connection_id": 2, "connection_name": "claude", "provider_type": "anthropic",
"model": null, "weight": 1, "priority": 0}],
"created_at": "…", "updated_at": "…"}
Candidate order for a call: groups by priority ascending; inside a group a weighted
random order without replacement. The first candidate is called; a failure before the
first byte is retried on it or hands the request to the next candidate, as
Retry and fallback describes, and a connection whose
circuit breaker is open is skipped.
Deleting a project removes its routes; a connection that a route target still uses cannot
be deleted (409). Create, update and delete are audited as route.create,
route.update and route.delete. Route and target names are never metric labels.
API keys
User-owned credentials, separate from a project’s default key. Everyone manages their
own; admins see and manage everyone’s. A key someone else owns answers 404, not 403,
so key ids are not enumerable. All of these need the keys scope when the caller is
itself a management key.
| Method | Path | Role | Purpose |
|---|---|---|---|
| GET | /keys |
viewer | The caller’s keys, newest first, each with the owner’s username. Admins get every owner and may narrow with ?user_id=; ?kind=gateway|management filters both. user_id is ignored for non-admins |
| POST | /keys |
viewer | Create → 201 {"key": {…}, "api_key": "sk-user-…"}; the credential is returned once and never again |
| GET | /keys/{id} |
owner or admin | Read one |
| PUT | /keys/{id} |
owner or admin | Update the mutable fields (below); the credential and the kind never change — revoke and reissue instead |
| POST | /keys/{id}/revoke |
owner or admin | Sets revoked_at → the key object; effective on the next request |
| GET | /keys/{id}/usage |
owner or admin | The key’s own counters, in the shape of /projects/{id}/usage with api_key_id instead of project_id |
| DELETE | /keys/{id} |
admin | Delete outright → {"ok": true}; 409 {"error":{"code":"key_in_use"}} while request logs still reference the key. Revoking is almost always what you want |
Request body:
{"kind": "gateway", "name": "ci-pipeline", "scopes": ["chat", "models", "retrieve"],
"project_ids": [1, 2], "default_project_id": 1, "expires_at": "2027-01-01T00:00:00Z",
"user_id": 4,
"rate_limit_rpm": 0, "rate_limit_tpm": 0, "budget_daily_tokens": 0, "budget_monthly_tokens": 0,
"allowed_cidrs": ["203.0.113.0/24"], "allowed_origins": ["https://app.example.com"]}
kind is gateway (default) or management. name is required, at most 64 characters
and unique per owner (409 otherwise). A gateway key’s scopes may name chat, models,
embeddings, retrieve and rerank and defaults to all five when omitted or empty; a
management key’s scopes may name read, write, admin and keys and are required. An
unknown scope (the message lists the valid values for the kind), or one the caller’s own
role does not cover, is a 400. expires_at is RFC 3339, and null or "" clears it.
user_id mints the key for another account and needs the admin role; the grants
are then checked against that account, not the admin’s.
For a gateway key, every id in project_ids must be a project the owner can access
(400 otherwise) and default_project_id must be one of them. For a management key,
projects and limits are refused with a 400: it has neither. Creating a management key
additionally needs at least the editor role and a dashboard session
(403 session_required for an api key); the admin scope needs the admin role.
allowed_cidrs and allowed_origins restrict where a gateway key may be used from
(Network allowlists): up to 32 entries each, empty
(the default) meaning no restriction. A CIDR entry is an IPv4 or IPv6 network, or a bare
address, which is stored as /32 or /128; an IPv4-mapped IPv6 network (::ffff:10.0.0.0/104)
is stored as the IPv4 one. An origin entry is scheme://host[:port] (http or https, lower
case, no path, no trailing /, the scheme’s default port left out) or https://*.example.com
for any subdomain but not the apex itself; a lone * is refused. Entries are stored in that
canonical form and repeats collapse. A malformed entry, a network with bits set to the right
of its mask (10.0.0.5/24) and more than 32 entries are 400; so is any entry on a
management key, which never passes through this check. On update a field left out keeps its
current list (unlike the limits above, which a save resets), and [] clears it, so a script
that does not know the fields never lifts a restriction by saving the rest of the key. When
the instance runs TRUST_PROXY_HEADERS=true with an empty TRUSTED_PROXY_CIDRS, a save that
leaves a CIDR list in place answers with "warnings": ["…"] next to the key (on update, beside
the key’s own fields), because the list can be walked around with a forged X-Forwarded-For;
the save is not refused.
The key object never contains the credential:
{"id": 7, "kind": "gateway", "name": "ci-pipeline", "key_prefix": "sk-user-Wg8TwBF",
"user_id": 1, "created_by": 1, "scopes": ["chat", "models", "retrieve"], "project_ids": [1, 2],
"default_project_id": null, "rate_limit_rpm": 0, "rate_limit_tpm": 0,
"budget_daily_tokens": 0, "budget_monthly_tokens": 0,
"allowed_cidrs": ["203.0.113.0/24"], "allowed_origins": ["https://app.example.com"],
"expires_at": null, "revoked_at": null, "last_used_at": "2026-09-19T03:41:00Z",
"created_at": "…", "updated_at": "…"}
key_prefix is the first 15 characters, for identification in listings and the audit
log. last_used_at is stamped by /v1 at most once a minute per key, so a busy key does
not rewrite its row on every request. Semantics, scopes and the interaction of the two
limit tiers are described in
Users, roles and limits.
Metrics
| Method | Path | Role | Purpose |
|---|---|---|---|
| GET | /metrics/summary?window=24h&compare=1&days=14&by_project=1 |
viewer | Summary over the projects the caller can see |
| GET | /metrics/requests?limit=50&project_id=3 |
viewer | Recent request logs, newest first (limit defaults to 100, max 1000; project_id must be visible to the caller) |
| GET | /metrics/requests.csv?window=24h&project_id=3 |
viewer | Request logs in the window as a CSV download (project_id optional, same visibility rule) |
window is a Go duration (default 24h). Optional summary parameters:
| Parameter | Effect |
|---|---|
compare=1 |
adds previous: the same summary fields for the window of equal length that ends where the current one starts |
days=N |
sizes the daily series (1–90, default 14; out-of-range values are clamped) |
by_project=1 |
adds projects: one row per project with requests in the window, busiest first, limited to the projects the caller can see |
The summary response (also used by /projects/{id}/metrics):
{"window": {"requests": 120, "errors": 3, "prompt_tokens": 51000, "completion_tokens": 9800,
"avg_latency_ms": 840.5, "p95_latency_ms": 2100, "rag_requests": 95, "rate_limited": 2,
"cost_micros": 184500, "cost_usd": 0.1845},
"total": {"…": "same fields over all time"},
"daily": [{"day": "2026-09-05", "requests": 10, "errors": 0, "prompt_tokens": 4000,
"completion_tokens": 900, "cost_micros": 15400, "cost_usd": 0.0154}],
"recent": [{"id": 991, "project_id": 3, "model_name": "claude-sonnet-4-5", "status_code": 200,
"prompt_tokens": 420, "completion_tokens": 80, "estimated": false, "latency_ms": 910,
"streamed": true, "rag_used": true, "rag_hits": 3, "cached_prompt_tokens": 200,
"cache_write_tokens": 0, "cost_micros": 1860, "cost_usd": 0.00186,
"cost_source": "builtin", "error": "", "api_key_id": 7, "user_id": 4,
"request_id": "3f2a9c1e", "endpoint": "chat.completions", "requested_model": "smart",
"route": "smart", "attempt": 2, "fallback_from": 1,
"session_id": "agent-run-42", "tool_names": ["get_weather"], "tools_denied": 1,
"end_user": "[email protected]", "tags": ["support", "v2"],
"created_at": "…"}],
"previous": {"…": "only with compare=1"},
"projects": [{"project_id": 3, "name": "support-bot", "requests": 80, "errors": 2, "prompt_tokens": 30000,
"completion_tokens": 6000, "rate_limited": 1, "rag_requests": 70,
"cost_micros": 120000, "cost_usd": 0.12}]}
daily covers the last days days (14 by default), recent the last 50 requests.
rag_hits is the number of retrieved passages injected into that request (0 when
rag_used is false). api_key_id and user_id attribute the request to the user-owned
key that made it and are null for a project’s default key; the owner is denormalised so
deleting the key later leaves user_id in place. request_id, endpoint,
requested_model, route, attempt and fallback_from identify how the request ran and
are left out of a row when empty (always for rows written before migration 0016);
attempt is the number of upstream calls, fallback_from the connection id of the first
target when the request moved to another one, and route is absent for the implicit
route. session_id (the request’s X-Ragmux-Session), tool_names (the tools the model
called in its answer: sorted, without duplicates, at most 32 names of at most 64 bytes;
names only, never arguments) and tools_denied (how many tools the project’s lists removed)
are left out when empty or 0. end_user (the request’s end user)
and tags (its tags, sorted, without duplicates) are left out when the request named none.
Their meaning is in the request log. Status semantics (429, 499,
502, 503/504) are described in
Users, roles and limits.
Cost fields appear on the summary objects (window, total, previous), on each
daily bucket, on each projects row and on each recent request:
| Field | Meaning |
|---|---|
cost_micros |
the estimated cost in USD millionths; an integer, so sums are exact |
cost_usd |
the same figure in dollars (cost_micros / 1e6) |
cost_source |
on a request: builtin or user for the price row that matched, none when no row did (then the cost is 0) |
cached_prompt_tokens |
part of prompt_tokens that a provider cache served |
cache_write_tokens |
part of prompt_tokens that was written into a provider cache (Anthropic only) |
Cost is an estimate from the price table, never a bill, and it is informational only — budgets are counted in tokens, not money.
CSV export
GET /metrics/requests.csv and GET /projects/{id}/metrics.csv return the window’s
request logs, oldest first and at most 50 000 rows, as text/csv with a
Content-Disposition: attachment; filename="ragmux-requests-<date>.csv" (or
ragmux-project-<id>-requests-<date>.csv) header. Columns:
created_at, project_id, project_name, model_name, status_code, prompt_tokens, completion_tokens,
estimated, latency_ms, streamed, rag_used, rag_hits, error,
cached_prompt_tokens, cache_write_tokens, cost_usd, cost_source, api_key_id, user_id,
session_id, tool_names, tools_denied, end_user, tags
New columns are appended at the end and existing ones never move, so an importer that
reads by position keeps working. cost_usd is written with six decimals — the full
precision of the stored micro-dollar integer, so a cheap request does not round to zero.
api_key_id and user_id are empty for a request made with a project’s default key,
which has no owner; an empty cell says that where a 0 would read as user zero.
Cells that begin with =, +, - or @ (also after a leading tab or carriage return)
are prefixed with a single quote so a spreadsheet does not evaluate them as formulas;
model names and error messages can be shaped by an upstream.
tool_names and tags are the names joined with ;; session_id, end_user and tags are
empty for a request that carried none. An end user can legitimately begin with + or @, so
it is prefixed with a quote like any other cell that could be read as a formula.
The CSV carries the columns above only: request_id, endpoint, requested_model,
route, attempt and fallback_from are in the JSON log and the database, not in the
export.
Model prices
The price table turns the token counts of a finished request into the estimated
cost_micros on its log row. It is an estimate, not a bill: providers round,
discount and change prices without telling the gateway.
| Method | Path | Role | Purpose |
|---|---|---|---|
| GET | /prices |
viewer | {"prices": [...], "builtin_version": 3, "unit": "per_million_tokens", "search_unit": "per_unit"} |
| POST | /prices |
editor | {provider_type, model_pattern, input_per_mtok, output_per_mtok, cache_write_per_mtok?, cache_read_per_mtok?, per_search_unit?, currency?} → 201 {price}; always created with source: "user". 409 when that provider/pattern pair already exists |
| PUT | /prices/{id} |
editor | Same body without provider_type/model_pattern (they are fixed); sets source: "user" → {price} |
| DELETE | /prices/{id} |
editor | {"ok": true}; 409 {"code":"builtin_price"} for a built-in row — reset it instead |
| POST | /prices/{id}/reset |
editor | Restores the shipped values and marks the row built-in again → {price}; 409 {"code":"no_builtin_price"} when the row has no shipped counterpart |
Every mutation is audited as price.create, price.update, price.delete or
price.reset, and drops the gateway’s cached table so the next request is costed with
the new numbers (it is otherwise re-read every 60 seconds).
A row:
{"id": 4, "provider_type": "anthropic", "model_pattern": "claude-sonnet-4-5*",
"input_per_mtok": 3.0, "output_per_mtok": 15.0, "cache_write_per_mtok": 3.75,
"cache_read_per_mtok": 0.30, "per_search_unit": null, "currency": "USD",
"source": "builtin", "builtin_version": 3, "created_at": "…", "updated_at": "…"}
per_search_unit is the price of one search unit of a rerank API, in the row’s currency
per unit, not per million tokens; null means the model has none. Cohere bills a
rerank call by search unit (the response’s meta.billed_units.search_units, taken as 1
when absent), so its rows carry it. Voyage bills rerank by token and uses
input_per_mtok. The value is 0 to 100. A row with a cohere_rerank or voyage_rerank
provider_type prices the rerank connection of that type; a spend whose connection has
no matching row adds 0 to cost_micros. A row whose per_search_unit is set (not null,
0 included) prices a rerank by search units alone: its token prices are never added for
that call, so a token price typed into a Cohere row has no effect on rerank spend, and an
explicit 0 makes the rerank free.
Prices are per million tokens and prices are between 0 and 100000. The two cache
prices are absolute prices, not multipliers of input_per_mtok — every provider
picks its own convention (Anthropic bills writes at 1.25x and reads at 0.1x, OpenAI does
not bill writes at all and reads at 0.5x) — and both are nullable: null means the
provider charges the input rate.
Matching. A model name is resolved against the rows of its connection’s provider
type. An exact model_pattern wins; otherwise the pattern with the longest literal
prefix (the text before its first *) that matches, ties going to the lowest id.
* stands for any run of characters, / included, so deepseek-ai/DeepSeek-V3* works.
Longest prefix is why gpt-4o-mini* beats gpt-4o* for gpt-4o-mini-2024-07-18. With
no match the main call adds 0 and the request is logged with cost_source: "none" — a
missing price is reported as missing, never guessed. A rerank that ran on another
connection inside the same request is priced by its own row and still adds its cost.
source plays no part in matching. Your own row wins where its pattern is the more
specific one, and you override a shipped number by editing that row (which keeps its
pattern and flips it to "user") rather than by adding a broader one — a * row that
outranked every built-in pattern would silently re-price every model the shipped table
already knows.
Built-in rows and upgrades. The shipped table is seeded on every start.
- Editing a built-in row flips its
sourceto"user", and upgrades never touch a"user"row again. - An untouched built-in row is refreshed only when the shipped table’s
versionincreases; a release that does not bump it changes nothing. - Built-in rows cannot be deleted, only edited or reset. That removes the “deleted row resurrects on upgrade” problem without a tombstone column to remember it by.
- The seed only inserts and refreshes; it never removes a row. Dropping a model from the shipped table therefore leaves existing installs holding the old row, and retiring one is a numbered migration you can read in the release — a general “remove whatever the shipped table stopped listing” rule would let a pattern renamed in a later release silently drop a model’s price everywhere.
ollamaships a*row at 0: it runs on your own hardware, so it must never report phantom spend.custom_openaiships no row at all — it is a URL, and it points at a paid API as readily as at vLLM, so its models arecost_source: "none"until you add a price. A catch-all at 0 would report a real bill as$0.00withcost_source: "builtin", which reads as a priced zero rather than the missing price it is.
Users and audit log
| Method | Path | Role | Purpose |
|---|---|---|---|
| GET | /users/lite |
editor | Active users as [{id, username, role}] (for member pickers) |
| GET | /users |
admin | All users, each with project_count (memberships), active_sessions (unexpired sessions), totp_enabled (two-factor authentication is on) and anonymized_at (when the account was anonymised, else null) |
| POST | /users |
admin | {username, password, role, project_ids?} → 201 user (role defaults to viewer, password at least 12 characters and ≤ 72 bytes, username ≤ 64); project_ids adds the memberships in the same transaction, 422 when one of them is unknown; 409 when the username already exists in any casing |
| GET | /users/{id} |
admin | Read one |
| PUT | /users/{id} |
admin | {role, is_active} (both optional); deactivating drops the user’s sessions |
| DELETE | /users/{id} |
admin | Delete → {"ok": true} |
| POST | /users/{id}/reset-password |
admin | {new_password} (at least 12 characters, at most 72 bytes); revokes the user’s sessions and clears the account’s wrong second-factor codes and open challenges; 400 for the caller’s own account (use POST /me/password). Session-only |
| POST | /users/{id}/totp/reset |
admin | Removes the user’s two-factor authentication (secret, recovery codes), its wrong-code history and its sessions → {"ok": true}; 400 for the caller’s own account (use /me/totp/disable). Audited as user.totp_reset. Session-only |
| POST | /users/{id}/sessions/revoke |
admin | Sign the user out everywhere |
| POST | /users/{id}/anonymize |
admin | {confirm} (the account’s current username, exactly) → {"ok": true, "pseudonym", "revoked_keys"}; replaces the personal fields with one random pseudonym and keeps usage history; 400 on a wrong confirm or for the caller’s own account, 409 for the last active admin or code: "already_anonymized". Audited as user.anonymize. Session-only |
| POST | /end-users/anonymize |
admin | {end_user, project_id?} → {"pseudonym", "request_logs", "end_user_usage", "alert_events", "webhook_deliveries"} (rows changed); without project_id every project; 404 for an unknown project. Audited as end_user.anonymize. Session-only |
| GET | /audit |
admin | Audit entries, newest first, with the total for the filter |
| GET | /audit/export |
admin | The same filters as NDJSON (one entry per line), at most 100 000 rows, newest first, as an attachment; audited as audit.exported |
| GET | /security/logins |
admin | Failed-login counters and active lockouts |
GET /users answers an array of user objects with the two counters, the second-factor flag and the anonymisation time:
[{"id": 1, "username": "admin", "role": "admin", "is_active": true,
"last_login_at": "2026-09-18T10:00:00Z", "created_at": "…",
"project_count": 2, "active_sessions": 1, "totp_enabled": false, "anonymized_at": null}]
POST /users/{id}/anonymize and POST /end-users/anonymize are for a signed-in session:
a management key, even one with the admin scope, gets 403 with
code: "session_required". What they change, and what they cannot reach, is in
Users, roles and limits.
PUT/DELETE on users refuse to demote, deactivate or delete the last active admin
(409) and to deactivate or delete the caller’s own account (400). On an
anonymised account, PUT with is_active: true and
POST /users/{id}/reset-password are 409 with code: "already_anonymized": it stays closed.
GET /audit?limit=100&action=project.&actor_user_id=1&since=2026-09-01T00:00:00Z&until=2026-09-18T00:00:00Z&before=2026-09-17T10:00:00Z:
action is a prefix match, since (inclusive) and until (exclusive) bound
created_at, before pages backwards (all three RFC 3339; a malformed value is a
400), limit defaults to 100 (max 1000). The response is
{"entries": [{"id": 512, "actor_user_id": 1, "actor_username": "admin", "action": "project.rotate_key",
"target_type": "project", "target_id": 3, "details": {"name": "support-bot"},
"ip": "203.0.113.7", "created_at": "…"}],
"total": 1834, "has_more": true}
where total counts every entry matching action, actor_user_id, since and
until (ignoring before and limit) and has_more tells whether another page
exists beyond this one.
GET /audit/export?action=login.&since=… streams the same entries as
application/x-ndjson (Content-Disposition: attachment; filename="ragmux-audit-<timestamp>.ndjson"),
one JSON object per line in the shape above, newest first, capped at 100 000 rows;
before is honoured so a larger range can be exported in slices. Every export writes
an audit.exported entry whose details carry the filters that were used.
GET /security/logins:
{"failed_last_hour": 12, "failed_last_24h": 40,
"active_lockouts": [{"username": "admin", "ip": "203.0.113.7", "until": "2026-09-18T10:14:00Z"}]}
The counters are failed password attempts in the login_attempts table (wrong second-factor codes are recorded there too but not counted); active_lockouts lists
the username/address pairs the login limiter currently refuses, computed with the same
LOGIN_LOCKOUT_FAILURES / LOGIN_LOCKOUT_MINUTES rule, with until the time the
lockout ends (empty when the lockout is disabled).
System
GET /system (viewer), with sample values — migrations_version and version are
whatever the running build reports:
{"database": {"postgres_version": "17.11", "pgvector_version": "0.8.6", "pg_search_version": "", "migrations_version": N, "size_bytes": 8787635},
"backup": {"tables": 1, "documents_bytes": 1048576, "last_migration_at": "2026-09-18T12:34:41Z"},
"secret_key_source": "env",
"version": "<x.y.z>"}
backup.tables is the number of chunk_embeddings_<dims> tables, documents_bytes the
bytes of uploaded files stored in the database, secret_key_source is env, file,
vault_transit or aws_kms (see Secret key sources).
database.pg_search_version is the installed ParadeDB pg_search extension, empty when it
is absent (see Search backends). database.postgres_version,
database.pgvector_version and database.pg_search_version are only returned to admins;
editors and viewers receive the database object without those three keys.
Health
GET /healthz pings the database and answers 200 {"status":"ok","version":"<x.y.z>"}
(the version of the running build) or 503 db unavailable (plain text). No
authentication.
GET /healthz (liveness) and GET /readyz (readiness, see
Observability) are part of the v1.0 API contract,
alongside /v1 and /admin/api/…. From 1.0 on, their paths, methods and status meanings
(200 passes, 503 does not, /readyz answers 200 with a degraded entry for conditions
that still serve traffic) follow the same deprecation policy as /v1, and their JSON bodies
only gain fields.
Client API (/v1)
Point any OpenAI SDK at http://<host>:8765/v1 with the project key as api_key. The
Anthropic SDKs and Claude Code use http://<host>:8765 as their base URL (they add
/v1/messages themselves); see POST /v1/messages.
POST /v1/chat/completions
Accepts the OpenAI Chat Completions payload: model, messages (text or
text / image_url content parts), stream, temperature, top_p, max_tokens /
max_completion_tokens, stop, n, tools, tool_choice, response_format,
stream_options, user (also safety_identifier; both name the request’s
end user). Unknown fields are forwarded to OpenAI-compatible upstreams
unchanged (see Providers), unless the project’s extra_allow / extra_deny
lists remove them (below), with one exception: an
optional ragmux object is consumed by the gateway and never sent upstream. A tool message may carry
"ragmux_is_error": true to mark a failed tool call (see
Anthropic). messages is required; the
body may not exceed 4 MiB.
{"model": "…", "messages": […], "ragmux": {"sources": "inline", "filter": {"lang": "tr"}}}
The ragmux object can only narrow what the project’s RAG settings would do for this
request, or ask for more information back; it cannot turn retrieval on or change a project
setting. Its fields:
| Field | Value | Effect |
|---|---|---|
retrieval |
"off" |
skip retrieval for this request |
filter |
an object | retrieve only from documents whose metadata matches (Metadata and filters) |
sources |
"inline" |
return the retrieved sources in the response body, streamed or not |
include_context |
true |
the sources plus the exact context block that was injected |
sources and include_context add a top-level ragmux object to a non-streaming response
and to the first chunk of a stream that carries choices (no extra chunk is sent); see
RAG. An object that is not a JSON object, or a filter
outside the grammar, is 400 with code: "invalid_ragmux"; every other thing the gateway
cannot honour (another value for retrieval or sources, a project setting, an unknown
field, a narrowing with nothing to narrow) is ignored and reported in a Warning header.
The full rules are in The ragmux request object.
What happens to a request, in order:
- The project’s rate limits and budgets are checked (before any embedding call).
- The project
system_prompt, if set, is prepended to the firstsystem/developermessage (or inserted as one). - If the project has a RAG store, the retrieval policy decides
whether to retrieve (a skipped request carries
x-ragmux-rag-skip). Otherwise the lastusermessage, or a standalone rewrite of it when the project’squery_strategyiscondense, is the query, and the retrieved passages are injected into the first system message or in front of the last user message, as the project’scontext_placementsays. The per-minute token limit is checked once more against the whole prompt. The response carriesx-ragmux-rag-hits: <n>and, when passages were injected,x-ragmux-rag-sourceslisting them. Retrieval failures are logged and the request continues without context. - The request is translated for the provider and sent. A project without chat
routes ignores
modelfor selection: the project’s connection decides. Once a project has a chat route,modelselects what runs and an unknown value is404 model_not_found(seeGET /v1/models). The value you send is echoed back in the response (modelof the completion and every stream chunk); an empty value is replaced with the connection’s model name. A failure before the first byte can be retried and handed to the route’s next target (Retry and fallback).
Non-streaming responses are the provider’s answer normalised to the OpenAI schema
(choices[].message, finish_reason, usage). Streaming responses are
text/event-stream with data: {chunk} lines and a final data: [DONE]; a failure
after the stream has started is emitted as a data: {"error": …} event before [DONE].
The usage-only trailer — one final chunk carrying "choices": [] and usage
before [DONE] — is sent only when you set stream_options: {"include_usage": true},
exactly as OpenAI does. This holds on every provider: the gateway always asks its
upstream for token counts, because the request log, the budgets and the cost are built
from them, but it does not pass that trailer on to a client that did not ask for one,
because a client indexing choices[0] on every chunk would break on it.
That is a promise about Ragmux’s own trailer, not about every chunk. An upstream is
relayed as it comes, and some send frames of their own with an empty choices array —
Azure’s content-filter chunk, a proxy’s keep-alive. Ragmux does not drop those: they
carry information it does not own. Guard the array before indexing it.
Reasoning and thinking. reasoning_effort (none, minimal, low, medium, high,
xhigh, max; max is Ragmux’s addition to OpenAI’s set) is translated into each
provider’s own thinking setting, and the thinking a model produces comes back in one field
whichever provider answered. Which setting a model takes is decided per model
(Model-level capabilities); the tables are in
Reasoning effort.
- Not sent, nothing sent. Without
reasoning_effortno thinking setting is sent and the model’s own default applies. - An unknown value is
400(code: "invalid_reasoning_effort") onanthropic,geminiandollama, because the gateway translates the field itself and a typo ("hgih") would otherwise run silently at the provider’s default. OpenAI-compatible and Azure connections relay the field as sent and the upstream judges it. - A model without thinking (a Claude 3.5, Gemini 2.0, …) is not an error: the field is
dropped and the response carries a
Warning. The same goes for the value the model cannot take (xhighon a model without it is the next level down;noneon a model that cannot switch thinking off is the lowest effort), and fortemperature, which Anthropic does not accept while thinking is on and is therefore left out. max_tokens. On Anthropic a thinking budget has to fit undermax_tokens, so the gateway adjusts it: with nomax_tokensit sends the budget plus 4096 (budget models) or 16000 athighand above (adaptive models); a budget at or above the client’s ownmax_tokensis lowered to leave 1024 tokens for the answer, and below that thinking is dropped with aWarning. On Gemini and Ollama the output limit covers thinking as well and is left as the client set it.
ragmux_thinking carries the thinking as Anthropic-shaped blocks, in a non-streaming
choices[].message and in the streaming choices[].delta:
"message": {"role": "assistant", "content": "...",
"ragmux_thinking": [
{"type": "thinking", "thinking": "…", "signature": "EuYBCkYI…"},
{"type": "redacted_thinking", "data": "EmwKAhgB…"}]}
In a stream the entries are partial updates, and a client merges them by index the way it
accumulates tool_calls: text arrives in thinking, the signature arrives last for its
block, and a redacted_thinking block arrives whole.
{"delta": {"ragmux_thinking": [{"index": 0, "type": "thinking", "thinking": "The user "}]}}
{"delta": {"ragmux_thinking": [{"index": 0, "type": "thinking", "signature": "EuYBCkYI…"}]}}
- The blocks are always sent when the model produced thinking; there is no opt-in, because a
tool round on Anthropic fails unless the client can hand them back. OpenAI SDKs ignore the
unknown field. Claude 5 returns the thinking text omitted:
thinkingis then empty or absent and thesignaturecarries the block. The gateway does not log thinking. - Gemini thought summaries and Ollama
message.thinkingbecome unsignedthinkingblocks. Gemini only returns thoughts whenreasoning_effortis set. Gemini’s own signatures stay inragmux_signatureon the tool calls. - OpenAI-compatible upstreams:
reasoning_contentis relayed as the upstream sent it, and also written as an unsignedthinkingblock, so a client can read one field everywhere. Areasoning_contenton an assistant message of the request is forwarded to these connections as sent; the adapters that translate the request (Anthropic, Gemini, Ollama) drop it and the response carries aWarning.
Sending thinking back. Put the ragmux_thinking the response gave you on the same
assistant message of the next request, unchanged, together with its tool_calls. On
Anthropic the signed blocks (thinking with a signature, redacted_thinking with
data) are written at the start of that assistant turn, in order and with their bytes
unchanged. Unsigned blocks (from Gemini, Ollama or a compat upstream) are not sent to
Anthropic, which cannot read them. Ollama takes unsigned thinking back as message.thinking;
every other adapter removes the field. Only the shape is checked: the value is an array
whose elements have type thinking or redacted_thinking, string thinking and
signature, and a non-empty string data for a redacted block, and it appears only on
assistant messages. Anything else is 400 with code: "invalid_ragmux_thinking". The
signature itself is the upstream’s to verify.
On Anthropic models with a thinking budget (Claude 4.5 and earlier), sending the blocks
back is what keeps thinking on across a tool round: a request that ends in a tool result
whose assistant turn carries no signed block is sent without thinking, and the response has
a Warning. The same models take no forced tool_choice with thinking, so there thinking is
left out as well, with a Warning.
Known limit: the gateway rebuilds an assistant message as thinking blocks, then text, then tool calls. If the model produced several text blocks, or thinking between text blocks, the order and the number of blocks do not survive the round trip through this endpoint. On Claude 5.1 and later, where the API checks a block against everything before it, that can make the replay invalid.
Retrieval and thinking blocks. Claude 5.1 and later bind a thinking block to the system
prompt and messages that preceded it, and retrieval changes that prefix on every turn. For a
model with that binding (thinking_prefix_bound), in a project whose retrieval is active (a
store, and a retrieval_policy other than off; a request that sends ragmux.retrieval: "off" counts, because earlier turns may have had context injected), the thinking blocks of
earlier turns are not sent to Anthropic and the response carries a Warning. The model
loses its earlier reasoning in exchange for a request that is not rejected. Models without
that binding keep their blocks.
usage carries OpenAI’s breakdown objects whenever the provider reports them:
"usage": {"prompt_tokens": 250, "completion_tokens": 500, "total_tokens": 750,
"prompt_tokens_details": {"cached_tokens": 200, "cache_creation_tokens": 40},
"completion_tokens_details": {"reasoning_tokens": 30}}
prompt_tokens always includes the cached and freshly written parts, on every provider:
that is a property of the mapping, so it holds whatever the upstream’s own spelling was.
prompt_tokens + completion_tokens == total_tokens is weaker — it describes how each
adapter assembles the block from an upstream that reports its counts consistently, and
it is not checked. Two things break it: a Gemini request that called tools, where
Gemini’s own total can be larger and the difference is neither mapped nor priced (see
Gemini tool-use tokens), and any upstream that reports
something that does not add up, which is relayed as it came (below). A client that
relies on the sum should verify it. cache_creation_tokens has no OpenAI equivalent
(OpenAI does not bill cache writes, Anthropic does). See
Prompt caching for the per-provider mapping, including
the accounting change for cached Anthropic requests.
The usage block in the response is the upstream’s own. Normalising renames fields
into the OpenAI shape and fills two gaps — a total_tokens of 0 is computed from the
two parts, and DeepSeek’s top-level prompt_cache_hit_tokens is folded into
cached_tokens — but it validates nothing. A provider that reports something impossible,
a negative count or a total that does not add up, reaches you that way.
What Ragmux records is cleaned. The request log, the budget counters and the cost
estimate floor every count at zero; a prompt_tokens or completion_tokens that arrived
unusable is replaced with a character estimate and the row is flagged estimated; an
unusable cache split drops to zero without that flag, because the flag speaks for those
two counts and they were fine. So a request log row and the usage of the same request
can differ when the upstream misreported. Trust the row for spend, and treat a mismatch
as a signal about that provider.
Sessions. A request may carry X-Ragmux-Session: <id> (1 to 128 characters of
A-Z a-z 0-9 . _ : -, sent once) to say which agent run it belongs to. The gateway stores
the id on the request log row and adds the request’s tokens to that session’s total, which
the admin API lists; when the project sets session_token_cap, a request of a
session that has already spent that many tokens is answered 429 (below). Without the
header nothing changes, and the cap does not apply to it: it is a guard against a runaway
loop, not an access control. An id outside that set is 400 with code: "invalid_session_id" and is never ignored, because ignoring it would let a malformed
header past the cap. The session is not a metric label or a span attribute.
End users and tags. A request can say who it is for and how to classify it; both go to the request log row, the CSV export and (for the end user) the per-end-user ceilings, and to nothing else: they are not a metric label, a span attribute or a log field.
Header (every /v1 endpoint, and the MCP search) |
Body | |
|---|---|---|
| End user | X-Ragmux-End-User: <id> |
chat and embeddings: safety_identifier, else user; messages: metadata.user_id |
| Tags | X-Ragmux-Tags: a,b,c |
chat and messages: ragmux.tags |
- Which one wins. The header beats the body for the end user: the header is Ragmux’s, the
body field is the provider’s. The body’s first filled field is the one used
(
safety_identifierbeforeuser); if it is unusable the next is not tried. For tags the request’s ownragmux.tagsbeats the header (a proxy may add one); with both, the extension is used and aWarningsays the header was not. - The end user. 1 to 128 bytes of
A-Z a-z 0-9 . _ : @ + = / -(an e-mail address fits). A header that is not of that shape, or is sent twice, is400withcode: "invalid_end_user"and is never ignored, because ignoring it would let a malformed header past the per-end-user ceilings. A body value that is not of that shape is not an end user: the request is served, the row has none and aWarningsays so, so a client that has always sent free text inuserkeeps working. - Tags. At most 8, each 1 to 64 bytes of
A-Z a-z 0-9 . _ : / -; repeated ones count once and the set is stored sorted. Anything else, an empty item (a,,b) and an empty header included, is400withcode: "invalid_tags". Tags classify; they take no part in limits or access. - What reaches the provider. Only the value the body carried, never the header’s. An
OpenAI-compatible upstream and the native
/v1/messagespath to Anthropic get the body as it was sent. On the translated path an Anthropic connection getsmetadata.user_idset toh-and the first 61 hex digits of the SHA-256 of the end user, 63 characters, only when the body’s value is usable; anything else is dropped, as before. This is a change from earlier releases, which dropped the field; see Anthropic for what the hash is and is not. Gemini and Ollama get nothing. The embeddings endpoint reads the body’s fields for the row only and sends them nowhere.
Tool lists. When the project sets tool_allow or tool_deny, the gateway applies them
to tools before the request goes upstream. A tool is matched by function.name (or
custom.name); a tool that matches tool_deny, or matches no tool_allow pattern while that
list is not empty, is removed from tools, and the response carries a Warning naming up
to five of them. tool_calls and tool messages already in the conversation are left as
they are. tool_choice is then reconciled with what is left:
tool_choice |
After the tools are removed |
|---|---|
| names a tool the project does not allow | 400, code: "tool_not_allowed" |
"required" and no tool is left |
400, code: "tool_not_allowed" |
"auto", absent or "none", and no tool is left |
tools, tool_choice and parallel_tool_calls are dropped, with a Warning. "none" is treated like "auto" here: with no tool left it has nothing to forbid, and upstreams refuse tool_choice without tools |
allowed_tools |
its tools list loses the entries the project does not allow, with a Warning; a "required" list that ends up empty is 400, code: "tool_not_allowed", and an emptied "auto" list becomes "none", so the model does not gain the tools the client left out (with no tool left, or none in the request, tool_choice is dropped) |
| anything else | unchanged |
Request fields the gateway does not read. Every top-level field outside the ones listed at the
start of this section (model … user) is kept as it came and sent to an OpenAI-compatible upstream unchanged
(Request field passthrough), and some of those
fields change what a request costs or what the provider keeps: store, service_tier,
web_search_options, modalities, audio, prediction. When the project sets extra_allow or
extra_deny, the gateway applies them to those fields right after the body is decoded, before the
tool lists. A field that matches extra_deny, or matches no extra_allow pattern while that list
is not empty, is removed from the request and the response carries Warning: 299 ragmux "field <name> removed by project policy" (one per field for up to five fields, then one more that counts
the rest); the request is still served, never refused. What Ollama reads (keep_alive, num_ctx,
options) is such a field too. The fields the gateway reads (the list at the start of this
section, and the ragmux object) are not affected, and neither is the user or
safety_identifier as the end user of record; a safety_identifier the
policy removed is, like any removed field, not sent to the provider on a translated request either;
the user the request also carries is what the provider gets then, as if the other field had not been sent.
The request log row records tools_denied (how many were removed) and tool_names (the
tools the model called, names only). An upstream may refuse a request whose history holds
tool calls but whose tools came out empty; that refusal is relayed as the upstream’s own
error.
Response headers, only for limits that are set on the project or the key. Where both tiers have a limit, the header describes whichever has the smaller remaining allowance:
| Header | Meaning |
|---|---|
x-ratelimit-limit-requests |
configured requests per minute |
x-ratelimit-remaining-requests |
requests left in the current UTC minute |
x-ratelimit-reset-requests |
whole seconds until the minute window resets |
x-ragmux-budget-daily-remaining |
tokens left in today’s budget |
x-ragmux-budget-monthly-remaining |
tokens left in this month’s budget |
x-ragmux-rag-hits |
passages injected (present whenever the project has a store, 0 when none matched) |
x-ragmux-rag-sources |
JSON array of {document_id, filename, section, page, score} for the injected passages; present only when x-ragmux-rag-hits is above 0, trimmed to whole entries to stay under 2 KB. ragmux.sources: "inline" returns the whole list in the body |
x-ragmux-rag-skip |
present when the project has a store and this request did not retrieve, with the reason: policy_off, client_off, tool_turn, greeting, ack or guardrail (then x-ragmux-rag-hits is 0). Absent when retrieval ran. See Retrieval policy |
X-Request-Id |
on every /v1 response, errors included. The client’s own X-Request-Id when it is 1 to 128 characters of A-Z a-z 0-9 . _ : -; anything else (absent, empty, longer, other characters) is replaced by an id the gateway generates — never rejected. The value is stored in request_logs.request_id for every call that writes a row: one that went upstream or was denied by a limit. A call answered earlier (401, 403, 400, project_required, an unresolvable route) carries the header but has no row. See the request log |
x-ragmux-guardrail |
blocked on a JSON answer a post_response block rule emptied (see Guardrails) |
x-ragmux-projects |
on a 400 project_required only: the project names the key grants, comma separated |
Warning |
299 ragmux "<text>" when the request was accepted but part of it was ignored (a body user / safety_identifier / metadata.user_id that is not a usable end user, or an X-Ragmux-Tags that ragmux.tags overrode, are two of them): response_format json_object on an Anthropic model that cannot be forced to call a tool, where an instruction in the system prompt stands in for it (see Structured output), or a tool_choice the model cannot take (see Anthropic), or a part of the ragmux object (see The ragmux request object), or a thinking setting the model could not take (see Reasoning and thinking), or a match a redact guardrail rule replaced (see Guardrails), one header per problem and at most eight. Set before the first byte, so a stream carries it too |
Browser clients need CORS_ORIGINS to read any of these: the gateway lists them in
Access-Control-Expose-Headers (together with Retry-After and X-Request-Id; Warning is in the table above) and
accepts X-Ragmux-Project, X-Ragmux-Session, X-Ragmux-End-User and X-Ragmux-Tags in
Access-Control-Allow-Headers, but a cross-origin page
sees no response header outside the CORS safelist unless the request went through CORS
at all.
Status codes:
| Status | When |
|---|---|
400 |
malformed JSON, missing messages, a ragmux that is not an object or has an invalid filter (code: "invalid_ragmux"; no request log row is written), a translation error such as an image the provider’s adapter cannot take (an unsupported type, or a remote URL while IMAGE_FETCH=false; see Images), a multi-project key that named none (code: "project_required", with X-Ragmux-Projects listing the valid values), an invalid X-Ragmux-Session (code: "invalid_session_id"), an invalid X-Ragmux-End-User (code: "invalid_end_user"), invalid tags in X-Ragmux-Tags or ragmux.tags (code: "invalid_tags"), a reasoning_effort the gateway cannot translate (code: "invalid_reasoning_effort"), a malformed ragmux_thinking (code: "invalid_ragmux_thinking"), or a tool_choice the project’s tool lists make impossible (code: "tool_not_allowed"), or a request a guardrail block rule refused (code: "guardrail_blocked", the message names the stage, never the rule or the match) |
401 |
missing or invalid key; code is key_revoked, key_expired or key_owner_inactive for a key that exists but no longer resolves, and null for an unknown one |
403 |
the key lacks the route’s scope (type: "insufficient_scope"), or it does not grant the requested project (code: "project_not_granted"), or the key’s network allowlist refuses the request (type: "permission_error", code: "ip_not_allowed" or "origin_not_allowed") |
404 |
the project has chat routes and model names neither a route nor the default connection’s model (code: "model_not_found") |
413 |
body larger than 4 MiB |
429 |
rate limit or budget exceeded; Retry-After set, body `{“error”:{“message”,“type”:“rate_limit_exceeded” |
429 |
the gateway is already fetching as many images at once as IMAGE_FETCH_MAX_CONCURRENT allows, or the project has taken its half of them; Retry-After set, body {"error":{"message","type":"rate_limit_exceeded","code":"image_fetch_saturated"}}. It is a resource limit rather than a fault, so it is not a 5xx, which would report the gateway as unwell when it is merely full; Retry-After carries IMAGE_FETCH_TIMEOUT, since a slot frees when a download finishes |
429 |
the session spent session_token_cap tokens; no Retry-After, because a session does not reset; body {"error":{"message":"Session token cap reached (N of M tokens used).","type":"insufficient_quota","code":"session_token_cap","scope":"session"}}. A request may run a session past the cap by its own size, and concurrent requests of one session can each pass the check before any of them is counted |
4xx from the provider |
relayed with the provider’s status and message (API-key-looking strings redacted). A Retry-After the provider sent (seconds or an HTTP date) is passed through unchanged; a malformed one is dropped |
503 / 504 |
the provider answered 503 or 504 (or, on an Anthropic connection, 529 overloaded, which becomes 503): the status is kept, because both say “retry later” rather than “broken”, with the provider’s message and its Retry-After, if any |
503 |
the guardrails could not be consulted: the project’s guardrail webhook failed under fail_closed, or its stored configuration cannot be used (type: "server_error", code: "guardrail_unavailable"; no Retry-After) |
500 |
the project’s model connection cannot be set up (model connection unavailable; the reason is in the gateway log) |
502 |
any other 5xx from the provider (500, 501, 502, …, with its message), transport failure, a provider error without a status, or a crash inside the provider adapter during a stream; mid-stream failures are logged as 502 |
499 |
never sent on the wire: recorded in the request log when the client disconnected before the completion finished. The upstream call is cancelled in both the JSON and the streaming path |
POST /v1/messages
The Anthropic Messages API, so the official Anthropic SDKs and Claude Code work after a base URL change and nothing else:
ANTHROPIC_BASE_URL=http://<host>:8765 ANTHROPIC_API_KEY=<key> claude
Everything around the call is POST /v1/chat/completions: the same key (in x-api-key or
Authorization), the same chat scope, project selection, routes,
retry and fallback, rate limits and budgets, the request log (endpoint = messages), the
tool lists and sessions. A query string such as ?beta=true is
ignored. POST /v1/messages/count_tokens and Anthropic-shaped model listings are not served.
The project’s guardrails apply here as on chat. A refusal comes in Anthropic’s error shape with the same code (guardrail_blocked, guardrail_unavailable); a post_response block ends the message with stop_reason: "refusal" and no content.
The optional ragmux object has the same grammar as on chat, as a top-level field of the
body. It is consumed by the gateway and never sent upstream, which matters because the
Anthropic API refuses an unknown field. "sources": "inline" returns the sources as a
top-level ragmux field of the answer, or in message_start.message.ragmux when streaming.
Two paths. Each attempt of a request takes the path its target allows, so a route whose first target is Anthropic and whose fallback is Gemini serves one client with both.
| Anthropic connection (native) | any other connection (translated) | |
|---|---|---|
| Request | the client’s body, with the changes listed below | translated to the chat request every adapter takes |
anthropic-version, anthropic-beta |
sent upstream as the client sent them (2023-06-01 if absent) |
not applied; a Warning lists the beta values, and a version other than 2023-06-01 |
| Answer | the upstream’s bytes, JSON or SSE, ping events included |
written as a Messages answer |
model in the answer |
the model the client sent (written over the one the upstream reports, in the message and in message_start) |
the model the client sent |
Upstream 4xx |
the upstream’s body, unchanged, with its status | n/a |
Native path. The gateway changes only these parts of the body (and, when the project sets
extra_allow or extra_deny, the unhandled top-level fields they remove, below): model (the connection’s
model is written in, and the client’s own model string is written back into the answer, so
a route alias such as fast reads the same whichever target served the call, as on
chat completions), system, ragmux (removed), the tools the project denies, the thinking
blocks of earlier turns under the retrieval rule below, and tool_choice where the model
cannot take it. Every other field, context_management, container, mcp_servers, strict
tools, cache breakpoints, passes through. Where the project’s context goes differs from
chat: the project’s system prompt, and retrieved context under the system placement, are
added after the client’s own system blocks, not in front of them. A Claude Code attribution
block therefore stays first. Under the before_last_user placement the context is a text
block in the last user message, after its tool_result blocks, which the API requires to come
first.
For a model that does not take a forced tool choice (forced_tool_choice in
Capabilities, true of Opus 5.5 and of models the table does not
know yet), tool_choice: {"type":"any"} and {"type":"tool",…} are sent as {"type":"auto"},
with a Warning. For a model with manual thinking (thinking: {"type":"enabled",…}), thinking is
left out, with a Warning, when tool_choice is forced or when the request returns tool
results to an assistant turn that has no thinking block; top_p below 0.95 is left out
while thinking is on, for manual and adaptive thinking alike.
Not metered. The native path sends the body and anthropic-beta on as they are. Some
features are billed by use, not by token: server tools such as web_search_*, container and
code execution, and mcp_servers. That spend does not reach Ragmux’s cost figures or token
budgets. A project can switch the server tools off with a tool_deny pattern (they are matched by
name, web_search* for example). mcp_servers and container are not in tools, so the
tool lists do not reach them; the project’s extra_deny does, for them and for every other
top-level field the gateway has no name for (context_management, top_k, …).
Field policy. extra_allow and extra_deny (see the project body) apply to the
top-level fields of the body that are not model, messages, system, max_tokens,
temperature, top_p, stop_sequences, stream, tools, tool_choice, thinking,
metadata, output_config and ragmux. A field the policy removes is left out of the body on
both paths, so a route that falls back from an Anthropic target to another provider sees the same
fields, and the response carries Warning: 299 ragmux "field <name> removed by project policy";
the request is served, not refused. Empty lists leave the body as it came. The values of the
anthropic-beta header are not part of this policy.
Translated path. The request becomes a chat request: system (one system message per
block, with its cache breakpoint), text and image blocks, tool_use and tool_result (a user
message that returns tool results becomes tool messages, then a user message for the rest),
tools, tool_choice (any is required, disable_parallel_tool_use is
parallel_tool_calls: false), stop_sequences, metadata.user_id as user, thinking and
output_config.effort as reasoning_effort (a budget_tokens is mapped to the nearest effort,
with a Warning), and a json_schema output_config.format as response_format. Thinking
blocks of earlier turns go through as ragmux_thinking. What has no counterpart is dropped and
named in a Warning: top_k, context_management, container, mcp_servers, server tools,
citations, document and search_result blocks, and any other field the gateway does not know.
The native path forwards such blocks to Anthropic as the client wrote them.
The answer is written as a message. stop_reason follows finish_reason (stop is
end_turn, length is max_tokens, tool_calls is tool_use, content_filter is
refusal); stop_sequence is always null, because which sequence matched is not known on
this path. A stream is message_start, the content blocks, message_delta and message_stop;
while the upstream is quiet a ping event is written every 10 seconds. Tool calls arrive as
tool_use blocks with their input in input_json_delta events. A model that returns
several text blocks, or thinking between them, is rebuilt as thinking, then text, then tool
calls, so the known limit stated for chat completions (the order
and number of blocks do not survive the round trip, which can invalidate a replay on Claude 5.1
and later) applies to this path. The native path has no such limit.
End user and tags. X-Ragmux-End-User and X-Ragmux-Tags work as on
chat; the body’s sources are metadata.user_id for the end user and
ragmux.tags for tags. On the native path metadata goes to Anthropic as the client sent it
(an over-long user_id is Anthropic’s 400, as it has always been); a translated request to
an OpenAI-compatible upstream sends it as user.
Sessions and retrieval. X-Ragmux-Session names the session; when it is absent, the
x-claude-code-session-id header Claude Code sends stands in, under the same rules (an
unusable value is 400, code: "invalid_session_id"). A turn whose last user message holds a
tool_result is a tool turn, whatever else the message holds (Claude Code adds a reminder
text next to the result), and retrieval is skipped for it. For a model that binds thinking to the
prompt prefix, in a project whose retrieval is active, earlier turns’ thinking and
redacted_thinking blocks are not sent, with a Warning: this is the retrieval rule of
chat, and it applies on both paths.
Errors. Errors the gateway makes (401, 403, 404, 429, a refused request, 5xx) are
Anthropic’s envelope, with Ragmux’s own code, when there is one, in error.code (an unknown
key has none, as in the body above):
{"type": "error", "error": {"type": "permission_error", "message": "api key is not authorised for chat completions", "code": "insufficient_scope"}, "request_id": "…"}
The request_id is the X-Request-Id of the response, also sent as request-id. error.type
follows the status: 400 invalid_request_error, 401 authentication_error, 403
permission_error, 404 not_found_error, 413 request_too_large, 429 rate_limit_error,
503 overloaded_error, 504 timeout_error, any other 5xx api_error. The statuses
are the ones of chat completions, above. On the native path a 4xx
from Anthropic reaches the client with Anthropic’s own body. An error after a stream began is an
error event.
POST /v1/embeddings
OpenAI’s embeddings.create, so an SDK’s client.embeddings.create(...) works against the
gateway. Needs the key’s embeddings scope (403 otherwise).
{"model": "text-embedding-3-small", "input": ["first text", "second text"], "encoding_format": "float"}
inputis a string or an array of up to 2048 non-empty strings. Arrays of token ids are refused (400); the providers behind the gateway embed text.encoding_formatisfloat(default) orbase64, the little-endianfloat32bytes base64-encoded, as OpenAI’s SDKs expect.dimensionsis not supported and answers400: the adapters cannot shorten a vector.safety_identifierandusername the request’s end user for the log row and the per-end-user ceilings, as on chat. They are not sent to the provider.
{"object": "list", "model": "text-embedding-3-small",
"data": [{"object": "embedding", "index": 0, "embedding": [0.01, -0.02, …]}],
"usage": {"prompt_tokens": 9, "total_tokens": 9}}
model is resolved in this order: a route of kind embeddings with exactly that name
(see Routes, which also gives it retries and fallback targets); the implicit
route, which is the embedding connection of the project’s RAG store and answers to that
connection’s model name and to an empty model; anything else is 404
{"error": {"type": "invalid_request_error", "code": "model_not_found", …}}. It never
falls back to the project’s chat connection, a model that cannot embed, and a project with
no RAG store has no implicit route. The response model is the client’s value (the
connection’s model name when none was sent).
Each call goes through the same steps as chat: limits and budgets are checked first, the
call is recorded in the request log with endpoint = embeddings, the upstream’s
prompt_tokens and the price. An upstream that reports no usage gets an estimate
(characters divided by 4), flagged estimated in the log. Errors use the
error envelope and the status mapping of chat completions.
POST /v1/retrieve
Searches the project’s RAG store and returns the passages, without calling a chat model.
Needs the key’s retrieve scope. The scope decides, not the owner’s role: a key a viewer
minted for the project works.
{"query": "how many vacation days do I get?", "top_k": 5, "filter": {"lang": "tr"}}
query is required. top_k is optional, 1 to 50; omitted or 0 uses the store’s
top_k. filter is optional and limits the search to documents whose metadata matches
(Metadata and filters); a filter outside the grammar, null
included, answers 400 invalid_request_error, and when no document matches the search
returns no hits without embedding the query (nothing is charged for it). The store’s search
mode, backend, rerank and distance settings apply; a request
cannot override them (the dashboard’s search endpoint can).
{"object": "retrieval", "mode": "hybrid", "backend": "pg_search", "reranked": false,
"rerank_backend": "", "rerank_fallback": false, "retrieval_latency_ms": 41, "rerank_latency_ms": null,
"hits": [{"chunk_id": 8, "document_id": 2, "content": "…", "score": 0.0325, "distance": 0.18,
"metadata": {"filename": "handbook.pdf", "section": "Leave > Vacation", "page": 12, "chunk_index": 3},
"document_metadata": {"lang": "tr", "product": "gateway"}}],
"usage": {"prompt_tokens": 7, "total_tokens": 7}}
hits is always an array, empty when nothing matched. metadata describes where the chunk
sits in its file; document_metadata is the document’s own filterable metadata ({} when it
has none). backend is the one that actually ran. usage counts the query’s embedding tokens, plus the tokens of the rerank call when
the store reranks with the LLM backend (that call goes to the project’s chat connection, so a
key with only retrieve can cause it; it is counted on the request row and against the
project’s limits, and priced at the rerank connection’s rate, not the embedding
connection’s; an API reranker is priced at its own connection’s price, Cohere by search
unit). A project without a RAG store answers
400 with code no_rag_store. The call is recorded with endpoint = retrieve,
rag_used, rag_hits, and the embedding connection’s model, tokens and price. An
embedding failure at the provider answers with the provider’s status as in chat.
A project’s pre_retrieval guardrails read query: a block rule answers 400 guardrail_blocked, a redact rule searches with the redacted query and sets a Warning.
POST /v1/rerank
Reorders documents by relevance to a query, in Cohere’s request and response shape, so a
Cohere SDK pointed at Ragmux works. Needs the key’s rerank scope.
{"model": "rerank-v3.5", "query": "vacation days", "top_n": 2,
"documents": ["Leave policy: 25 days.", "Parking rules.", {"text": "Sick leave: 10 days."}]}
query and a non-empty documents array (at most 1000; each entry a string or an object
with a text string) are required. top_n is optional and at least 1; omitted returns
every document. return_documents: true adds the document text to each result. model is
optional.
{"id": "5c1e…", "results": [{"index": 0, "relevance_score": 0.92}, {"index": 2, "relevance_score": 0.31}],
"meta": {"tokens": {"input_tokens": 42, "output_tokens": 0}}}
results holds at most top_n entries sorted by relevance_score, highest first;
index points into the request’s documents.
model resolves as for the other endpoints (ADR-018): a kind = rerank route
with exactly that name; else the implicit route, the project’s RAG store’s
rerank_connection_id, when model is empty or equals that connection’s model name; else
404 with code model_not_found. A store without a rerank_connection_id has no implicit
route. A route target or the implicit connection may be a cohere_rerank / voyage_rerank
connection (their scores are returned as the provider gives them) or a chat connection,
which is asked to rank the documents (at most 100 of them). With a chat model,
relevance_score is derived from the rank, not a model-reported number: the r documents
the model ranked get r/r (1.0) down to 1/r, and the others follow in their request
order with a score of 0. A model that answers with an empty list (“none is relevant”)
therefore yields every document at 0, not the client’s own order passed off as a ranking.
The call is recorded with endpoint = rerank: the connection’s model, the tokens the
provider reported (an estimate from the text, flagged estimated, when it reports none),
the price, and the usual limits and budgets apply. Rerank tokens spent inside a RAG chat or
/v1/retrieve request are added to that request’s own row instead. An API reranker
(cohere_rerank, voyage_rerank) has a token count that is optional in the response, so
the estimate (characters divided by 4, over the passages as sent: each is capped at 4000
characters) is a measure of usage for limits. Its cost follows its price row: Cohere by
search unit (a row with a per_search_unit never adds token prices), Voyage by token.
Inside a chat or retrieve request that cost is added to the row’s cost_micros, priced
with the rerank connection; the llm backend’s tokens are priced with the chat connection
that ran the rerank. A rerank connection with no price row adds 0.
POST /v1/moderations
The OpenAI moderation call, answered by the project’s own guardrails: no model is
called. Each input is read by the project’s pre_request rules (and the guardrail webhook, if
the project has one) and reported, never applied.
{"input": ["my id is 10000000146", "good morning"], "model": "omni-moderation-latest"}
input is a string or an array of at most 32 strings (an entry that is not a string, null included, is a 400); model is accepted and ignored.
{"id": "modr-3f9c0a7d5b1e4c2a8d6f0b13", "model": "ragmux-guardrails",
"results": [{"flagged": true, "categories": {"citizen-id": true, "card-words": false},
"category_scores": {"citizen-id": 1, "card-words": 0},
"ragmux": {"action": "redact"}},
{"flagged": false, "categories": {"citizen-id": false, "card-words": false},
"category_scores": {"citizen-id": 0, "card-words": 0}, "ragmux": {"action": "none"}}]}
Every pre_request rule is a category, its id the key; the score is 1 or 0. ragmux.action is
the strongest action among the rules that matched (none, flag, redact, block) and says what the
project’s rules would do; nothing is blocked or changed here. With the webhook on, its verdict is
one more category, webhook, on the inputs it concerns (it answers once for the whole call, so a
block or flag marks them all). The key needs the chat scope. The call takes a slot of the request
limit, costs no tokens, and leaves a request log row with endpoint = moderations. A webhook failure
answers as in chat (503 guardrail_unavailable under fail_closed).
A project without pre_request rules answers flagged: false with empty categories. An SDK that
reads categories as OpenAI’s fixed category set sees the project’s rule ids instead.
POST /v1/feedback
A score, and optionally a label, for a request the project already made. It collects a quality
signal without collecting content: the admin API shows the share of positive scores per project
(GET /projects/{id}/feedback/summary, under Projects), so a model, a route or a RAG setting can be
judged by what users said about it.
{"request_id": "3f2a9c1e", "score": 1, "label": "helpful"}
request_id is the X-Request-Id of the response being rated. score is 1 or -1.
label is optional: 1 to 64 characters of a-z 0-9 . _ : -. Any other field, free-text
comment included, is a 400 (invalid_feedback). The answer is 200 with
{"request_id": "3f2a9c1e", "score": 1, "label": "helpful"}.
- One feedback per request. Feedback is kept per
(project, request_id). Sending it again replaces the score and the label (the last one wins) and answers200. Arequest_ida client chose itself is not unique, so two requests that share one share their feedback too. - Which requests. The id must belong to a request log row of the key’s project. Any key of
the project may send it: the back end makes the call, a front end with a key of its own can
rate it. An id the project has no row for, and an id that belongs to another project, get the
same answer:
404{"error": {"type": "not_found_error", "code": "request_not_found", …}}. A call refused before its request log row is opened (401, a scope or project-selection403/400, a malformed body) has no row to rate; a429from a limit and a guardrail block do leave a row, so they can be rated. - Retry once on
404. The request log row is written after the response, for a JSON answer and for the end of a stream alike, so feedback sent the instant a response ends can arrive before the row exists. Retry it once after a short pause (a few hundred milliseconds). If the row could not be written at all, which the gateway only logs, the404stays. - Scope and limits. The key needs the
chator theretrievescope (403insufficient_scopeotherwise); there is no scope of its own. Feedback does not count against the project’s request or token limits, leaves no request log row and has no metric. The body is at most 4 KiB. - Retention. Feedback is deleted with the request logs, after
LOG_RETENTION_DAYS, counted from the day it was first received.
GET /v1/models and GET /v1/models/{id}
Return the project’s models in OpenAI’s shape so SDK model listings work:
{"object": "list", "data": [{"id": "claude-sonnet-4-5", "object": "model", "created": 1758190800, "owned_by": "anthropic"}]}
A project without chat routes lists its connection’s model, as above. When the project
has chat routes, the list holds each chat route’s name (owned_by: "ragmux") plus the
implicit route’s name, the default connection’s model name, unless a route already has
that name. With more than one entry, {id} has to match one of them (404 otherwise).
When the project has chat routes, POST /v1/chat/completions resolves model in this
order: an exact route name; the default connection’s model name (the implicit route); an
empty model (the implicit route). Anything else is 404
{"error": {"type": "invalid_request_error", "code": "model_not_found", "message": …}}.
The message repeats the requested value (cut to 128 characters) and does not list the
valid names. The response model is always the client’s value.
For a project without chat routes, with one project resolved, {id} is ignored and both
routes describe that project’s connection. A sk-user-… key that grants several projects and names none lists one entry
per granted project’s connection instead, deduplicated by model name; {id} then has to
match one of them (404 otherwise). Both routes need the key’s models scope.
MCP endpoint
POST /mcp serves the project’s RAG store to Model Context Protocol
clients as one tool, over Streamable HTTP. It is the same search as
POST /v1/retrieve: same key, same retrieve scope, same limits, same request
log row (endpoint = retrieve, one per tools/call). Neither the query nor the hits are logged.
Authentication. Authorization: Bearer <key> or x-api-key: <key>, a project key or a
sk-user-… key with the retrieve scope. The key and scope are checked on every request, the
handshake included. A key that grants several projects names one in X-Ragmux-Project, as for
chat. There is no OAuth: clients are configured with the key as a static header.
The tool. A project has one RAG store, so tools/list returns one tool, named search_ plus
the store’s name as a slug: lowercase, every character outside [a-z0-9_] becomes _, repeated
underscores merge, leading and trailing ones are trimmed, and the whole name is cut at 48
characters. A name that leaves nothing (one written entirely in non-ASCII characters) gives
search_store_<id>. Renaming the store renames the tool. A project without a store lists no
tools. The description carries the store’s name and document count.
| Argument | |
|---|---|
query |
Required. What to look for, up to 32 KiB. |
top_k |
Optional, 1 to 50. Omitted uses the store’s top_k. |
filter |
Optional metadata filter (grammar). null means no filter. |
The result is one text content item holding JSON, {"hits": [{"content", "score", "filename", "section", "page", "chunk_index", "document_id", "chunk_id", "document_metadata"}]}. The store’s
search mode, rerank and distance settings apply, as for /v1/retrieve. A bad argument (an unknown one included) or a failed
search (the embedding provider is down, say) comes back as a tool result with isError: true, so
the model can read it; a rerank or lexical backend that is unavailable falls back as it does for
chat.
Protocol. The server keeps no state: it mints no Mcp-Session-Id and ignores one a client
sends, so any replica can answer any request. Responses are application/json; no event stream is
opened. GET and DELETE answer 405. Each request is read on its own to decide which protocol
era it speaks:
initializeis legacy.- A request whose
params._meta["io.modelcontextprotocol/protocolVersion"]is set is modern (2026-07-28); itsMCP-Protocol-Versionheader must carry the same value. - Otherwise the
MCP-Protocol-Versionheader decides: a legacy version is legacy,2026-07-28without_metais a header mismatch, anything else is unsupported. - No header at all is
2025-03-26.
| Era | Versions | Methods |
|---|---|---|
| Modern | 2026-07-28 |
server/discover, tools/list, tools/call. Mcp-Method must equal the body’s method, and Mcp-Name the tool name on tools/call (a value sent as =?base64?…?= is decoded first). Every result carries "resultType": "complete"; server/discover names the server in _meta["io.modelcontextprotocol/serverInfo"]. |
| Legacy | 2025-11-25, 2025-06-18, 2025-03-26 |
initialize, notifications/initialized (202), ping, tools/list, tools/call. |
| Status | JSON-RPC code | When |
|---|---|---|
400 |
-32020 |
A modern request whose Mcp-Method, Mcp-Name or MCP-Protocol-Version is missing or differs from the body. |
400 |
-32022 |
An unsupported protocol version (for example 2024-11-05). error.data.supported lists the supported ones. |
404 |
-32601 |
A modern request for a method the server does not have. A legacy request gets the same error in a 200. |
405 |
GET, DELETE and any other method. |
|
400 |
-32700, -32600 |
Unparseable JSON, batches, a malformed envelope. |
200 |
-32602 |
tools/call for a tool the project does not have. |
Refusals. Authentication, scope, project and limit refusals keep the status /v1/retrieve
gives them (401, 403, 400 project_required, 429 with Retry-After), with the OpenAI error
body replaced by a JSON-RPC error. Those that happen before the request is read (key, scope,
project, Origin) have no id; a limit refusal of a tools/call carries the call’s id:
{"jsonrpc": "2.0", "error": {"code": -32001, "message": "api key is not authorised for retrieval",
"data": {"code": "insufficient_scope"}}}
data.code is the Ragmux code (invalid_api_key, key_revoked, insufficient_scope,
project_required, ip_not_allowed, origin_not_allowed, rate_limited, …). An unknown key’s message is fixed, as for /v1.
Origin. A request that carries an Origin header is checked against CORS_ORIGINS: one that
is not listed answers 403, an empty list refuses every request with an Origin, and * lets
every one through. A request without Origin, which is what non-browser MCP clients send, always
passes. The key’s own network allowlist is checked on top
of this, and a key that lists origins needs an Origin that matches one. For browser clients the preflight allows MCP-Protocol-Version, Mcp-Method and
Mcp-Name.
The endpoint and the supported protocol versions are part of the public contract frozen at v1.0.