Self-hosting
The agents backend is a single Go binary. Run it in your own cloud, point the SDKs at it, and nothing about an agent changes: the same agent.yaml syncs to it, the same sessions open on it, the same client SDKs talk to it. This page covers how to start it, the YAML it reads, how callers prove who they are, how to run a model on your own hardware behind it, and how to move the data you already have into it without a window where writes are lost.
What you run
| Piece | Why | Without it |
|---|---|---|
The router (acceleration/cmd/router) |
Serves the API, routes models, holds sessions | Nothing |
| A key encryption key | Seals the secrets the router stores: API key secrets, model keys, connector credentials. See Key encryption key | The router refuses to start in api_key mode |
| Postgres | Agents, conversations, keys, usage | The router routes but records nothing, and /health says so |
| Redis | Live provider health and the daily limits | Routing ignores which providers are struggling |
| A Stream app | Keeps every session that isn't incognito in Stream Chat: its history, reopening it, regenerate and edit | Only incognito sessions open |
| An object bucket | Recordings behind a voice of your own | Voices of your own are unavailable |
A self-hosted router needs a Stream app for any session that keeps its conversation. The router keeps no history of its own: a session that isn't incognito is kept in your Stream app's Chat, which is what lets a person see their history, reopen a conversation, regenerate a reply or edit a question. Set the app's key and secret as stream.api_key and stream.api_secret (STREAM_API_KEY, STREAM_API_SECRET). Without them, or with keys Stream refuses, such as placeholders, opening a session that isn't incognito answers 400 not_configured, naming those two variables and incognito: true. Without a Stream app, only incognito sessions work, and an incognito session can't be listed, reopened, regenerated, edited or forked.
Provider credentials stay in the environment, one variable per provider, and a provider whose credential is missing is skipped rather than fatal. So a router with only OPENAI_API_KEY set routes to OpenAI and to nothing else. A text session on a model of your own needs no provider key at all. A voice session still needs a hosted model for its flow controller, the model that decides when the agent speaks, so a voice agent needs at least one hosted provider's key.
With Docker Compose
The quickest way to see it running is the compose file in the repository, which starts Postgres, Redis, the router and a usage service. Compose reads the router's settings from a .env file at the root of the repository. Set the key encryption key, ROUTER_DEV_KEK, there once, before the first docker compose up:
git clone https://github.com/GetStream/Agents
cd Agents
echo "ROUTER_DEV_KEK=$(openssl rand -hex 32)" >> .env # once
echo "ROUTER_PUBLIC_URL=http://localhost:8080" >> .env
docker compose up --build -d
curl http://localhost:8080/healthWithout ROUTER_DEV_KEK the router container exits at start, while docker compose up -d still returns 0, so /health doesn't answer. docker compose logs router shows the reason and the variable to set. Keep that .env, and don't run the echo for the key again: a new ROUTER_DEV_KEK leaves every secret stored under the old one unreadable. ROUTER_PUBLIC_URL is where callers reach the router. For sessions that keep their conversation, add your Stream app's keys to the same file:
STREAM_API_KEY=your_stream_app_key
STREAM_API_SECRET=your_stream_app_secretThen mint the first API key inside the router's container. The router image's entrypoint is the router binary, so the command names it twice:
docker compose exec router router keys create \
--org "Acme" --app-name "Acme local" --key-name defaultIt prints the key and its secret once: see The first credential.
Compose runs the router with ROUTER_LIMITS_MODE=off. A new organization starts with no credit in compose's usage service, and every priced model a voice session opens, or a session on a hosted model, would otherwise be refused with 402 insufficient_credits. With off, usage is still priced and recorded; nothing is refused for money. Set ROUTER_LIMITS_MODE=enforce, or shadow to log what would be refused, in .env to test spend limits.
Every port is published on 127.0.0.1 only. ROUTER_PUBLISH_ADDRESS=0.0.0.0 in .env publishes the router on every address, for a phone on the same network.
compose.yaml names its project vision-agents and its router image vision-agents-router, whatever the directory is called. A second checkout, or volumes left by an earlier one, such as vision-agents_pgdata19, are reused as they are, and their secrets were sealed under that checkout's ROUTER_DEV_KEK, not yours. Give each checkout a project of its own with docker compose -p <name> ... on every command, or COMPOSE_PROJECT_NAME=<name> in its .env, or remove the old project's volumes with docker compose down -v there first. -p keeps volumes apart, not the fixed image tag or the host ports, so two checkouts still can't run at once.
The binary
On your own machines, the binary is enough. It builds with Go 1.27 or later, and runs its own migrations on start, so there is no separate step before the first boot. It needs a key encryption key in its environment:
go build -o router ./acceleration/cmd/router
# The YAML below names a Cloud KMS key, which unwraps this at start.
# On a laptop, set ROUTER_DEV_KEK instead and leave auth.kms_key out.
export ROUTER_AUTH_KEK_V1_WRAPPED=...
./router --config /etc/router.yamlTo make that wrapped key, encrypt a new key with the Cloud KMS key auth.kms_key names, using router-kek-v1 as additional authenticated data, and base64 the ciphertext:
openssl rand -hex 32 | tr -d '\n' > kek.txt
printf 'router-kek-v1' > aad.txt
gcloud kms encrypt --project acme --location europe-west1 \
--keyring agents --key router-kek \
--plaintext-file kek.txt --additional-authenticated-data-file aad.txt \
--ciphertext-file kek.enc
export ROUTER_AUTH_KEK_V1_WRAPPED=$(base64 < kek.enc | tr -d '\n')
rm kek.txtThe AAD names the version: a key wrapped for ROUTER_AUTH_KEK_V2_WRAPPED is encrypted with router-kek-v2. The router's service account needs permission to decrypt with the key.
On a laptop, the binary can run against compose's Postgres and Redis. Stop compose's router first, since both listen on port 8080, and give the binary the same ROUTER_DEV_KEK as .env, because the secrets in that database are sealed under it. With no --config, it reads the file built in for a laptop, which points at compose's Postgres and Redis:
docker compose stop router
export STREAM_API_KEY=your_stream_app_key STREAM_API_SECRET=your_stream_app_secret
export ROUTER_PUBLIC_URL=http://localhost:8080
ROUTER_DEV_KEK="$(grep '^ROUTER_DEV_KEK=' .env | cut -d= -f2-)" ROUTER_MODELS_PRIVATE_ENDPOINTS=true ./routerThe binary doesn't read .env: export what it needs from there yourself, such as your Stream app's STREAM_API_KEY and STREAM_API_SECRET and ROUTER_PUBLIC_URL, as above. The built-in file listens on :8080, every address of the machine, where compose publishes on 127.0.0.1 only. The binary's limits.mode defaults to enforce, and it has no usage service unless you set usage.url (ROUTER_USAGE_URL): without one it reads no credit balance, so enforce doesn't refuse a new organization for credit, and usage rows are written to Postgres and never shipped.
Your YAML
Everything that is not a provider credential is one YAML file, and --config says which:
addr: ":8080"
# Where callers reach you, which behind a load balancer is not where you listen.
# Telephony vendors fetch a call plan from it on answer.
public_url: https://agents.example.com
log_level: info
postgres:
dsn: postgres://agents:secret@db.internal:5432/agents?sslmode=require
redis:
addr: cache.internal:6379
username: agents
password: secret
auth:
mode: api_key
# The Cloud KMS key that unwraps ROUTER_AUTH_KEK_V<n>_WRAPPED at start. The key
# encryption key itself is never in this file, which refuses `kek`: see Key
# encryption key below.
kms_key: projects/acme/locations/europe-west1/keyRings/agents/cryptoKeys/router-kek
# Lets a model of your own be served from a private address or over plain http,
# such as vLLM on the next machine. Off by default. See Run a local model.
models:
private_endpoints: false
# Whether the router refuses work for money: enforce (the default), shadow or off.
limits:
mode: enforce
# CIDR ranges your own proxies sit in. Decides how much of X-Forwarded-For is
# believed. Empty means none of it is.
trusted_proxies:
- 10.0.0.0/8
# The default for what one end user may spend in a UTC day. An app sets its
# own with `quota` in its policy. A 0 is no default cap on that half, and an
# app's own `quota` still applies.
rate_limit:
messages_per_day: 200
tokens_per_day: 5000000
# How long recorded changes are kept while somebody is moving their data here.
data_move:
retention: 168h
# Your Stream app. Every session that isn't incognito is kept in its Chat, and
# its secret signs call events and the tokens a browser joins a call with.
# Without it only incognito sessions open. Leave it out rather than fill it with
# placeholders: Stream refuses those, and so every session that isn't incognito.
stream:
api_key: your_stream_key
api_secret: your_stream_secret
# Paths to capability files. Empty means the catalogue built into the binary.
routing_config: ""
phone_config: ""
voices_bucket_url: s3://voices?region=eu-west-1rate_limit is only the default. An app sets its own with quota: see Daily limits.
postgres.dsn and redis.addr are the two a self-hosted deployment always sets. An empty postgres.dsn is a router that records nothing, which is fine for a smoke test and not for anything else.
Three ways to choose the file, in the order they win:
| How | What it does |
|---|---|
--config /etc/router.yaml |
The file this deployment runs on |
ROUTER_CONFIG_FILE=/etc/router.yaml |
The same thing, for a chart that sets environment and not arguments |
ROUTER_ENV=local|testing|staging |
One of the files built into the binary, when you name no file of your own |
Saying nothing at all picks local, which points at the Postgres and Redis that the compose file starts.
Every setting also has the environment variable it has always had, and the variable wins over the file. ROUTER_POSTGRES_DSN, ROUTER_REDIS_ADDR, STREAM_API_SECRET and ROUTER_REDIS_PASSWORD are the ones worth using that way, because they are secrets and a file checked in beside your charts is not where a secret belongs. models.private_endpoints is ROUTER_MODELS_PRIVATE_ENDPOINTS, limits.mode is ROUTER_LIMITS_MODE and public_url is ROUTER_PUBLIC_URL.
Key encryption key
The router seals every secret it stores under a key encryption key: the secrets behind API keys, the api_key of a model of your own, connector credentials, Stream app keys and SIP trunk passwords. It never reads that key from the YAML file. There are two ways to give it one:
| Variables | Where | What it holds |
|---|---|---|
ROUTER_DEV_KEK |
A laptop, CI, compose | The key itself. Any non-empty string works; generate one with openssl rand -hex 32 |
ROUTER_AUTH_KEK_V<n>_WRAPPED, with auth.kms_key (ROUTER_AUTH_KMS_KEY) |
A production deployment | The key, encrypted by Google Cloud KMS with additional authenticated data router-kek-v<n>, in standard base64. auth.kms_key is the CryptoKey's resource name, and the router unwraps each key once at start with Application Default Credentials |
Today, Cloud KMS is the production path: there is no supported key source outside Google Cloud yet. ROUTER_DEV_KEK holds the key in the clear, which is why it is meant for a laptop and CI.
To rotate a wrapped key, add ROUTER_AUTH_KEK_V2_WRAPPED beside the first and set ROUTER_AUTH_KEK_VERSION=2. New secrets are sealed under version 2, and every version still set keeps opening the rows sealed under it. ROUTER_DEV_KEK is version 1 only.
The router refuses to start, naming the variable, when:
- the YAML holds
auth.kek, even empty, or the environment setsROUTER_AUTH_KEKor a plainROUTER_AUTH_KEK_V<n>. Both were retired; the error says which variable replaces it. ROUTER_DEV_KEKis set besideauth.kms_keyor a wrapped key.auth.modeisapi_keyand no key is set.
Keep the key: a different one leaves every secret already stored unreadable.
Authentication
auth.mode picks between four deployments:
| Mode | Who a caller is | Use it when |
|---|---|---|
api_key |
An API key, plus a token signed with the secret behind it. The default | The router is reachable by anything you did not write |
proxy |
Whatever the thing in front of the router already decided, read from headers it overwrites | You have a gateway that authenticates |
noauth |
The customer named in X-Customer-Id, taken at face value, and every caller is that customer's backend |
A laptop |
custom |
An authenticator you supply in code | You have an answer of your own |
The default verifies, on purpose. A default that trusts whatever reaches it is only correct when something else guarantees that nothing does, and that guarantee is a NetworkPolicy in one deployment and nothing at all in the next. api_key refuses to start without a database and a key encryption key, rather than refusing every request later.
noauth means the tenant is whatever the caller writes in a header. Anything that can open a TCP connection to the router is every customer on it. Keep it on a laptop.
The first credential
api_key mode cannot bootstrap itself over HTTP: every endpoint wants a key and there is nobody to issue the first one. A command run beside the database, with the same key encryption key as the router, can:
./router --config /etc/router.yaml keys create \
--org "Acme" --app-name "Acme production" --key-name defaultUnder compose, run it in the router's container: docker compose exec router router keys create --org "Acme" --app-name "Acme local" --key-name default.
organization 01JC...
app 01JC...
key vak_live_7f2b...
secret vas_live_9a41...
The secret is shown once. Set it where your SDK reads it and keep it out of the router's own config.The secret is printed and never logged or shown again. The app id it prints is the tenant: it is what every row is keyed by. If you are moving off another deployment, pass the app id you had there with --app-id, so the rows you import still belong to something:
./router --config /etc/router.yaml keys create --app-id 1234567 --key-name movedRunning it again for an app that exists adds a second key rather than refusing, which is how you rotate.
What a client gets
A client never holds the secret. Your server mints a token for the user, the client sends the key and that token, and the router treats it as a client: it may open and hold its own conversations, and everything that configures an agent answers it with a 403. That split is the same self-hosted as hosted.
Point your SDK at it
Server SDKs take the router's URL and a key and secret. Use the ones keys create printed, not your Stream app's.
Every one of them reads the same three variables, in the environment of your own server:
export STREAM_ACCELERATION_URL=https://agents.example.com
export STREAM_API_KEY=vak_live_7f2b...
export STREAM_API_SECRET=vas_live_9a41...Two different pairs share the names STREAM_API_KEY and STREAM_API_SECRET. The router's are your Stream app's key and secret, which keep its conversations in Stream Chat. Your SDK's are the vak_ key and vas_ secret that keys create printed. Never put the vak_ pair in the router's environment, or in the .env compose reads: the router would offer it to Stream as its Stream app, Stream would refuse it, and every session that isn't incognito would answer 400 not_configured.
Leave STREAM_ACCELERATION_AUTHENTICATE unset. It says the router is behind Stream's own authenticating proxy, which a deployment of yours is not.
The Go SDK is the exception: it reads these variables only for the proxy, and names a tenant with STREAM_ACCELERATION_CUSTOMER_ID otherwise. It names the tenant rather than carrying a key of its own, so it reaches a deployment running in proxy mode behind a gateway that authenticates, or in noauth mode on a laptop. api_key support is planned.
Or pass them in code:
import { Client } from "@stream-io/stream-agents";
const api = new Client({
url: "https://agents.example.com",
apiKey: "vak_live_7f2b...",
apiSecret: process.env.ROUTER_API_SECRET!,
});import os
from vision_agents.plugins import stream
api = stream.Client(
url="https://agents.example.com",
api_key="vak_live_7f2b...",
api_secret=os.environ["ROUTER_API_SECRET"],
)api = GetStream::VisionAgents::Client.new(
url: "https://agents.example.com",
api_key: "vak_live_7f2b...",
api_secret: ENV["ROUTER_API_SECRET"]
)$client = new Client(new Backend(
url: 'https://agents.example.com',
apiKey: 'vak_live_7f2b...',
apiSecret: getenv('ROUTER_API_SECRET'),
));api, err := stream.NewClient(stream.Backend{
URL: "https://agents.example.com",
CustomerID: "1234567",
})using var api = new VisionAgentsClient(new VisionAgentsOptions
{
Url = "https://agents.example.com",
ApiKey = "vak_live_7f2b...",
ApiSecret = Environment.GetEnvironmentVariable("ROUTER_API_SECRET"),
});let api = Client::new(ClientOptions {
url: Some("https://agents.example.com".into()),
api_key: Some("vak_live_7f2b...".into()),
api_secret: std::env::var("ROUTER_API_SECRET").ok(),
..Default::default()
})?;Client SDKs only need the URL and the credentials your server hands down. None of them holds a secret.
import { Client } from "@stream-io/stream-agents";
const api = new Client({
url: "https://agents.example.com",
apiKey: "vak_live_7f2b...",
token: async () => {
// Your server mints it: https://getstream.io/agents/docs/auth/#generating-a-token
const response = await fetch("/api/agent-token");
if (!response.ok) throw new Error(`token: ${response.status}`);
return response.text();
},
});A page on any origin may call the router and open a session socket, because every call carries the API key and a token: there is no list of allowed origins, and cors_origins (ROUTER_CORS_ORIGINS) is ignored if set. Only a router in noauth mode limits browsers, to pages served from localhost or a loopback address.
import { Client } from "@stream-io/stream-agents";
const api = new Client({
url: "https://agents.example.com",
apiKey: "vak_live_7f2b...",
token: async () => {
// Your server mints it: https://getstream.io/agents/docs/auth/#generating-a-token
const response = await fetch(
"https://your-app.example.com/api/agent-token",
);
if (!response.ok) throw new Error(`token: ${response.status}`);
return response.text();
},
});An app makes no CORS preflight, and the router has no list of allowed origins to add it to.
val agents = StreamAgents(url = "https://agents.example.com", apiKey = "vak_live_7f2b...")
agents.setUser(User(id = "alice"), token = tokenFromYourBackend)let agents = StreamAgents(apiKey: "vak_live_7f2b...", url: URL(string: "https://agents.example.com")!)
agents.setUser(User(id: "alice"), token: tokenFromYourBackend)final agents = StreamAgents(
url: Uri.parse('https://agents.example.com'),
apiKey: 'vak_live_7f2b...',
userId: 'alice',
token: () async => tokenFromYourBackend,
);Run a local model
A model on your own hardware, served by Ollama, llama.cpp, vLLM or any other OpenAI-compatible server, is a model of your own: register it once as custom/<name> and name it wherever an agent takes a model. A text session on it needs no hosted provider key.
Turn on models.private_endpoints first. By default the router only calls a model of your own at a public https address, so registering http://localhost:11434/v1 or http://10.0.0.7:8000/v1 is refused with 400 base_url must be a public https URL without userinfo, query or fragment. A local server is on a private address, usually over plain http, so a router that calls one needs:
models:
private_endpoints: trueor ROUTER_MODELS_PRIVATE_ENDPOINTS=true in its environment (in .env under compose). Turn it on only for a router no one else's apps share: it lets any app on the router point it at your network.
The built-in ollama provider is Ollama Cloud, and a *_BASE_URL variable such as TOGETHER_BASE_URL only moves a host's catalogue models to another address, still billed at that host's list price. Neither runs weights of your own: custom/ does. See Inference hardware and hosting.
Start the model server
Any one of these. The samples are sized for a laptop with no GPU, or Apple Silicon: a 3B model with an 8K context. With a GPU, a 7B or larger model and a longer context work the same way: change the model and the context length in the server's command and in the registration below. Note the context length the server runs the model with: you register it in a later step. For Ollama, that is OLLAMA_CONTEXT_LENGTH on the ollama serve process; if Ollama already runs as a service or desktop app, set it there and restart it.
# Ollama: an OpenAI-compatible API at http://localhost:11434/v1.
# serve stays in the foreground: pull in another terminal.
OLLAMA_CONTEXT_LENGTH=8192 ollama serve
ollama pull qwen2.5:3b
# llama.cpp: --jinja renders the model's own chat template, which tool calls need.
# Pick a port other than 8080, which the router listens on.
llama-server -hf Qwen/Qwen2.5-3B-Instruct-GGUF --jinja -c 8192 --port 8081
# vLLM, on a machine with a GPU
vllm serve Qwen/Qwen2.5-3B-Instruct --max-model-len 8192 \
--enable-auto-tool-choice --tool-call-parser hermesThe vLLM command was checked against vLLM's documentation and the router's code, but not run: no GPU was available when this page was written. Ollama and llama.cpp were run live. If a vLLM flag differs on your version, trust vLLM's own --help.
Which address the router uses for the server depends on where the router runs:
- The binary, on the same machine:
http://localhost:11434/v1(Ollama),http://localhost:8081/v1(llama.cpp above) orhttp://localhost:8000/v1(vLLM). - Compose with Docker Desktop: the router runs in a container, where
localhostis the container itself. It reaches your machine athost.docker.internal, such ashttp://host.docker.internal:11434/v1. - Compose on Linux: map
host.docker.internalto the host in acompose.override.yamlbesidecompose.yaml, which compose reads with it, and have the server listen on an address the container can reach (OLLAMA_HOST=0.0.0.0, or--host 0.0.0.0):
services:
router:
extra_hosts:
- "host.docker.internal:host-gateway"Registering a model only checks that its base_url is a URL the router may call, not that anything answers there, so a wrong host shows up on the first turn. Its error frame says only something went wrong for a refused connection or a name that doesn't resolve; the model_call frame beside it carries the cause in error_message, such as dial tcp: lookup host.docker.internal: no such host.
Allow private endpoints
Set ROUTER_MODELS_PRIVATE_ENDPOINTS=true as above and restart the router: docker compose up -d router under compose.
Register the model
Registering is server-side only: it takes the key keys create printed, Stream-Auth-Type: server, and a server token, an HS256 JWT signed with the key's secret that carries server: true, no user_id, and an exp. One way to mint one, with PyJWT. uv run --no-project --with pyjwt runs it without installing anything into your environment, and without syncing the repository's own Python workspace. Without uv, use a virtual environment: python3 -m venv .jwt && .jwt/bin/pip install pyjwt, then run .jwt/bin/python3 in place of uv run --no-project --with pyjwt python3. The unrelated package named jwt has no jwt.encode and breaks this line:
export ROUTER=http://localhost:8080
export API_KEY=vak_live_7f2b...
export API_SECRET=vas_live_9a41...
SERVER_TOKEN=$(uv run --no-project --with pyjwt python3 -c 'import jwt, os, time; print(jwt.encode({"server": True, "exp": int(time.time()) + 3600}, os.environ["API_SECRET"], algorithm="HS256"))')
AUTH=(-H "X-Api-Key: $API_KEY" -H "Stream-Auth-Type: server" -H "Authorization: Bearer $SERVER_TOKEN")
curl -sS -X POST "$ROUTER/v1/agents/models" "${AUTH[@]}" \
-H "Content-Type: application/json" \
-d '{
"name": "local-qwen",
"base_url": "http://host.docker.internal:11434/v1",
"model": "qwen2.5:3b",
"context_window": 8192,
"per_million_input_tokens": 0,
"per_million_output_tokens": 0,
"trains_on_data": "no",
"retention": "none"
}'This registers the Ollama server above, as a compose router on Docker Desktop reaches it. For llama.cpp, use "base_url": "http://host.docker.internal:8081/v1"; for vLLM, "base_url": "http://host.docker.internal:8000/v1" and "model": "Qwen/Qwen2.5-3B-Instruct", or localhost in place of host.docker.internal for a router run as a binary. The address is part of the registration: a model registered with host.docker.internal for compose fails under the binary, where that name usually doesn't resolve, and the other way round. When you move between the two, PUT /v1/agents/models/{id} each model with the whole registration and the other base_url; the id is in the answer to the POST, or in GET /v1/agents/models. A PUT that leaves api_key out keeps the stored one, and one that sends it empty removes it. model is the id the server serves the weights under: Ollama's tag, the Hugging Face id vLLM was started with, or for llama.cpp the id its /v1/models lists. context_window is the context the server actually runs the model with, not the most the model supports, because the router keeps its default reply cap inside it. Add api_key only if the server asks for one; without it, the router sends no Authorization header. The fields are described in Bring your own model.
Open a session on it
SESSION_ID=$(curl -sS -X POST "$ROUTER/v1/agents/sessions" "${AUTH[@]}" \
-H "Content-Type: application/json" \
-d '{
"llm": "custom/local-qwen",
"incognito": true,
"instructions": "Answer in one sentence. Use get_weather for weather questions.",
"tool_timeout_ms": 120000,
"tools": [{
"name": "get_weather",
"description": "Current weather for a city.",
"parameters": {
"type": "object",
"properties": { "city": { "type": "string" } },
"required": ["city"]
}
}]
}' | jq -r .id)llm names the conversation model for this session. model_overwrites: { "llm": ... }, which Sessions uses, does the same, and wins when both are sent. Each entry of tools is a tool the session's caller runs: name and description are required, and parameters is a JSON Schema object for its arguments. tool_timeout_ms is how long the model waits for a tool's result: 30 seconds when left out, which is little time to answer by hand. incognito: true is what a router without a Stream app needs. With your Stream app's keys set on the router, leave it out and the conversation is kept, with its history, regenerate and edit.
Chat over the events socket
The session's events socket carries the answer as it streams. Open it with the same three headers, here with websocat, and send a respond frame:
websocat "ws://localhost:8080/v1/agents/sessions/$SESSION_ID/events" \
-H="X-Api-Key: $API_KEY" -H="Stream-Auth-Type: server" \
-H="Authorization: Bearer $SERVER_TOKEN"websocat sends each line you type as one frame, so write each frame on one line:
{"type": "respond", "text": "What is the capital of France?"}
{"type": "respond", "text": "What is the weather in Lisbon?"}The second one asks for the weather, so the model calls get_weather.
The answer arrives as response_delta frames, each with the next piece of text, and ends with a responded whose pending_work is false. When the model calls a tool, a responded with pending_work: true comes first, then the tool_call, and the answer after the result ends with the responded whose pending_work is false.
A tool_call frame names the call in id, with its name and arguments. Answer it on the same socket, one frame per line:
{"type": "tool_result", "tool_call_id": "<that id>", "output": "12C, light rain"}To report that the tool failed, send error with what went wrong, which the model is told the call failed with. When a result carries both, error wins and output is dropped:
{"type": "tool_result", "tool_call_id": "<that id>", "error": "the weather service is down"}A frame that isn't JSON, such as one line of a pretty-printed object, makes the router close the socket with code 1008.
id is also read in place of tool_call_id, and a result that no call is waiting for, such as one already answered or timed out, gets a tool_result_ignored frame saying why.
The socket also sends responding, turn, model_call (each model request: provider, model, ttft_ms, duration_ms, success, and error_code and error_message when it failed), tool_started, tool_call.started, tool_ran, tool_call.finished, error and left, among others. When an error frame says only something went wrong, the model_call frame of the same turn has the cause in error_message. Sessions describes the frames you will use most, and the description of GET /v1/agents/sessions/{id}/events in the router's OpenAPI spec lists most of them; model_call isn't in it yet.
An incognito session records nothing, so its answers exist only on the events socket. POST /v1/agents/sessions/{id}/responses on one answers 202 with an empty id, and there are no items to read back afterwards. The server SDKs' session.events() reads the same socket; read an incognito session's replies there, not from a turn's items. See responses.create.
How the router talks to a model of your own
A custom/ model gets a request shaped for the strictest chat templates the weights ship with, and a few limits a hosted model doesn't need:
- Messages. One system message, first: later system notes, such as the date, are joined into the user turn before them. An assistant turn that calls tools always has
content, empty when the model said nothing. Tool-call ids are rewritten to 9 alphanumeric characters in what is sent, and the results that answer them carry the same ids. - First token within 60 seconds of the request. A server that never answers fails over to the next model in the router's list. One that sent its headers and then nothing fails the turn with an
errorframe, without failing over. - A default
max_tokenswhen the session sets none: 2048, or 6048 for a model whose family the router cannot switch thinking off for, since thinking counts against the cap, kept within the registeredcontext_windowafter the prompt. With less than 512 tokens of room, none is sent, and a server that refuses the cap as too large for the prompt is asked once more without it. Amax_tokensthe session sets is always sent as it is. - A
200that isn't a stream fails. An HTML page or a JSON body from a misconfigured server fails over to the next model rather than being recorded as an empty answer. - No
Authorizationheader when the model has noapi_key.
There are no per-model settings beyond the fields you register. Two models showed limits of their own in testing, which no request shape avoids:
| Model | Limit |
|---|---|
| Gemma 3 | Ollama refuses a turn that offers it tools, from the first turn: gemma3:1b does not support tools. Its Hugging Face chat template has no tool role either, so a server that renders it, such as vLLM, fails a turn after a tool result. Use it without tools |
| Llama 3.2 | Its chat template takes one tool call per turn. On Ollama, llama3.2:1b wrote a second call as JSON in its answer text, which reaches the person, rather than as a structured call |
Move your data here
Three endpoints move a tenant between two deployments, and all three are server-side only.
| Endpoint | What it does |
|---|---|
GET /v1/data/export |
Everything the calling app has, as one JSON object per line, ending with the cursor its changes carry on from |
POST /v1/data/import |
Writes an export, or a batch of changes, into this deployment |
GET /v1/data/changes?after=<cursor> |
What has happened to the app's rows since that cursor |
The customer is always the caller. Nothing in the request body or the query string can name a different one, so an export is your own data and an import lands under your own app however the file was edited on the way.
An export deliberately does not carry:
- API key secrets. Key rows are not exported at all. Mint new ones on the new deployment with
keys create. - Organizations and apps. Those are the account, and the new deployment has its own.
keys create --app-idis what puts the rows under the right one.
Everything else comes across: agent configs, router configs, conversations and their turns, knowledge, campaigns, phone numbers, usage. Voice recordings live in the object bucket rather than in Postgres, so the rows come across and copying the bucket is yours to do.
Switch over with no downtime
router replicate does both halves: the copy, and everything that happens after the copy. Run it on the new deployment, pointed at the old one.
Create the app and a key on the new deployment
Reuse the app id you have today:
./router --config /etc/router.yaml keys create --app-id 1234567 --key-name movedStart replicating
The copy is read at one moment; the changes carry on from exactly where it stopped:
./router --config /etc/router.yaml replicate \
--from https://accelerate-us-east4.gcp.stream-io-api.com \
--api-key vak_live_7f2b... --api-secret vas_live_9a41...It prints caught up at cursor N once it is following live, and keeps following until you stop it.
Point your SDKs at the new URL and deploy
Writes that were in flight against the old deployment are still being replayed.
Run it once more with --once
--once stops as soon as there is nothing left to catch up on, and you are moved.
Applying the same change twice lands where applying it once would, so a replay that overlaps the switchover is not a problem. The one thing that does not wait is data_move.retention, seven days by default: a move that takes longer than that starts again from a fresh export rather than resuming from a cursor the old deployment no longer honours, and asking for one returns 410.
Recording changes costs nothing until somebody is moving. The triggers return early unless an export has started, and they stop again on their own when nobody has read a page for the retention window.
Doing it by hand
The endpoints are plain HTTP, so a move is two curl commands if you would rather:
curl -sS https://old.example.com/v1/data/export \
-H "X-Api-Key: $OLD_KEY" -H "Stream-Auth-Type: server" \
-H "Authorization: Bearer $OLD_SERVER_TOKEN" > export.ndjson
curl -sS -X POST https://agents.example.com/v1/data/import \
-H "X-Api-Key: $NEW_KEY" -H "Stream-Auth-Type: server" \
-H "Authorization: Bearer $NEW_SERVER_TOKEN" \
--data-binary @export.ndjsonThe server token is an HS256 JWT signed with the key's secret, carrying server: true, no user_id, and an expiry. The last line of the export names the cursor: if it is missing, the stream was cut short and the file is not a complete export.
Who may move data
The three endpoints refuse three kinds of caller, and the refusals are worth knowing before you wonder why a request failed:
- A caller nobody authenticated gets a 401. There is no customer, so there is no data.
- A client gets a 403. A token your server minted for a user lets them hold a conversation, not walk off with the account.
- Every caller gets a 403 while the router runs in
noauthmode. There the customer is whatever the caller says it is, so serving an export would mean handing anybody anybody's data for the price of naming them.
Going further
The router README documents every provider credential and every setting in depth.