Skip to main content

AI Gateway (Psyche)

Psyche is an AI gateway. Your app, your users and your tools call one OpenAI-compatible endpoint, and Psyche sends each call to the right provider with your own provider keys, streams the answer back as it arrives, and records what every call used. It is one small static binary, written in Rust, at the path /ai/v1.

Psyche routes calls to models; it is not a model itself, and it never answers on its own.

In SnoutData Cloud you switch it on per project, on every plan (below); in the self-hosted stack it is the ai profile; and its source is at github.com/snoutdata/snout-psyche (Apache-2.0).

In SnoutData Cloud​

Each project can run its own Psyche, beside its database in the project's own pod, at https://<ref>.api.snoutdata.com/ai/v1. Its providers, models, keys, budgets and request log are tables in the project's database, in the psyche schema.

  1. Switch it on. In the dashboard, open the project and choose AI, then Turn on AI. It is ready in about a minute, and the database restarts once while it joins.
  2. Add a model. Add your first model opens a guide for where the model runs: Amazon Bedrock, Anthropic, OpenAI, OpenRouter, your own Ollama, or any server that speaks OpenAI's API, with that provider's own steps and links. Your key is checked with the provider before it is kept, stored in the project's database, and never shown again.
  3. Call it from a server or a tool with a key from the Keys card: it is the OpenAI API key, and the project's /ai/v1 address is the base URL.
  4. Call it from the browser once the project has two hard budgets, one for the whole project and one for each signed-in user (the Calling from your app card). Your users then call with their own access token as the Bearer token; the app key alone calls nothing.

A call to a paused project is refused, as any call is, until the project is resumed from the dashboard or the CLI.

Switching it off stops the server and keeps its tables, so turning it back on finds the models, keys and records where they were.

The same from a terminal, with the snoutdata CLI (0.18.0 or newer):

snoutdata ai enable
snoutdata ai models add --source openai --model gpt-4o-mini --stdin < openai.key
snoutdata ai budgets set project --amount 5
snoutdata ai budgets set users --amount 0.50
snoutdata ai test

What works today​

  • Routes and fallbacks. A route is one name for several models, tried in turn: the next is asked only when the one before failed for a reason that was not your request's (a rate limit, a provider error, no answer in time, a provider account refused or out of credit, a budget too small for that model). A provider error or a short rate limit is asked once more first; nothing is retried once the reply has started. Sort a route order (as written), price (the cheapest first), or latency or throughput (the fastest first, as measured; a model not measured yet goes first, so it gets measured). OpenRouter's models list works the same way on any request. The answer names the model that replied (x-psyche-model) and the route (x-psyche-route), and each try is its own row in the request log.

  • auto, and what a model can take. A model may say what it can take, in fits: its window in tokens, and whether it takes tools, images and a reply held to a JSON schema. Before a route, a fallback list or auto sends anything, it leaves out every model whose facts say it cannot take the request; when none can, the call is refused with each model's reason. Send "model": "auto" and Psyche chooses among the models that wrote fits, cheapest first, or as a route named auto says (its targets and its sort). auto:floor is always the cheapest first and auto:nitro always the fastest. No model decides: the same request under the same measurements goes the same way, and each log row's routing says the order tried and why any model was left out.

    curl -X PUT http://localhost:5300/ai/v1/admin/models/sonnet -H "Authorization: Bearer $SERVICE_KEY" \
    -d '{"provider": "anthropic", "upstream": "claude-sonnet-4-5",
    "fits": {"context": 200000, "tools": true, "images": true, "json_schema": true}}'
  • Health. Each model is measured from its own calls: time to the first byte, tokens a second, and the last five minutes of requests, failures and provider rate limits. Three failures in a row that were the model's (a provider error, no answer, no connection, a rate limit, a refused or empty account) cool it down: a route asks every other model first, while a call that names it alone still gets it, so a cooldown never fails a call by itself. After 10 seconds the next call to reach it is its probe; a failed probe doubles the cooldown, up to five minutes, and an answer brings it back. A provider's 429 with retry-after cools it for exactly that long. GET /ai/v1/admin/health (service key) lists every model's state, readings and what the provider says is left on its rate limits; with a database they are kept in psyche.provider_stats and read back at start. In the dashboard, a Cloud project's AI tab shows each model's last five minutes beside it in Models.

  • The OpenAI API. POST /ai/v1/chat/completions and POST /ai/v1/completions, streamed or not, POST /ai/v1/embeddings, and GET /ai/v1/models. Each is also served at /v1/..., for clients whose base URL ends in /v1, so the official OpenAI SDKs work by changing their base URL.

  • Any provider that speaks OpenAI's API: OpenAI, vLLM, Groq, Together, DeepSeek, LM Studio, Ollama's /v1. The request goes as you wrote it, with three changes: the model becomes the provider's own name for it, a streamed call asks the provider for usage so every call is counted (you get the usage chunk only if you asked for it), and prompt-caching breakpoints are removed for a model that does not take them.

  • Anthropic, through the same API. A chat request to an Anthropic model is translated to Anthropic's Messages API and the answer translated back, streamed or not: system messages, images, tools and tool results, tool_choice, stop, and usage with cache reads and writes counted. Anything with no Anthropic equivalent that would change the answer (n above 1, response_format, log probabilities, a field Psyche does not know) is refused with a 400 that names it, never dropped in silence.

  • Amazon Bedrock, through the same API, on Bedrock's Converse API, which every chat model there answers (Claude, OpenAI's models on Bedrock, Qwen and others). Requests are signed with AWS Signature Version 4 from an access key (with a session token for temporary credentials), or carry a Bedrock API key instead. A model id or an inference-profile ARN works as the upstream name. Throttling and "no capacity" come back as rate_limited. Embeddings from Amazon Titan and Cohere (v3 and v4) go through Bedrock's InvokeModel.

  • Reasoning. reasoning_effort is sent in the form each model takes, which its entry in the providers file names. The reply carries reasoning_content and thinking_blocks (signatures included); send thinking_blocks back on the assistant turn and they reach the model unchanged, which a tool loop with thinking on needs.

  • Prompt-caching breakpoints reach only a model that takes them. A cache_control breakpoint is sent to a model whose entry says "prompt_caching": true, and removed for every other model, which could otherwise refuse the whole request. Off unless written; Psyche never adds one.

  • Streams pass through as they arrive, never buffered. If the caller goes away, the provider's call is cancelled, so nobody pays for tokens no one reads.

  • Errors say whose fault they are. Your own bad request gets the provider's status (a 400); a provider rate-limiting gets 429 with its retry-after. Anything else the provider does wrong is a 503, and its code says which: provider_auth when the provider refused Psyche's credential (never passed on as if your key were wrong), provider_billing with no retry-after when the provider account has no credit or quota left, since waiting will not fix it, upstream_error when the provider failed, and timeout when it did not answer in time. A provider error that echoes the key Psyche sent never reaches you or the log.

  • Outbound calls are checked. By default Psyche connects only to public https addresses: no private ranges, no metadata service, no redirects. PSYCHE_EGRESS=private lifts that for a server beside your own model servers.

  • A request log in your own Postgres, below.

Callers authenticate as a Bearer token or an apikey header, with the project's service key (an HS256 JWT with role: service_role) or, when Psyche has a database, one of its own keys (below).

Run it yourself​

Build the image from the repository root and run it with a providers file:

git clone https://github.com/snoutdata/snout-psyche
cd snout-psyche
docker build -f Containerfile -t snout-psyche .

docker run -p 5300:5300 \
-e PSYCHE_JWT_SECRET='your project JWT secret, at least 32 characters' \
-e PSYCHE_PROVIDERS_FILE=/etc/psyche/providers.json \
-e OPENAI_API_KEY=sk-... \
-v "$PWD/providers.json:/etc/psyche/providers.json:ro" \
snout-psyche

Then point any OpenAI client at http://localhost:5300/ai/v1 with a service-role token as its key.

In the self-hosted stack (snout-stack 0.1.12 and later) it is the ai profile, on by default in a stack made from then on, at <API_EXTERNAL_URL>/ai/v1, with its tables in the project's database. AI_EGRESS=private in .env lets it reach an Ollama on the same machine or network.

Configuration​

Every setting is an environment variable. Nothing secret has a default: without its JWT secret, and without a providers file or a database to keep its providers in, the server refuses to start and says what is missing.

VariableDefaultSecretWhat it is
PSYCHE_JWT_SECRET(required)yesThe project's JWT secret, which callers' tokens are verified with. At least 32 characters.
PSYCHE_PROVIDERS_FILE(required without DATABASE_URL)noThe providers and models file (below). With a database it seeds the providers and models tables, and may be left out.
PSYCHE_ADDR0.0.0.0:5300noWhere the API listens.
PSYCHE_EGRESSpublicnopublic: https to public addresses only. private: anywhere, http included, for a server beside its own model servers.
PSYCHE_FIRST_BYTE_TIMEOUT_S300noHow long to wait for a provider's response to begin.
PSYCHE_IDLE_TIMEOUT_S120noThe longest silence allowed in the middle of a stream.
PSYCHE_TOTAL_TIMEOUT_S600noA whole non-streamed reply.
PSYCHE_MAX_REQUEST_MB32noThe largest request accepted (1 to 256).
DATABASE_URL(none)yesThe Postgres the request log is kept in (below). Without it no call is stored.
PSYCHE_LOG_RETENTION_DAYS30noDays of request rows kept (1 to 3650). The daily totals are kept for good.
PSYCHE_LOGinfonoLog filter, tracing syntax.
PSYCHE_LOG_FORMATtextnojson for one JSON object per line.
each provider's api_key_env(as named)yesThe provider's key, in the variable the providers file names.

The providers file​

The file holds no keys: each provider names the environment variable its key is in, so the file can be committed.

{
"providers": [
{"name": "openai", "kind": "openai", "base_url": "https://api.openai.com/v1",
"api_key_env": "OPENAI_API_KEY"},
{"name": "local", "kind": "openai", "base_url": "http://ollama:11434/v1"}
],
"models": [
{"name": "fast", "provider": "openai", "upstream": "gpt-4o-mini"},
{"name": "qwen2.5-coder", "provider": "local"}
]
}

kind is openai (OpenAI, or any server that speaks its API), anthropic (base URL https://api.anthropic.com/v1) or bedrock. A Bedrock provider names its region instead of a base URL, and either a Bedrock API key in api_key_env or AWS credentials, each part named by the variable that holds it:

{"name": "bedrock", "kind": "bedrock", "region": "us-west-2",
"aws": {"access_key_id_env": "AWS_ACCESS_KEY_ID", "secret_access_key_env": "AWS_SECRET_ACCESS_KEY",
"session_token_env": "AWS_SESSION_TOKEN"}}

A model's upstream is the provider's name for it (for Bedrock, the model id or inference profile) and defaults to name. A model may also say:

  • "prompt_caching": true, only for a model that takes cache breakpoints (Claude does; OpenAI's models on Bedrock cache by themselves and refuse a request that has one).
  • "reasoning": how it takes reasoning_effort, budget (Claude before Sonnet 5), adaptive (Claude Sonnet 5 and after) or effort (OpenAI's models on Bedrock). Without it, a request that asks for reasoning is refused rather than guessed at.
  • "embeddings": for a Bedrock embedding model, titan or cohere.
  • "max_output_tokens": the reply length asked for when the caller names none.

A mistake in the file (an unknown provider, a name used twice, a key variable that is not set, an http URL under public egress) stops the server at start, naming it.

The request log​

With DATABASE_URL set, Psyche makes a psyche schema in that database at start and keeps one row per call in psyche.requests: the operation, model, provider, how it ended (completed, cancelled, or failed with an error code), the tokens the provider reported, the time to first byte and the total time. Never a prompt or a reply. psyche.usage_daily holds each day's totals per operation, model and provider. Neither table is granted to any other role, and row-level security is on for both. Its migrations are recorded with a hash of each file, so a changed file is refused rather than run again.

No call waits for the database. A finished call is handed to a task of its own, which writes what it holds as one COPY every half second or every 1,000 rows, whichever comes first, with the day's totals in the same transaction. So a crash can lose only the rows that task held since its last write; a clean stop (SIGTERM) writes everything. If the database cannot be reached the rows are held and written once it can, up to 100,000; past that the oldest are dropped and the number is logged.

The rows are partitioned by day (UTC). Psyche makes the partitions from yesterday to two days ahead and drops those older than PSYCHE_LOG_RETENTION_DAYS, so an expired day is one DROP TABLE, never a long delete. Tested on Postgres 17.

Each finished call is also logged to the process's own output under the psyche::call target, with the same fields.

Prices​

Each log row carries what the call cost, in dollars, exact to a millionth of a millionth: the tokens the provider reported at the model's price. Give a model its price in the providers file, in dollars per million tokens as providers publish them:

{"name": "sonnet", "provider": "bedrock", "upstream": "us.anthropic.claude-sonnet-5-5",
"price": {"input": 2.2, "output": 11, "cache_read": 0.11, "cache_write": 2.75}}

cache_read and cache_write default to the input price, request adds a fee per call, and long_context ({"above": 272000, "input": ..., "output": ...}) is the second tier some models have. Without one, Psyche looks the model up in the price list it ships, which today holds the Amazon Bedrock models it has been run against, in us-west-2, from AWS's own price list (GPT-5.6 Luna, which that list does not carry, at the rate it is billed at in production). Prices differ by region and by inference profile (a us. profile costs 10% more than a global. one), so the list matches on both. A model priced by neither still works: its calls are logged with no cost, and Psyche names it in a warning at start.

Keys, budgets and rate limits​

With a database, the service key manages keys, budgets, rate limits and groups under /ai/v1/admin. Each is a table in the psyche schema, and a change made there by any means (this API or plain SQL) reaches Psyche at once: a trigger announces it and Psyche reloads.

Keys (/admin/keys): a psy_ key for a person, an app or an agent, optionally limited to some models and given an expiry. Only its hash is stored, so it is shown once, when it is made. A key sees only its models on /models, and each log row names the key that made it. The list shows when each key was made and when it was last used.

curl -X POST http://localhost:5300/ai/v1/admin/keys -H "Authorization: Bearer $SERVICE_KEY" \
-d '{"name": "ci", "models": ["sonnet"], "expires_in": 2592000}'

Budgets (/admin/budgets): what the project, one key, each signed-in user, one user or a group may spend in a day, a month (UTC), the last N days, or a month at a time from a day of your choosing ("period": "monthly" with "starts_on": a billing period that starts again on its own, on each anniversary of that day). Before a call is sent, its worst case (the prompt's size and the reply's cap, at the model's price) is reserved against every budget on it, and when it ends it is settled to what the provider reported. So calls in flight together cannot spend past a budget, and a long reply cannot run through one. A hard budget refuses with 429, the code budget_exceeded, a sentence saying how much is left, and scope: whose budget it was (project, key, user or group), so your app can tell its user's own budget from yours; a soft one lets the call through and names itself in x-psyche-budget-warning. A budget cannot be kept for a model with no price, so such a call is refused. In our test, 300 calls at once on a $0.001 budget: 18 answered, 282 refused, $0.000342 spent. The reservation is generous, so near its end a budget refuses some calls that would have fit.

curl -X POST http://localhost:5300/ai/v1/admin/budgets -H "Authorization: Bearer $SERVICE_KEY" \
-d '{"name": "ci daily", "amount": 5, "period": "day", "key_id": "<key id>"}'

Rate limits (/admin/limits): requests and tokens a minute, for any of the same. Over a limit, a call gets 429 with the code rate_limit_exceeded, its scope as for a budget, and a retry-after; every response to a limited call carries OpenAI's x-ratelimit-* headers.

curl -X POST http://localhost:5300/ai/v1/admin/limits -H "Authorization: Bearer $SERVICE_KEY" \
-d '{"name": "ci", "key_id": "<key id>", "requests_per_minute": 60}'

Under a hard budget a reply always has a cap. When a call names no max_tokens (and the model has no max_output_tokens), Psyche sends 4,096, or less when that is all the budget has room for, down to 256, below which the call is refused. One thing a budget does not catch, stated rather than hidden: the rows a crash did not write are not counted after a restart.

Providers and models in your database​

With a database, your providers and models are rows of psyche.providers and psyche.models, and those rows are what Psyche serves. A providers file, if you keep one, is written into them at each start. Add and change them with the service key, or in SQL, and the change is served at once:

curl -X PUT http://localhost:5300/ai/v1/admin/providers/openai -H "Authorization: Bearer $SERVICE_KEY" \
-d '{"kind": "openai", "base_url": "https://api.openai.com/v1", "credential": "openai"}'
curl -X PUT http://localhost:5300/ai/v1/admin/models/fast -H "Authorization: Bearer $SERVICE_KEY" \
-d '{"provider": "openai", "upstream": "gpt-4o-mini", "price": {"input": 0.15, "output": 0.6}}'

To pick a model rather than know its id, ask the provider for its own list, with the credential its calls use; the POST form takes a provider and key that are not saved yet and keeps neither:

curl http://localhost:5300/ai/v1/admin/providers/openai/upstream-models -H "Authorization: Bearer $SERVICE_KEY"
# {"object": "list", "data": [{"id": "gpt-5-mini", "owned_by": "system", "created": 1754425777, "kind": "chat"}, …]}
curl -X POST http://localhost:5300/ai/v1/admin/upstream-models -H "Authorization: Bearer $SERVICE_KEY" \
-d '{"provider": {"kind": "openai", "base_url": "https://api.openai.com/v1"}, "credential": {"api_key": "sk-…"}}'

Each entry is the provider's id, with name, owned_by, created, kind (chat, embedding or completion) and context_window when known, chat models first and newest first. It covers every OpenAI-style provider (GET {base}/models), Anthropic, and Bedrock (its inference profiles, such as us.openai.gpt-5.6-luna, and the models it serves on demand). A provider that refuses or has no list answers an error with a sentence, and the key never appears in it.

A model takes the same fields as in the file, plus "enabled": false to stop serving it, and its name may contain /. A model that could not be served is refused with the reason, and nothing is stored. GET /ai/v1/admin/models shows the price each model is charged at and where it comes from. A provider may take "auth_header", the header its key is sent in instead of a Bearer token. That is for a model server behind a gate that checks a header of its own, such as an Ollama on another machine reached through a tunnel, with a firewall rule refusing any request that does not carry the secret:

curl -X PUT http://localhost:5300/ai/v1/admin/providers/home-ollama -H "Authorization: Bearer $SERVICE_KEY" \
-d '{"kind": "openai", "base_url": "https://ollama.example.com/v1", "credential": "home-ollama", "auth_header": "x-gate-key"}'

A provider from the providers file stays the file's, because its key may come from Psyche's environment: the admin API will not change it. A model from the file can be edited (its price, its limits, whether it is served), and the file then leaves your edit alone.

Credits and model access​

A signed-in user can have credits (psyche.credits), which pay for a call only when their own budgets are full, never past the project's; the log marks each call credits paid. A model can be limited to the users and groups granted it ("access": "granted" and psyche.model_grants); anyone else is refused it and does not see it in /ai/v1/models. The service key grants a model with POST /ai/v1/admin/grants and {"model": "…", "user_id": "…"} (or "group_id"), lists the grants with GET /ai/v1/admin/grants?model=…, and takes one back with DELETE /ai/v1/admin/grants/<id>. The dashboard and Studio do the same from a model's editor.

Stored credentials​

With a database, a provider can name a stored credential ("credential": "openai") instead of the environment variable its key is in (in the file, or on a provider you made through the admin API), and the service key sets it with PUT /ai/v1/admin/credentials/openai and {"api_key": "…"} (or AWS credentials for Bedrock). Psyche checks it against the provider first, with a request that spends no tokens, and stores it only if the provider takes it. The next call uses it, with no restart. A stored credential is never shown again: lists give its kind, a fingerprint and its last four characters, and only Psyche's own database role can read the table.

Calling from the browser​

Your app's signed-in users can call models directly: the anon key as apikey and the user's own access token as the Bearer token, the way the data API takes them, with no backend of yours in between. Since anyone can reach that door, Psyche takes no such call until the project has a hard budget of its own and a hard budget for every user, and until then it refuses with a sentence saying which is missing. The anon key alone calls nothing.

curl -X POST http://localhost:5300/ai/v1/admin/budgets -H "Authorization: Bearer $SERVICE_KEY" \
-d '{"name": "each user", "amount": 0.50, "period": "day", "every_user": true}'

A budget or limit with "every_user": true gives each user one of their own; one naming a user_id replaces it for that user. A group (/admin/groups, and PUT /admin/members/<user id> with a group_id) is a team inside your app whose members share one budget. A key with an owner counts against that user's budgets and limits too.

Each user can read their own usage through RLS: their keys (never the hash), calls, daily totals, group, and the budgets and limits that apply to them, so "your AI usage" is a query from the app.

From JavaScript, @snoutdata/client (0.5.0 and later) does this for you: db.ai sends the signed-in user's token.

const { data, error } = await db.ai.chat({ model: 'chat', messages: [{ role: 'user', content: 'Hello' }] })

const { data: chunks } = await db.ai.stream({ model: 'chat', messages })
for await (const chunk of chunks) {
// each chunk is OpenAI's; the last one carries the usage
}

db.ai.models() lists what the user may call, and db.ai.embed() makes embeddings. A refusal is error, with Psyche's own sentence, its code (budget_exceeded, model_not_found) and the status.

What is coming​

  • More routing: spreading across accounts by their remaining quota, keeping a conversation on the one holding its prompt cache, and a balanced policy for auto.
  • The Anthropic Messages API in, at /ai/v1/messages, so tools that speak Anthropic's API can use it too.
  • More of it in the dashboard: routes and a playground, and the same screens in Studio.

The source and its own README are at github.com/snoutdata/snout-psyche.