Skip to main content

Auto router API

This page documents the 6 gateway endpoints tagged auto router in the gateway's OpenAPI document. Every example targets a gateway on http://localhost:4000 and authenticates with the SPANWAY_API_KEY environment variable, which holds the master key or a virtual key that has access to the route. Request and response fields are taken from the schema the running gateway publishes at /openapi.json, and the same document is bundled with this site as openapi.json.

MethodPathSummary
GET/auto_router/benchmarksAuto router usage and savings over a date range
GET/auto_router/sessionSpend and last model of one auto routed session
POST/auto_router/shadow_eval/startStart a shadow eval of an auto router
GET/auto_router/shadow_evalList shadow eval jobs
GET/auto_router/shadow_eval/{job_id}Read one shadow eval job with its results
POST/auto_router/shadow_eval/{job_id}/stopStop a running shadow eval

Endpoints​

GET /auto_router/benchmarks​

Auto router usage and savings over a date range

How much the auto routers saved and how they behaved over a date range, for the Auto-Router tab of the Cost Optimization page. Proxy admins and admin viewers only.

The answer has the savings against each router's baseline model, how long sessions ran and how well prompt caching worked for each kind of routing decision. Money counts only requests on the chosen UTC days, and the savings total matches the Overall tab. Session shape and caching cover every session that overlaps the range. Send api_key (a key's token hash) or user_id to see one key or one internal user, and note that turns recorded before user attribution existed only show up under their key. Every configured router appears, with zeros until it serves traffic, and routers_in_scope counts those too. The data comes from a rollup written as each request is billed, so the route stays fast on a busy gateway.

Parameters:

NameInTypeRequiredDescription
start_datequerystring or nullNoYYYY-MM-DD UTC, inclusive (defaults to 30 days before end_date)
end_datequerystring or nullNoYYYY-MM-DD UTC, inclusive (defaults to today)
api_keyquerystring or nullNoFilter to one virtual key token hash
user_idquerystring or nullNoFilter to one canonical internal user recorded on each turn

Example request:

curl -X GET "http://localhost:4000/auto_router/benchmarks" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200Totals for the window and one group per configured auto router.application/json AutoRouterBenchmarksResponse
400end_date must not be earlier than start_date or Invalid date format: 2026-13-01. Expected: 'YYYY-MM-DD'application/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403Only proxy admin roles can view auto-router benchmarks across the deploymentapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500DB not connected. This endpoint needs a database; set DATABASE_URL to a PostgreSQL connection string (postgresql://...) to enable it. See https://docs.spanway.ai/docs/proxy/virtual_keysapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
start_datestringYesWindow start day, YYYY-MM-DD UTC, inclusive
end_datestringYesWindow end day, YYYY-MM-DD UTC, inclusive
routers_in_scopeintegerYesHow many groups this response carries. Every auto-router configured on the proxy counts, whether or not it served anything in the window. To count only the routers that did serve traffic, filter groups to the entries w
totalsAutoRouterBenchmarkTotalsYesAuto-routed traffic in the window. Turns, spend and savings count requests on the selected UTC days;
groupsarray of AutoRouterBenchmarkGroupYesOne entry per auto-router, listed from the model registry rather than from the rollup, so a router appears as soon as it is configured and reads zero until it serves traffic. Semantic auto-routers are absent: they record

GET /auto_router/session​

Spend and last model of one auto routed session

One auto-routed session, for the key that ran it: the model its last turn was routed to and the session's spend against the router's savings baseline. Built for a coding agent's status line or stop hook, so any virtual key may call it and only ever sees rows written under its own key hash. Reads the Spanway_AutoRouterSession rollup, which the asynchronous spend flush fills a moment after each turn; a session with no flushed auto-routed turn yet is a 404. The id is bounded the way the writer bounded it, so an oversized client id still finds its row.

Parameters:

NameInTypeRequiredDescription
session_idquerystringYesThe client session id (x-*-session-id header) the turns were sent under

Example request:

curl -X GET "http://localhost:4000/auto_router/session?session_id=session_id-123" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200The session rollup for the calling key.application/json AutoRouterSessionResponse
401No valid key or Admin UI session was presentedapplication/json ProxyError
404No auto-routed turns recorded for session 'claude-code-4f1a' under this keyapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500DB not connected. This endpoint needs a database; set DATABASE_URL to a PostgreSQL connection string (postgresql://...) to enable it. See https://docs.spanway.ai/docs/proxy/virtual_keysapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
session_idstringYesSession Id
router_namestringYesThe auto-router alias the session's requests were sent to
router_typestringYescomplexity, adaptive or quality
turnsintegerYesAuto-routed turns the rollup has recorded for this session so far
last_modelstringYesThe deployment model the most recent turn was routed to
spendnumberYesWhat the session's routed traffic actually cost, classifier calls included
savings_estimated_turnsintegerYesRequests whose savings estimate recorded its baseline cost
savings_estimated_actual_spendnumberYesActual spend, including classifier cost, for requests whose estimate recorded its baseline cost
saved_spendnumber or nullYesRecorded historical savings plus newer estimates, net of classifier cost
baseline_spendnumber or nullYesEstimated single-model cost: spend plus recorded savings
savings_estimated_baseline_spendnumber or nullYesEstimated single-model cost for requests whose estimate recorded its baseline cost
baseline_modelstring or nullYesThe savings baseline recorded by most session turns, including historical turns, recorded turn by turn, so it still names the counterfactual after the router is reconfigured or removed. None when no turn recorded one: ro
baseline_modelsobjectYesSession turns recording each baseline model; more than one entry means the router's baseline changed mid-session; these counts do not imply savings coverage

POST /auto_router/shadow_eval/start​

Start a shadow eval of an auto router

Start a shadow eval: duplicate a sampled slice of one or more targets' live traffic against a second arm, judge the two responses blind, and stratify win rates by tier, by the model that served the real arm, and by target.

A target is a virtual key, a team, or a user. Team and user targets match on the identity every request resolves to at auth time, so they cover JWT-authenticated traffic, which presents no virtual key; a user target samples that user's traffic across all their teams, whether it arrives on a JWT or a key they own. models narrows every target to requests for those model groups, so a user plus one model samples that user's traffic on that model across every key they own; it is forward-only, since a reverse job already samples exactly the traffic its own router served.

A forward job answers whether the targets should adopt router_name: it samples the requests the router did not serve and duplicates them through it. A reverse job answers whether a target already on the router still gains from it: it samples the requests the router did serve and duplicates them against baseline_model. A target can hold one active job per direction, so both questions can run at once, and a request matching several jobs' targets (say its key and its team) is sampled by each, separately budgeted.

Shadow responses are never served to users. Each target samples until its recorded eval spend, the shadow and judge calls' own cost, reaches max_budget dollars, the job's window ends, or the job is stopped, so one target running out of budget does not end sampling for the others; sampling changes propagate to pods within about 10 seconds. Shadow and judge calls bill to the sampled request's own identity but are excluded from request counts and auto-router adoption metrics.

Request body (application/json, schema StartShadowEvalRequest):

FieldTypeRequiredDescription
api_key_idsarray of stringNoHashed virtual keys whose traffic will be shadowed. Combined with team_ids and user_ids the job needs at least one target and at most 100, which also bounds every read the job's endpoints make. Each target carries its ow
team_idsarray of stringNoTeams whose traffic will be shadowed, matched on the team every authenticated request resolves to, so a team's JWT-auth and virtual-key traffic are both sampled
user_idsarray of stringNoUsers whose traffic will be shadowed, matched on the user every authenticated request resolves to across all their teams: JWT requests carrying their subject claim and virtual keys they own
modelsarray of stringNoModel groups to narrow the sampled traffic to, matched on the group the caller requested and resolved through model_group_alias, so an alias and its target are one name. Empty samples every model the targets use. This AN
router_namestring or nullNoThe auto-router under evaluation, in either direction: the single-router spelling of router_names. Provide exactly one of the two fields
router_namesarray of stringNoThe auto-routers under evaluation, at most 4. Every sampled request runs through every router listed and each arm is judged independently against the same real response, so routers compare head-to-head on identical traff
directionenum: "forward", "reverse"Noforward answers 'should this key adopt router_name': it samples the requests the key did NOT route through the router and duplicates them through it. reverse answers 'is the router still worth it for a key already on it'
baseline_modelstring or nullNoRequired when direction is reverse and rejected otherwise: the fixed model the router's own responses are judged against. Must be a plain model rather than another auto-router
shadow_percentagenumberYesPercentage of each target's requests to duplicate through the router
judge_modelstringNoModel used to blindly judge real vs. shadow responses. The judge only compares two answers, so a mid-tier model (Claude Sonnet or GPT-4o class) is the sweet spot: small/nano-class models produce unreliable or malformed v
duration_daysintegerNoHow many days the job samples traffic before completing on its own
max_budgetnumberNoPer-target USD budget for the eval's own overhead, the shadow-arm and judge calls, priced with the same figures the spend pipeline bills. EACH scoped target samples until its recorded eval spend reaches this, so a job ov

Example request:

curl -X POST "http://localhost:4000/auto_router/shadow_eval/start" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"team_ids": [
"team-platform"
],
"router_names": [
"smart"
],
"direction": "forward",
"shadow_percentage": 10,
"judge_model": "claude-sonnet-5-5",
"duration_days": 7,
"max_budget": 25
}'

Responses:

StatusDescriptionBody
201The new job with its targets.application/json ShadowEvalJobResponse
400Not a configured auto-router: 'smart' or team_ids not on this proxy: team-unknown or judge_model 'smart' is an auto-router; it must be a plain model or judge_model 'claude-judge' is neither a model configured on this proxy nor a provider-qualified public model name (e.g. 'anthropic/claude-sonnet-5') or judge_model 'anthropic/claude-sonnet-5' uses the Spanway SDK but required credentials are not configured: ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN or models not served by this proxy: 'gpt-unknown' or judge_model 'claude-sonnet-5-5' is also an arm this job would judge: tier model 'claude-sonnet-5-5'. A judge scores its own answers higher than a rival's, so the win rates would measure the judge; pick a judge that serves neither armapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403Only a proxy admin can start a shadow evalapplication/json ErrorDetail
409Already in an active forward shadow eval job: team team-platform (job 7c1f2a90-5e3b-4d8a-9b61-2f0e8c4a1d77). Stop it first. or A requested target was claimed by another forward shadow eval job concurrently. Stop it first.application/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500DB not connected. This endpoint needs a database; set DATABASE_URL to a PostgreSQL connection string (postgresql://...) to enable it. See https://docs.spanway.ai/docs/proxy/virtual_keysapplication/json ErrorDetail

GET /auto_router/shadow_eval​

List shadow eval jobs

List shadow eval jobs, newest first, each target with its attempt count so status is accurate. Judged counts, spend, and results ride the detail endpoint only.

Parameters:

NameInTypeRequiredDescription
target_typequeryenum: "key", "team", "user" or nullNoKind of target to filter on; requires target_id
target_idquerystring or nullNoFilter to jobs that shadow this target, alone or alongside others
limitqueryintegerNoNewest jobs to return

Example request:

curl -X GET "http://localhost:4000/auto_router/shadow_eval" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200Jobs newest first, without results.application/json array of ShadowEvalJobResponse
400target_type and target_id filter together; pass both or neitherapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403Only proxy admin roles can view shadow evalsapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500DB not connected. This endpoint needs a database; set DATABASE_URL to a PostgreSQL connection string (postgresql://...) to enable it. See https://docs.spanway.ai/docs/proxy/virtual_keysapplication/json ErrorDetail

GET /auto_router/shadow_eval/{job_id}​

Read one shadow eval job with its results

Shows one shadow eval job with how many turns were judged, what the judge cost, the latest error, and the win rates by tier, model and router, so an operator can decide whether to switch traffic to the auto router. Nothing changes.

Parameters:

NameInTypeRequiredDescription
job_idpathstringYes

Example request:

curl -X GET "http://localhost:4000/auto_router/shadow_eval/job_id-123" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200The job with derived counts, judge spend, the latest error and stratified verdicts.application/json ShadowEvalJobResponse
401No valid key or Admin UI session was presentedapplication/json ProxyError
403Only proxy admin roles can view shadow evalsapplication/json ErrorDetail
404No shadow eval job 7c1f2a90-5e3b-4d8a-9b61-2f0e8c4a1d77application/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500DB not connected. This endpoint needs a database; set DATABASE_URL to a PostgreSQL connection string (postgresql://...) to enable it. See https://docs.spanway.ai/docs/proxy/virtual_keysapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
job_idstringYesJob Id
targetsarray of ShadowEvalJobTargetResponseYesThe targets whose traffic this job evaluates, and only theirs, each with its own budget
router_namesarray of stringYesEvery auto-router this job runs as a shadow arm. Multi-router jobs sample one slice of traffic and judge every arm against the same real responses
modelsarray of stringNoModel groups the sampled traffic is narrowed to; empty means every model the targets use
directionenum: "forward", "reverse"NoDirection
baseline_modelstring or nullNoBaseline Model
judge_modelstringYesJudge Model
shadow_percentagenumberYesShadow Percentage
created_atstringYesCreated At
ends_atstringYesEnds At
stopped_bystring or nullNoThe operator who stopped the job early, recorded by the stop endpoint; 'unknown' backfilled by migration for jobs that displayed stopped when the column arrived; None when the job ended on its own. Its presence is what m
judged_countinteger or nullNoVerdicts recorded; detail endpoint only
error_countinteger or nullNoSampled attempts that errored; detail endpoint only
judge_spendnumber or nullNoJudge cost so far; detail endpoint only
last_errorstring or nullNoMost recent attempt error; detail endpoint only
resultsAutoRouterShadowEvalResult or nullNoStratified verdicts; detail endpoint only
router_namestringYesThe first router, kept for callers that predate router_names; derived so the
statusenum: "running", "completed", "stopped"YesThree recorded facts, no history-guessing: a stop is stopped_by (the migration

POST /auto_router/shadow_eval/{job_id}/stop​

Stop a running shadow eval

Stop an active shadow eval job, every target it scopes at once. Attempts are kept; sampling halts within ~10s. Targets that already stopped on their own budget keep the stopped_at they earned. The statement is the whole state machine: it claims the job only while a leg still samples inside the window with no stop recorded, so a racing operator, a same-instant budget spend, and a repeat stop all read the same 400 with the status the job actually holds.

Parameters:

NameInTypeRequiredDescription
job_idpathstringYes

Request body (application/json, object):

Example request:

curl -X POST "http://localhost:4000/auto_router/shadow_eval/job_id-123/stop" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{}'

Responses:

StatusDescriptionBody
200The job as it stands after the stop.application/json ShadowEvalJobResponse
400Job 7c1f2a90-5e3b-4d8a-9b61-2f0e8c4a1d77 is already stoppedapplication/json ErrorDetail
401No valid key or Admin UI session was presentedapplication/json ProxyError
403Only a proxy admin can stop a shadow evalapplication/json ErrorDetail
404No shadow eval job 7c1f2a90-5e3b-4d8a-9b61-2f0e8c4a1d77application/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
500DB not connected. This endpoint needs a database; set DATABASE_URL to a PostgreSQL connection string (postgresql://...) to enable it. See https://docs.spanway.ai/docs/proxy/virtual_keysapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
job_idstringYesJob Id
targetsarray of ShadowEvalJobTargetResponseYesThe targets whose traffic this job evaluates, and only theirs, each with its own budget
router_namesarray of stringYesEvery auto-router this job runs as a shadow arm. Multi-router jobs sample one slice of traffic and judge every arm against the same real responses
modelsarray of stringNoModel groups the sampled traffic is narrowed to; empty means every model the targets use
directionenum: "forward", "reverse"NoDirection
baseline_modelstring or nullNoBaseline Model
judge_modelstringYesJudge Model
shadow_percentagenumberYesShadow Percentage
created_atstringYesCreated At
ends_atstringYesEnds At
stopped_bystring or nullNoThe operator who stopped the job early, recorded by the stop endpoint; 'unknown' backfilled by migration for jobs that displayed stopped when the column arrived; None when the job ended on its own. Its presence is what m
judged_countinteger or nullNoVerdicts recorded; detail endpoint only
error_countinteger or nullNoSampled attempts that errored; detail endpoint only
judge_spendnumber or nullNoJudge cost so far; detail endpoint only
last_errorstring or nullNoMost recent attempt error; detail endpoint only
resultsAutoRouterShadowEvalResult or nullNoStratified verdicts; detail endpoint only
router_namestringYesThe first router, kept for callers that predate router_names; derived so the
statusenum: "running", "completed", "stopped"YesThree recorded facts, no history-guessing: a stop is stopped_by (the migration