Evals and red teaming
Evals answer the question "which model should serve this workload" with evidence instead of a guess. You define a dataset of inputs with optional expected outputs and context, pick the models to compare, pick a scorer, and the gateway runs every item through every model, scores each answer, and reports pass rate, mean score, latency and cost per model. Red teaming turns the same machinery against a single model to find the vulnerabilities an attacker would exploit. Both are enterprise features, and every /eval route returns 403 without a license.
Every model call an eval makes goes through the gateway's own router as the caller, so it is logged and cost-tracked like any other request. That covers runs started from the Admin UI or the API, scheduled runs, runs started by a CI key, the playground, judge calls and the judges of online scoring. Before each call the caller's key budget and team budget are checked, and a call over either is recorded as an error instead of being sent. The call is then prepared the way the gateway prepares a request, so the guardrails attached to the key, the team and the gateway apply, the rate limits and parallel request limits of the key apply, and output guardrails check the answer. A guardrail that blocks an item's input or the model's answer records that item as an error that says it was blocked by a guardrail, and the run carries on with the other items. Scheduled runs act as the admin who created the schedule and online judges as the admin who created the rule, so their own key and team budgets apply. Judge models and attack simulators are gateway models too. Nothing leaves your deployment except the provider calls you already allow.
A real-world scenario
A product team plans to move a support assistant to a newer model. Before they switch, they want proof that refund answers do not get worse. They build a dataset from last week's refund conversations, run it against the current and the candidate model with a judged rubric, compare the two runs item by item, and schedule the same run every night so a later prompt change that breaks refunds raises an alert.
Steps
-
In the Admin UI open Evals under Developer Tools. On the Datasets tab click From logs, filter on the
supporttag, preview the rows, and click Create dataset. With the API, send the same filters toPOST /eval/datasets/from_logs, or create a dataset from pasted items.curl -X POST http://localhost:4000/eval/datasets \-H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \-d '{"name": "refund-questions", "items": [{"input": "How long do refunds take?", "expected": "Refunds are issued within 14 days."}]}' -
On the Runs tab click New run, pick the dataset, both models and a scorer, and click Start run.
curl -X POST http://localhost:4000/eval/runs \-H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \-d '{"dataset_name": "refund-questions", "models": ["gpt-5.5", "claude-sonnet-5-5"], "scorer": {"type": "contains", "substrings": ["14 days"]}}' -
Open the run when it completes, or poll
GET /eval/runs/{run_id}, and click Compare to see which items changed between the two models. The API equivalent isPOST /eval/compare, shown in Comparing runs. -
On the Schedules tab click New schedule, give it the same dataset, models and scorer, a cron such as
0 2 * * *and an alert threshold. See Scheduled runs and regression alerts for the fields.
Expected result
The run answers 200 with the run in pending, then reads completed with a per-model summary. The Compare view lists items that regressed or improved, and the schedule starts the next run at 02:00 and sends a regression alert when the pass rate drops by more than the threshold.
Datasets
A dataset is a named list of items. Each item has an input, which is either a prompt string or an OpenAI-style messages array, and optional fields the scorers use.
| Field | Used by |
|---|---|
expected | exact_match, contains, regex, and the contextual precision and recall metrics. |
context | hallucination, which looks for contradictions against the ground truth. |
retrieval_context | faithfulness and the contextual metrics, which judge the answer against what a retrieval step returned. |
tools, tool_fixtures | Agent mode, see Conversations and agents. |
expected_tool_calls | tool_call_correctness and argument_match. |
expected_outcome | task_completion. |
images on a user message | The image scorers, and vision models in replay and agent mode, see images. |
audio on a user or assistant message | The voice scorers, see voice. |
metadata | Free-form, shown next to results. |
Create a dataset with POST /eval/datasets, or upload a .jsonl or .csv file to POST /eval/datasets/import. JSONL carries one item per line with the keys above. CSV uses the columns input, expected, context and retrieval_context, where the two context columns hold a JSON array or a single string. CSV cannot carry tools or tool calls, so agent items come through JSONL or the API. The Admin UI accepts pasted rows in either format and files for upload.
An item may be at most 256 KiB and a dataset at most 32 MiB of JSON. Creating, importing or replacing items past either limit fails with 400. Datasets stored before these limits existed keep working.
Dataset versions
Every set of items a dataset has held is kept as an immutable version. Creating or importing a dataset stores version 1, and every PATCH /eval/datasets/{dataset_id} or review export that changes the items stores the next version in the same transaction. Sending items identical to the current ones, or only renaming or describing the dataset, keeps the version. Two edits landing at the same moment get a 409 for the later one. GET /eval/datasets/{dataset_id}/versions lists the versions newest first with their item count and digest, and GET /eval/datasets/{dataset_id}/versions/{version} returns one with its items. A dataset created before versions existed gets its version 1 from its current items the first time anything reads its versions, starts a run on it or edits it. In the Admin UI, a dataset's versions sit at the bottom of its detail sheet on the Datasets tab, where Show items reads an earlier version and Delete removes it, and the New run form shows a Dataset version select once a dataset has more than one version, set to the current one unless you pick an earlier one.
A run records the dataset_version it ran, the current one unless POST /eval/runs names an earlier dataset_version, so a run reads back against exactly the items it saw however the dataset changes afterwards. Scheduled runs record the version current when they fire. Comparing runs reads the items of the baseline arm's version and flags an arm whose run ran another version. Versions are deleted with their dataset, and a data subject erasure strips the subject's golden items from every version as well as from the dataset. To drop an item from history, for example one that holds personal data, replace the dataset's items without it and then DELETE /eval/datasets/{dataset_id}/versions/{version} every earlier version that still holds it. The current version cannot be deleted (409), and neither can a version a pending or running run is pinned to. Finished runs of a deleted version keep their results, and comparing them reads the dataset's current items.
Datasets from production traffic
The most realistic test set is the traffic the gateway already serves. POST /eval/datasets/from_logs samples spend log rows into a new dataset, so a model change can be checked against the prompts your users actually send.
{
"name": "support prompts, last week",
"filters": {
"start": "2026-10-08T00:00:00Z",
"end": "2026-10-15T00:00:00Z",
"models": ["gpt-5.5"],
"teams": ["support"],
"tags": ["prod"],
"status": "success",
"min_tokens": 50
},
"sample": {"size": 200, "strategy": "random"},
"include_outputs_as_expected": true
}
Every filter except start and end is optional. models matches the model group or the deployment model, keys takes key aliases or hashed virtual keys as the logs page shows them, and an alias is resolved to its key, tags matches rows carrying any of the given tags (the gateway reads up to the newest 10,000 rows that pass the other filters looking for them, and says so in the 400 when none of those carry a tag), and status is success, failure or all (the default). sample.strategy is latest, which keeps the newest rows, or random, which draws without replacement from the newest 1,000 matching rows, tags included. sample.size is at most 1,000.
Each chosen row becomes one item. The input is the logged chat transcript with its system, user and assistant text turns. With include_outputs_as_expected, the recorded response becomes expected, which turns the dataset into a regression test against what production returned. The item's metadata keeps the request id, model, team, tags, cost, latency and timestamp, and the item id is the request id.
Items copied from logs or sessions are personal data whenever the request was. Their metadata keeps the timestamp of the logged request and, when the request named them, the internal user as subject_user and the end user as subject_end_user. A data subject request exports those items and erase removes them from the dataset and every stored version. The spend log cleanup job also removes them once they are older than maximum_eval_dataset_retention_period, or older than maximum_spend_logs_retention_period when that is shorter, so a copied prompt never outlives the request it came from. Items typed in or imported are never touched by that period. Sessions taken from Lens traces carry no user, so remove them by hand or set the period.
Items need the request and response bodies, which the gateway only keeps when general_settings.store_prompts_in_spend_logs is true (or STORE_PROMPTS_IN_SPEND_LOGS=true). Rows without a body are skipped, and when none of the matching rows has one the request fails with 400 and names that setting.
GET /eval/logs/preview takes the same filters as query parameters plus limit (default 20, at most 100) and shows what a sample would draw from, so you can tune the filters before creating anything.
{
"items": [
{"request_id": "chatcmpl-9f2", "model": "gpt-5.5", "team": "support", "tags": ["prod"], "timestamp": "2026-10-14T18:22:05Z", "input_preview": "My invoice shows two charges for...", "output_preview": "I can see the duplicate charge...", "cost": 0.0031, "latency_ms": 1420}
],
"total": 4810,
"bodies_available": true
}
total counts every matching row. With a tags filter it counts the tagged rows found, at most 1,000, because tags live in a JSON column the database cannot count by. bodies_available is false when none of the previewed rows kept a body.
Datasets from sessions
An agent run or a chat is many requests that share a session. POST /eval/datasets/from_sessions turns each session into one item whose input is the whole conversation, tool calls and tool results included, so it can be replayed, rerun as an agent or scored as it was logged. Only proxy admins can create one, because it reads the logs of every team.
{
"name": "support agent sessions",
"source": {"type": "spend_logs", "session_ids": ["sess-41c", "sess-9e0"]},
"include_truncated": false
}
Sessions come from spend logs, by session_ids (at most 1,000) or by filters and sample exactly as for datasets from logs, or from Lens with {"type": "lens", "trace_ids": [...]} (at most 200). Spend logs store the value of the x-spanway-session-id header, or the trace id the request carried, as the session id.
For each spend log session the gateway picks the chat completions, Anthropic messages or Responses request with the longest message history, because coding agents share a session with title generation and compaction calls that see only part of the conversation. Only that request's body is read, however many requests the session has. Anthropic and Responses bodies are translated to the same chat shape, so one conversation gives the same transcript whichever API served it. The logged reply, with its tool calls, becomes the last assistant turn. The item id is that request's id and metadata keeps the request_id, session_id, team_id, model and the number of requests in the session, so the run ledger of that request shows the scores of every run over the item.
For Lens, the gateway reads each trace in the caller's own trace scope, takes its LLM span with the most input tokens and uses that span's messages. Lens messages carry no tool call ids, so calls get ids of the form lens_<span>_<n> and each tool result answers the earliest unanswered call. A trace the caller cannot see, or whose span holds no messages, is skipped. Lens must be configured with SPANWAY_LENS_URL, otherwise creating a dataset from a Lens source fails with 501 and the preview answers with no sessions and lens_available set to false. When Lens is configured but the caller may not read agent traces, both fail with 403.
Sessions are skipped and counted when their messages were redacted, when no user turn can be read, or when the data policy stored on their key, team or organization is invalid. The gateway truncates long strings in logged bodies to MAX_STRING_LENGTH_PROMPT_IN_DB characters (2048 by default), which most agent sessions hit somewhere. A session where only prose was truncated is kept and flagged as truncated. A session whose tool arguments or tool results were truncated, in the history or in the logged reply, is skipped, since tool scorers would compare broken JSON, unless include_truncated is true, in which case truncated arguments are kept whole under _raw with the truncation marker. Redacted tool arguments get the session skipped the same way as redacted messages. Raise MAX_STRING_LENGTH_PROMPT_IN_DB if you plan to evaluate long agent sessions, and keep store_prompts_in_spend_logs on.
Every item keeps the data policy of the key, team and organization of the request it came from in source_data_policy. Every call a run makes for that item, the judge included, carries that policy on top of the caller's own, so a zero data retention team's sessions are only replayed or judged on deployments that declare zero retention. Remote scorers make no retention promise the gateway can check, so an item under any restricting policy is never sent to one and its result is an error naming the policy. A Lens trace with no gateway request behind it carries no source policy. Datasets drawn with from_logs, and the datasets schedules draw from logs, snapshot the same policy onto each item, and a row whose stored policy is invalid is left out. The gateway alone sets source_data_policy. It is ignored when a client sends it on create, import or PATCH, and a PATCH that replaces the items keeps the stored policy of every item whose item_id it keeps. Content copied into an item with a new id does not carry the policy, so anyone who can read a dataset drawn from logs can still repeat its content in another dataset.
GET /eval/sessions/preview shows at most 50 sessions as the dataset would hold them, with turn and tool call counts, a truncated flag, a flag for sessions under a data policy, the skipped counts and whether bodies and Lens are available. Pass source=spend_logs with repeated session_id, or start and end, or source=lens with repeated trace_id. Like the log preview, it shows request bodies from every team, so both previews are open to proxy admins and admin viewers only.
Session datasets hold production prompts, tool arguments and tool outputs. Everyone who can read evals can read them, and deleting the dataset is the only way to remove them.
Synthetic datasets from documents
When a feature has no traffic yet, POST /eval/datasets/synthesize writes a starter dataset from documents you paste in. For each context (one to ten text chunks from the same document) the model writes questions a user could ask, a critic call checks each one is answerable from the context, one refinement pass makes it harder, and with include_expected_output the model answers it from the context. Every item keeps its context, so the faithfulness and contextual scorers can use it, and is tagged {"source": "synthetic"}.
curl -X POST http://localhost:4000/eval/datasets/synthesize \
-H "Authorization: Bearer sk-admin-key" -H "Content-Type: application/json" \
-d '{
"name": "refund-policy-starter",
"synthesis": {
"model": "my-model",
"contexts": [["Refunds are issued within 14 days of a returned item reaching the warehouse."]],
"goldens_per_context": 2,
"scenario": "customers asking a support chatbot",
"task": "answer refund questions"
}
}'
Generation uses a model the gateway serves and runs as your key, so the key's budget and rate limits, its guardrails on both input and output, and its data policies apply to every call, the same as a real request. A guardrail that blocks a call fails the whole request with 502 and nothing is stored. Only the text in contexts is sent, never logged traffic. A request takes up to 20 contexts of at most 8,000 characters per chunk and 5 items per context, and stops after a fixed number of model calls (one per context plus five per requested item), so a misbehaving model cannot run up cost. The call returns when the dataset is stored, so keep large jobs to several smaller requests. Like the other dataset routes, it needs a role that can change datasets and the evals extra installed on the proxy, or it answers 501.
In the Admin UI, Generate synthetic dataset on the Datasets tab of the Evals page takes a model and documents separated by a line holding ---, and shows the most model calls the run can make before you start it.
Review synthetic items before you gate releases on them, since the model can write questions that read well but miss the point of the document.
Scorers
A scorer is chosen per run. GET /eval/scorers returns the catalogue, including which item fields each scorer requires, so the Admin UI can warn when a dataset lacks them. The Admin UI scorer picker shows each scorer's one-line description from the same catalogue under the picker.
Metric catalogue
| Scorer | What it checks | Needs a judge model |
|---|---|---|
exact_match | Output equals expected, optionally case-insensitive and whitespace-stripped. | No |
contains | Output contains any or all of the given substrings, or expected. | No |
regex | Output matches a pattern. | No |
json_schema | Output parses as JSON and validates against a schema. | No |
g_eval | A rubric you write as criteria or evaluation steps, scored 0 to 1. | Yes |
arena_g_eval | The output against expected, judged blind by criteria you write. The item passes when the output wins. | Yes |
dag | A decision graph you define. The judge walks it node by node and the verdict it reaches is the score. | Yes |
answer_relevancy | How much of the output addresses the input. | Yes |
faithfulness | Every claim in the output is supported by retrieval_context. | Yes |
hallucination | The output does not contradict context. | Yes |
bias, toxicity | The output is free of biased or toxic content. | Yes |
non_advice | The output gives none of the kinds of advice named in advice_types, such as financial or medical. | Yes |
misuse | The output stays inside the assistant's domain and is not put to an unrelated or harmful use. | Yes |
pii_leakage | The output reveals no names, contact details, identifiers or other personal data. | Yes |
role_violation | The output never breaks the role it was given, for example by dropping the persona or its rules. | Yes |
summarization | The output covers the input without inventing facts. | Yes |
json_correctness | The output matches an expected JSON schema. | Yes |
contextual_precision, contextual_recall, contextual_relevancy | Ranking, coverage and relevance of retrieval_context against expected. | Yes |
tool_call_correctness | The transcript called the tools in expected_tool_calls. | No |
argument_match | Those calls were made with the expected arguments. | No |
task_completion | The conversation achieved expected_outcome. | Yes |
turn_relevancy | Every assistant turn is relevant to the turns before it. | Yes |
conversation_completeness | The assistant met every intention the user expressed. | Yes |
step_efficiency | The agent reached its result without redundant steps or tool calls. | Yes |
plan_adherence | The agent followed the plan it stated in its replies. | Yes |
plan_quality | The plan the agent stated is complete, logical and fit for the task. | Yes |
argument_correctness | Every tool call's arguments fit the user's request, with no expected_tool_calls needed. | Yes |
goal_accuracy | The conversation reached the goal the user set, by a sound plan. | Yes |
tool_use | The agent picked the right tools from the item's tools and called them with fitting arguments. | Yes |
knowledge_retention | The assistant remembers what the user told it earlier and never asks for it again. | Yes |
role_adherence | Every assistant turn stays in the chatbot_role you describe. | Yes |
turn_faithfulness | Every assistant turn's claims are supported by retrieval_context. | Yes |
conversational_g_eval | A rubric you write, applied to the whole conversation. | Yes |
mcp_use | The agent picked the right tools of the MCP servers named in server_prefixes and called them with fitting arguments. | Yes |
mcp_task_completion | The conversation completed what the user asked through those servers' tools. | Yes |
multi_turn_mcp_use | Across every turn, the agent picked the right MCP tools and called them with fitting arguments. | Yes |
citation_faithfulness, ragas | Cited passages support what they are cited for, and the RAGAS score over precision, recall, faithfulness and relevancy. | Yes |
agent_loop_detection, tool_permission | The agent never loops, and calls only the tools you allow. | No |
text_to_image, image_editing, image_coherence, image_helpfulness, image_reference | The images in the answer, judged by a vision model. | Yes |
voice_naturalness, turn_taking_naturalness, speech_intelligibility, voice_consistency, agent_responsiveness, audio_integrity, voice_reliability | Recorded voice audio, measured with no judge. | No |
The last four rows are explained, with their settings, item fields, steps and errors, on RAG, agent, image and voice scorers.
Judged scorers take a judge_model, which must be a model name the gateway serves, and a threshold between 0 and 1 (default 0.5). arena_g_eval has no threshold, since it scores 1 when the output wins and 0 when the expected answer does. It takes name, criteria and optional evaluation_steps like g_eval, and the judge sees both answers under random names so it cannot favour the reference. conversational_g_eval takes the same fields plus a threshold, and shows the judge expected_outcome too when the item has one. The judge is asked for a score, a pass or fail, and a reason, and the reason is kept with every result.
Every scorer from tool_call_correctness to multi_turn_mcp_use, and the agent checks and voice scorers, reads the whole transcript, so it runs only in replay, agent and logged mode, and GET /eval/scorers marks it with observes: "transcript". Any other scorer used in those modes scores the final assistant reply, which is empty when the conversation ended on a turn that still called tools. Schedules run in single mode and refuse transcript scorers.
dag takes a name and a graph, which is {"nodes": {...}} keyed by node id, at most 50 nodes. A BinaryJudgementNode asks the judge a yes or no criteria and continues with the VerdictNode child whose verdict is true or false. A NonBinaryJudgementNode does the same with verdicts that are strings. A TaskNode asks the judge to produce something under instructions, named by output_label, which its judgement children then see. A VerdictNode ends the walk with a score from 0 to 10, which becomes 0 to 1, or continues with {"type": "node", "ref": "<id>"} as its child, never both. evaluation_params picks what a node sees from input, actual_output, expected_output, context and retrieval_context, and a root node must set it. Unknown references, a graph with no root, verdicts with both or neither of a score and a child, and children that would run another metric or another model are refused when the run is created, so every call the graph makes goes to the run's judge.
{
"type": "dag",
"judge_model": "claude-opus-5-5",
"name": "cites a source",
"graph": {
"nodes": {
"cites": {
"type": "BinaryJudgementNode",
"criteria": "Does the answer cite a source for its main claim?",
"evaluation_params": ["actual_output"],
"children": ["yes", "no"]
},
"yes": {"type": "VerdictNode", "verdict": true, "score": 10},
"no": {"type": "VerdictNode", "verdict": false, "score": 0}
}
}
}
tool_call_correctness takes order: subsequence (the default) wants the expected tools in that order with other calls allowed in between, exact wants exactly that sequence, and any ignores order. The score is the share of expected calls matched, and with allow_extra set to false any call beyond them fails the item. argument_match pairs each expected call that names arguments with the transcript's call of the same tool in the same position among that tool's calls, and compares the arguments with mode subset (the default, extra keys allowed) or exact. Key order never matters, 1 equals 1.0, and true never equals 1. Both default to a threshold of 1. They are computed by the gateway itself and follow the name, order and input parameter rules of the judged tool correctness metric, so they need no evals extra and cost nothing.
task_completion judges task completion without a trace: the judge reads the first user turn, the final reply and every tool call, and compares the outcome with expected_outcome. step_efficiency, plan_adherence and plan_quality read the transcript as an agent trace, one model step per assistant reply and one tool step per call with its arguments and result, and the two plan metrics take the plan from what the assistant wrote, so an agent that never states a plan scores as having none. argument_correctness judges the arguments of every call against the first user turn, unlike argument_match, which compares them with expected_tool_calls and costs nothing. goal_accuracy and tool_use judge the conversation turn by turn like the conversation metrics, and tool_use shows the judge the item's tools as the tools the agent could have picked. role_adherence takes chatbot_role, for example a polite airline support agent that never discusses refunds. turn_faithfulness gives every assistant turn the item's retrieval_context, takes window_size (1 to 50, default 10) like turn_relevancy. The three MCP metrics take server_prefixes, the prefixes the gateway puts before the tool names of each MCP server, which is the server alias, or its short prefix when SPANWAY_USE_SHORT_MCP_TOOL_PREFIX is on, followed by MCP_TOOL_PREFIX_SEPARATOR (- by default). A tool in the item's tools named jira-create_issue is offered as create_issue on server jira, and a call of it counts as an MCP call, while calls of other tools stay plain function calls. turn_relevancy takes window_size (1 to 50, default 10). Both conversational metrics see tool calls and their results described inside the assistant turn that made them, and they drop system messages.
Custom scorers
When the built-in scorers cannot express what "good" means for your workload, register a remote scorer: an HTTPS endpoint you run that receives each output and answers with a score. The gateway never imports or runs scorer code. It sends one signed request per item and model and reads back the verdict, so your scorer can use any language, library or private data.
Registering a scorer
curl -X POST http://localhost:4000/eval/remote_scorers \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
-d '{"name": "support-grader", "url": "https://scorer.internal.example.com/score", "requires": ["expected"]}'
The response carries signing_secret, a whsec_ secret shown this once and never again. Store it with your scorer. Optional fields are description, timeout_ms (500 to 60000, default 10000), max_retries (0 to 3, default 2), max_concurrency (1 to 64, default 8), requires, the item fields the scorer reads, and self_hosted (default false), which says the scorer runs on your own infrastructure so an online rule may send it requests under a restricting data policy. Eval runs never send an item under a restricting data policy to any remote scorer, self_hosted or not, and such an item becomes an error result. self_hosted is accepted only for a host listed in general_settings.eval_self_hosted_scorer_hosts in the config file, which the admin API cannot change, and it is checked again every time an online rule resolves the scorer, so a scorer whose host is removed from that list stops getting restricted requests. Items without a required field become error results before any request is sent. Names are lowercase letters, digits, - and _.
GET /eval/remote_scorers and GET /eval/remote_scorers/{scorer_id} show a scorer without its secrets and with the scheme and host of its URL only, since webhook paths often carry credentials. PATCH changes the fields you send and checks a new URL again. A change to url, timeout_ms, max_retries, max_concurrency, requires or self_hosted starts a new revision, a change to description or enabled does not. DELETE is refused while a pending or running run or an enabled schedule uses the scorer, and the error names them. Disabling or deleting it while an enabled online rule uses it is refused with 409. A run left running after a restart can be cancelled with POST /eval/runs/{run_id}/cancel to unblock the delete.
Using one in a run
{"dataset_id": "6c1f...", "models": ["gpt-5.5"], "scorer": {"type": "remote", "scorer_id": "3f2a...", "params": {"rubric": "strict"}, "threshold": 0.7}}
params is sent with every request and is visible to every admin viewer, so never put credentials in it. It is capped at 16 KiB. The run stores the scorer's current revision and required fields whatever the request sends, and every item is scored against that revision. If the scorer is edited, disabled or deleted while a run is going, the run keeps the target it resolved when it started. A new run of a disabled or unknown scorer is refused with 400. Schedules pin the revision again on every fire, so they follow edits. A schedule whose scorer was disabled or deleted is skipped on each fire with a Medium eval_regression alert, launches nothing and stays enabled. Reproducing a result later depends on you versioning the scorer behind the URL.
POST /eval/scorers/test scores one output with any scorer type, built-in, judged or remote, exactly as a run would, and stores nothing:
curl -X POST http://localhost:4000/eval/scorers/test \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
-d '{"scorer": {"type": "remote", "scorer_id": "3f2a..."}, "item": {"input": "Capital of France?", "expected": "Paris"}, "model": "gpt-5.5", "output": "Paris"}'
It answers {"outcome": "scored", "score", "passed", "reason", "latency_ms"} or {"outcome": "error", "error", "latency_ms"}.
The request your scorer receives
Each request is a POST with a JSON body that follows the v1 schema:
{
"version": "1",
"scorer": {"id": "3f2a...", "name": "support-grader", "revision": 2},
"params": {"rubric": "strict"},
"item": {
"item_id": "i1",
"input": "Capital of France?",
"expected": "Paris",
"context": null,
"retrieval_context": null,
"tools": null,
"expected_tool_calls": null,
"expected_outcome": null,
"metadata": null
},
"model": "gpt-5.5",
"output": "Paris",
"source": {"kind": "run", "run_id": "9b1e..."}
}
output is the model's reply, or the final assistant reply of a replay, agent or logged conversation. source.kind is run, schedule (with schedule_id) or test. Receivers must ignore fields they do not know, because optional fields can be added to v1 without a new version.
Answer 200 with {"score": 0.8, "passed": true, "reason": "..."}. score must be a number from 0 to 1, a string is refused. passed is optional and defaults to score >= threshold. reason is optional and kept up to 2000 characters. A bare number or true/false body is accepted too. Replies over 64 KiB are refused.
Verifying the signature
Requests are signed with Standard Webhooks. The webhook-id, webhook-timestamp and webhook-signature headers sign the exact body bytes with HMAC-SHA256, and any Standard Webhooks library verifies them with the secret. webhook-signature can hold several space-separated signatures, and a request is genuine when any one of them matches. Reject timestamps older than a few minutes. X-Spanway-Scorer-Id names the scorer.
POST /eval/remote_scorers/{scorer_id}/rotate_secret returns a new secret, shown once. For grace_seconds (default 86400, up to 7 days) the old secret stays valid and every request carries one signature per secret, so you can switch the receiver over without dropping requests. {"grace_seconds": 0} drops the old secret at once. Signing secrets are encrypted at rest and move with a master key rotation.
Timeouts, retries and concurrency
Each attempt gets timeout_ms in all, including reading the reply, with a 2 second connect timeout. Connection errors, 429 and 5xx are retried up to max_retries times with jittered backoff, and Retry-After is honoured up to 10 seconds. Other 4xx, redirects and timeouts are not retried. Every retry of one delivery keeps the same webhook-id, so deduplicate on it. max_concurrency caps the requests in flight to one scorer across every run on a gateway instance, so the total is that cap times your replicas.
A failure becomes the error of that one result, for example remote scorer support-grader answered HTTP 503, and is left out of the means like any other error. Error messages carry the status only, never the reply body, the URL, a header or a secret.
Network rules
Scorer URLs must use https and resolve to public addresses. The gateway checks this when the scorer is registered or its URL changes, and again before every request. For a scorer inside your cluster, add its host to user_url_allowed_hosts, which allows private addresses and plain http for that host only. Set general_settings.eval_remote_scorer_hosts to restrict scorers to a list of hosts. Credentials in the URL are refused, redirects are never followed, and https scorers are refused while ssl_verify is off.
An item under a restricting data policy (require_zdr, forbid_training or restrict_code_traffic), whether it comes from the caller's key, team or organization or from the logged request in source_data_policy, is never sent to a remote scorer. Its result is an error such as item i1 falls under the source team data policy, so it is not sent to a remote scorer, and no request leaves the gateway. The dry run follows the same rule for the caller's own policies.
A remote scorer receives your dataset items and model outputs, so only proxy admins can register, change, rotate, delete or dry-run one, and these routes are outside the evals custom role permissions. In Spanway Cloud, remote scorers are managed by the operator only for now, since eval tables are not yet scoped per organization.
Running your own scorer
A remote scorer is any HTTPS service that implements the request and reply above and verifies the Standard Webhooks signature, in whatever language your team uses. Keep it idempotent on webhook-id, answer 422 for an item it cannot score so the gateway records the error without retrying, and keep its own deadline below the scorer's timeout_ms, otherwise the gateway records a timeout first. Spanway does not distribute a scorer helper package or image, so you build the service from this request and reply format. A Compose service next to the gateway looks like this:
services:
scorer:
image: my-registry/my-scorer:1.0.0
environment:
SCORER_SECRET: ${SCORER_SECRET}
Register it as http://scorer:8080/score and add scorer:8080 to user_url_allowed_hosts.
Runs
POST /eval/runs with a dataset_id, a list of models and a scorer starts a run and returns 200 immediately with the run in pending. The run moves to running, then completed, failed or cancelled. Items run concurrently up to concurrency (default 4), one failure never stops the run, and POST /eval/runs/{run_id}/cancel stops it between items.
GET /eval/runs/{run_id} returns the run with its summary once it completes.
{
"status": "completed",
"summary": {
"models": [
{"model": "gpt-5.5", "item_count": 120, "scored_count": 120, "error_count": 0, "mean_score": 0.91, "pass_rate": 0.93, "mean_latency_ms": 1840, "total_cost": 0.42},
{"model": "claude-sonnet-5-5", "item_count": 120, "scored_count": 119, "error_count": 1, "mean_score": 0.94, "pass_rate": 0.96, "mean_latency_ms": 2110, "total_cost": 0.57}
],
"best_model": "claude-sonnet-5-5"
}
}
GET /eval/runs/{run_id}/results pages through the per-item rows, filterable by model and passed, each with the output, score, reason, latency, cost and any error.
GET /eval/runs lists runs newest first and filters by dataset_id, status, schedule_id, prompt_id, mode, baseline_key and git_ref, the last two being what a CI job reported.
Results and their transcripts copy model outputs and whole conversations, so they are personal data whenever the dataset item came from someone's requests. They are kept until the run is deleted or maximum_eval_run_retention_period removes finished runs, and once that period is set the shorter of it and the spend log period applies. A data subject erasure that removes a person's dataset items also deletes the results and transcripts produced for them. Red team runs work the same way under maximum_red_team_run_retention_period.
Testing a managed prompt
A run can render every item through a managed prompt before it is sent. Add prompt_id, and optionally prompt_version, to POST /eval/runs. The prompt's messages come first and the item's messages follow, exactly as the gateway renders a request that names the prompt, and the prompt's optional parameters such as temperature apply. The prompt's own model is ignored, because the run decides which models answer. Without prompt_version the run uses the latest version the gateway serves when the run starts. The run resolves the version and environment once, stores them as prompt_version and prompt_environment, and renders every item with that version, so publishing a new version while the run is going does not change the items that are still waiting. Add prompt_environment, for example staging, to test the version of that environment instead of the one requests get by default. In the Admin UI it is the Prompt environment field of New run. A run of an exact prompt, version and environment whose quality gate passes is what a promotion into a protected environment such as production asks for, and prompt_environment without prompt_id is refused with 400 prompt_environment needs a prompt_id.
The prompt must be loaded on the gateway when the run starts, or the request fails with 400. Run the same dataset once per prompt version and compare the runs, or list every run of a prompt with GET /eval/runs?prompt_id=support-agent.
Templates and sampling params
A run can instead wrap every item in a literal template. template.system replaces the system turns of each item, and template.user_template wraps the last user turn, with every {{input}} replaced by that turn's text. That placeholder is the only substitution. Nothing else in the template or the input is expanded, so an input that itself contains {{input}} or {{ 7*7 }} is sent as it is. A user template without {{input}} is refused. params sets temperature, top_p, max_tokens, seed and up to four stop sequences for every completion of the run, and any other key is a 422, so a run cannot change routing, metadata or response format through it. Params also apply on top of a managed prompt and win over the prompt's own values.
{
"dataset_id": "6c1f...",
"models": ["gpt-5.5", "claude-sonnet-5-5"],
"scorer": {"type": "contains", "substrings": ["Paris"]},
"template": {"system": "Answer in one word.", "user_template": "Question: {{input}}"},
"params": {"temperature": 0, "max_tokens": 64}
}
A template works in single and agent mode and cannot be combined with prompt_id. Params work in every mode but logged, which makes no completion. Judge calls never see the template or the params. The run stores both, and GET /eval/runs returns them with items_digest, a hash of the dataset items the run saw.
Every completion of a run, and every judge call, carries {"spanway_eval": "run", "eval_run_id": "<run_id>"} in its spend log metadata. It is a label only, it does not add request tags or change which deployment serves the call. When general_settings.spend_logs_metadata_fields sets an include list, add spend_logs_metadata to it to keep the label on the spend row. Eval completions inherit the gateway-wide structured output repair setting but not a key or team override, since they do not pass through the per-key request setup.
Comparing runs
POST /eval/compare lines up two to four arms of one dataset item by item. An arm is a run_id and one of its models, so an arm can be another run or another model of the same run. The first arm is the baseline.
curl -s http://localhost:4000/eval/compare \
-H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \
-d '{"arms": [{"run_id": "run-a", "model": "gpt-5.5"}, {"run_id": "run-b", "model": "gpt-5.5"}], "filter": "regressed", "tolerance": 0.05}'
For every item, each arm's change against the baseline is decided in this order.
| Order | Condition | Change |
|---|---|---|
| 1 | Either side has no result for the item | incomparable |
| 2 | Only the arm errored, or only the baseline did | regressed with new_error, or improved with error_fixed |
| 3 | passed flipped | regressed with pass_to_fail, or improved with fail_to_pass, whatever the score did |
| 4 | The score moved by more than tolerance (strictly) | regressed with score_drop, or improved with score_gain |
| 5 | Anything else, both sides erroring included | unchanged |
Each change carries score_delta, latency_delta_ms and cost_delta, arm minus baseline, or null when either side lacks the value. An item with a regressed arm and an improved arm is mixed, and appears under the regressed, improved and changed filters. filter is one of all, regressed, improved, changed, unchanged and incomparable, sort is dataset or score_delta (largest drop first, items without a score delta last), and pages hold at most 50 items. Items keep dataset order, and results for items no longer in the dataset follow, sorted by id.
totals cover every item whatever the filter and page. They count each change kind per arm and give mean_score_delta, pass_rate_delta and the cost and latency differences. Each arm's pass rate is computed over that (run, model) arm alone, while a schedule's regression alert uses the mean over the run's models, so the two numbers can differ for a run of several models. Each item's cells carry the stored results, with outputs cut to their first 4000 characters and output_truncated set. GET /eval/runs/{run_id}/results has the full text.
warnings explain when a comparison deserves care.
| Warning | Meaning |
|---|---|
scorers_differ | The arm's run used a different scorer config than the baseline's. Each arm carries its scorer and a scorer_digest. |
arms_dataset_differ | Both runs recorded an items digest and the digests differ, so they saw different items. |
dataset_changed | The dataset changed after the run. basis is digest when the run recorded one, or updated_at for runs from before digests were recorded. Input previews show the current items. |
run_incomplete | A run is still pending or running, or was cancelled or failed. The comparison is polled until every arm finishes. |
orphan_items | Results whose item was removed from the dataset. |
Runs of different datasets or different modes cannot be compared and return 400, and so does an arm whose model is not in its run. A schedule that draws from logs creates a fresh dataset on every fire, so its runs cannot be compared item by item. A comparison classifies at most 40000 results across all arms and returns 400 beyond that. Comparing reads stored results only, costs nothing and writes no audit row.
Playground
POST /eval/playground tries a setup on a few items while the request waits, so a prompt can be tuned before it runs on the whole dataset.
curl -s http://localhost:4000/eval/playground \
-H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \
-d '{"dataset_id": "6c1f...", "sample": {"mode": "random", "size": 5}, "models": ["gpt-5.5", "claude-sonnet-5-5"],
"template": {"system": "Answer in one word.", "user_template": "Question: {{input}}"},
"params": {"temperature": 0}, "scorer": {"type": "contains", "substrings": ["Paris"]}}'
sample picks the items: {"mode": "items", "item_ids": [...]} in the order given, {"mode": "first", "size": n}, or {"mode": "random", "size": n} drawn without replacement and kept in dataset order. A random draw returns its seed, and sending it back draws the same items. The setup is a template or a managed prompt_id with optional prompt_version, never both, plus optional params, with the same rules as a run. Without a scorer only the outputs come back and summary is null. A transcript scorer is refused, since the playground runs single mode. A remote scorer sends each item and output to its endpoint, as it does in a run.
The response has the item_ids, every result in item then model order, a rendered_example showing the first item's messages exactly as the first model receives them, after the template or the managed prompt has been applied, the per-model summary, and timed_out. Limits are 20 items, 3 models and 30 item and model pairs per request, at most 8 pairs in flight (concurrency, default 4), and 45 seconds. Pairs still running at the deadline come back as timed out after 45s errors while finished outputs stay. Each gateway replica runs at most 4 playground requests at once and answers 429 with playground is busy beyond that.
Nothing is stored. Every completion is still routed, logged and billed to the caller's key, and carries {"spanway_eval": "playground"} in its spend log metadata, with the same include-list caveat as runs. To run the setup on the whole dataset, send the same template, prompt_id and params to POST /eval/runs.
Conversations and agents
A run has a mode. single, the default, sends each item once to each model as described above. Three more modes evaluate conversations.
| Mode | What runs | What is scored |
|---|---|---|
replay | Each model answers every user turn of the item's stored conversation in order. The stored assistant turns are never sent, so each turn sees the model's own earlier replies. | The new conversation. |
agent | Each model works the item with its tools. Every tool call is answered from the item's tool_fixtures, and the loop ends when the model replies without calling a tool or after max_steps model calls (1 to 25, default 8). | The full transcript. |
logged | Nothing. models must be empty. | The stored conversation as it is, under the model recorded in the item's metadata.model. |
An agent item names its tools in the OpenAI function shape and the canned results of calling them:
{"input": "What is the weather in Paris?", "tools": [{"name": "weather", "description": "Current weather", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}}}], "tool_fixtures": [{"name": "weather", "arguments": {"city": "Paris"}, "output": "sunny, 21C"}, {"name": "weather", "output": "no data"}], "expected_tool_calls": [{"name": "weather", "arguments": {"city": "Paris"}}], "expected_outcome": "reports the weather in Paris"}
A fixture with arguments answers only a call with equal arguments and wins over a fixture without them, which answers any call of that tool. A call no fixture answers gets {"error": "no fixture for <tool>"} back and the loop continues, so the transcript shows what the model does with a failing tool. Fixtures are static strings and no tool code runs. A replay item is a conversation of system, user and assistant turns without tool turns, with at most 100 user turns. A logged item is any conversation with at least one assistant turn, such as an item from sessions.
{"dataset_id": "6c1f...", "models": ["gpt-5.5"], "mode": "agent", "max_steps": 6, "scorer": {"type": "tool_call_correctness", "order": "subsequence"}}
The run is refused with 400 when a transcript scorer is used in single mode, when max_steps is sent outside agent mode, when a managed prompt is used in replay or logged mode, or when items do not fit the mode (every agent item needs tools, and the error names up to ten items). With a managed prompt in agent mode, the item's tools replace any tools the prompt defines.
Each result row gains steps, the number of model calls (assistant turns for logged runs), and tool_call_count, and the run summary gains mean_steps per model over results without an error. Logged results have no cost or latency, and a logged run stores the distinct models of its items as its models. GET /eval/runs/{run_id}/results/{result_id} returns one result with its transcript, the stop reason (finished, max_steps or logged) and the item's trace id. Result lists never include transcripts.
Every turn goes through the router as the proxy admin who started the run, so it is logged and billed like any request. A run costs up to items x models x max steps model calls, plus judge calls for judged scorers, and the conversational metrics make several judge calls per conversation. Each call carries the caller's data policies and the item's source_data_policy, and a call no deployment can serve under them becomes one error row. Cancelling a run stops a conversation within five model calls.
Not in this version: live MCP or A2A tools, a simulated user, Responses previous_response_id chains, images and other non-text parts (dropped from logged conversations), Lens lookup by session id, and modes other than single on schedules.
Scheduled runs and regression alerts
A schedule starts a run on a cron, so a quality drop shows up the morning after a provider ships a new model snapshot or someone edits a prompt, without anyone remembering to rerun the eval.
{
"name": "nightly support regression",
"dataset_id": "6c1f...",
"models": ["gpt-5.5", "claude-sonnet-5-5"],
"scorer": {"type": "g_eval", "judge_model": "gpt-5.5", "criteria": "The answer resolves the customer's issue."},
"cron": "0 3 * * *",
"timezone": "Europe/Berlin",
"alert": {"min_pass_rate": 0.85, "regression_threshold": 0.05}
}
A schedule evaluates either a fixed dataset_id or from_logs, which takes the filters, sample and include_outputs_as_expected fields of the from-logs request above and draws a new dataset from spend logs every time it fires. Exactly one of the two is set. Add lookback_seconds to from_logs (at least 60) to sample recent traffic: each fire then replaces filters.start and filters.end with the window of that length ending at the fire time, so "lookback_seconds": 86400 on a nightly schedule tests the last day of traffic every night. Without it, every fire samples the same fixed start to end window. cron has five fields and is read in timezone (default UTC). The response carries next_run_at in UTC.
Add prompt_id, and optionally prompt_version, to render every item through a managed prompt, as in a run. Without prompt_version each fire resolves the latest version at that moment and the run records it, so the regression alert catches a newly published prompt version the night after it ships. A fire whose prompt is no longer loaded is skipped and raises an eval_regression alert.
| Route | What it does |
|---|---|
POST /eval/schedules | Creates a schedule and computes its first next_run_at. |
GET /eval/schedules | Lists schedules, filterable by enabled. |
GET /eval/schedules/{schedule_id} | Returns one schedule with last_run_id, last_run_at and next_run_at. |
PATCH /eval/schedules/{schedule_id} | Changes the fields sent. A new cron or timezone, or re-enabling, recomputes next_run_at from now. Only dataset_id, from_logs, prompt_id and prompt_version accept null. Sending prompt_id without prompt_version follows the latest version. |
DELETE /eval/schedules/{schedule_id} | Deletes the schedule. The runs it started stay. |
POST /eval/schedules/{schedule_id}/run_now | Starts the schedule's run immediately without moving next_run_at. |
Every gateway replica checks for due schedules once a minute, and each due schedule is claimed by exactly one replica, so running several replicas never starts a schedule twice. A schedule whose cron cannot be parsed is disabled. Schedules stop firing while the gateway has no license and resume once it has one again. Scheduled runs act as the admin who created the schedule, so their spend lands on that user like any other eval run. Before each fire the gateway checks that the creator still exists and is still a proxy admin, and skips the fire with a warning in the logs when they were deleted or lost the role. A schedule created with a virtual key is also bound to that key, and a fire is skipped once the key is deleted, blocked or expired, so revoking a leaked admin key stops what it scheduled. Rotating the key with /key/regenerate or auto_rotate moves the schedule to the new key, so it keeps firing. Recreate the schedule with a working key to start it again. A schedule created with the master key or from a dashboard session is not bound to a key, and one created with the master key keeps firing.
When a scheduled run completes, its pass rate (the mean over the models that scored any item) is compared with the previous completed run of the same schedule. The run raises an eval_regression alert through the gateway's alerting integrations when the pass rate is under alert.min_pass_rate, or when it fell by more than alert.regression_threshold since the previous run. Leave both unset to never alert. The verdict is stored on the run's summary either way.
{
"summary": {
"models": [{"model": "claude-sonnet-5-5", "item_count": 120, "scored_count": 120, "error_count": 0, "mean_score": 0.86, "pass_rate": 0.88, "mean_latency_ms": 2050, "total_cost": 0.55}],
"best_model": "claude-sonnet-5-5",
"regression": {"previous_run_id": "a91e...", "delta": -0.08, "alerted": true}
}
}
delta is this run's pass rate minus the previous run's, and is null on the first run of a schedule. The alert goes to the destinations configured in alerting. When general_settings.alert_types is set, add eval_regression to it, and when it is unset the alert is sent by default.
Gating pull requests
A CI job can start a run with a ci key, and GET /eval/runs/{run_id}/verdict checks it against a gate and a trusted baseline run. spanwayctl evals gate turns the verdict into an exit code and a pull request comment. Gating pull requests on evals covers CI keys, baselines, every threshold and a workflow to copy.
Shadow results
Shadow evaluation tests a candidate auto router on a sample of live traffic without serving its answers, and a judge compares the replies. GET /eval/shadow returns those verdicts in the shape of eval results, so they can be read next to offline runs.
| Query parameter | Meaning |
|---|---|
model | Matches either the shadow or the serving model. |
start, end | Limits the verdicts to a time window. |
page, page_size | Pagination, 50 per page by default and 200 at most. |
Each row has source set to shadow. model is the shadow model and real_model the model that served the request, item_id is the judged request id and run_id the shadow job. score is the judge's confidence and passed is true when the shadow model won or tied. Rows where judging failed carry the error and no score.
Online scoring
Online scoring grades production responses as they happen. A rule picks the live requests it cares about, samples a share of them, and scores each sampled response with one to five scorers. Scoring starts after the response went back to the caller, in a task detached from the request, so it never adds latency. Scores are stored per request id, summarised per model group and scorer by hour or day, shown in the log drawer of each scored request, and can raise eval_regression alerts.
{
"name": "support answers",
"match": {"model_groups": ["claude-sonnet-5-5"], "tags": ["support"]},
"sample_percentage": 5,
"scorers": [
{"type": "contains", "substrings": ["refund policy"], "mode": "any"},
{"type": "g_eval", "judge_model": "gpt-5.5", "name": "tone", "criteria": "The reply is polite and resolves the question."}
],
"daily_judge_budget": 5,
"alert": {"min_pass_rate": 0.8, "regression_threshold": 0.1, "window_minutes": 60, "min_scored": 20}
}
match has four lists, model_groups, team_ids, keys and tags. Values within one list are alternatives, every list that is set must match, and an empty list matches anything. Model groups resolve through the router's aliases, so a rule on an alias follows it when it is re-pointed. keys takes key aliases or key hashes and refuses anything that looks like a raw sk- key. An alias keeps matching after its key is regenerated. Request tags are set by the caller, so anyone who can call the gateway can put their traffic in front of a tag rule. Sampling is decided by a hash of the request id and the rule id, so every replica makes the same choice and different rules sample independent slices.
Online scorers see only the request's conversation and the reply the caller received, so a rule accepts contains (with substrings), regex, json_schema, the judged metrics that need no expected answer or context, such as g_eval, answer_relevancy, toxicity, bias, non_advice, misuse, pii_leakage, role_violation and summarization, the conversation metrics turn_relevancy and conversation_completeness, which judge the request's conversation with the reply appended, the agent checks agent_loop_detection and tool_permission, the image scorers, and remote scorers that require no item field. The voice scorers are refused, since live traffic carries no recording. Scorers that need an expected answer, retrieval context, tools or expected tool calls are refused. Regex patterns are capped at 1000 characters and every regex match, online or offline, times out after 0.1 seconds instead of stalling a worker. Native scorers run on a small thread pool, never on the event loop that serves requests.
Before saving a rule you can try it on real logged requests, Lens traces or typed answers and preview its daily judge cost. Every save keeps a numbered version you can restore, a backfill scores past traffic with a saved rule, and the rule's verdicts can be compared with human reviewers. See evaluator operations.
Remote scorers on live traffic
A remote scorer on a rule is pinned to its registered revision when the rule is created and whenever scorers is sent in a PATCH, so a change to the scorer's URL, limits, required fields or self_hosted flag stops the rule from calling it until the rule is saved again. Each sampled request goes out as the usual signed request with source set to {"kind": "online", "rule_id": ..., "request_id": ...}, the request's conversation as the item input and the reply the caller received as output. That is what leaves the gateway: the messages as they were logged after the gateway's own redaction, the reply, and the model name, never keys, metadata or headers. A request whose messages are redacted from logging is never scored at all, so nothing is sent for it. A request that ran under any restricting data policy (zero data retention, no training, or restricted code traffic) or whose end user is pinned to a model region is sent only to a scorer registered with "self_hosted": true on a host listed in eval_self_hosted_scorer_hosts, and a request whose data policy cannot be read is never sent anywhere. Such a refusal is an error row on the request, so the counters show it.
A scorer whose concurrency cap is full sheds live requests at once with an error row instead of queueing them behind the slow scorer, while runs still wait for a slot. daily_remote_call_cap caps how many requests a day the rule sends to its remote scorers, and requests past it count as over_budget. When a rule's remote scorer is disabled, deleted or changed since the rule pinned it, each request gets a scorer unavailable error row and the gateway raises one eval_regression alert a day per rule and scorer from each replica. Disabling or deleting a remote scorer that an enabled rule uses is refused with 409, so pause the rule or remove the scorer from it first.
A rule with a judged scorer needs daily_judge_budget, in USD per UTC day. Judge calls run as the admin who created the rule and are labelled "spanway_eval": "online" with the rule id and the source request id in the spend log metadata, so they show up in spend and usage like other eval traffic. Before each judge call the gateway reads the rule's spend for the day from the same cross-replica counter key budgets use, and once it reaches the budget the judged scorers of that rule are skipped and counted as over budget while its native scorers keep scoring. The spend is read once before each metric starts, and one metric can make several judge calls. Metrics already running when the budget is crossed still finish, so a rule can overshoot its budget by up to ONLINE_EVAL_MAX_CONCURRENT_TASKS (32 by default) scoring tasks per replica times the cost of one metric. A judged rule that samples more than 10 percent of traffic also needs at least one match list. If the rule's creator is deleted or is no longer a proxy admin, its judged scorers record an error instead of calling the judge.
Every judge call carries the data policies of the request it scores, read from the request or recomputed from its key, team and organization, so a request that required zero data retention is never judged by a deployment that retains data. When the gateway labelled the request as code traffic, the judge call carries that label too, so a restrict_code_traffic policy limits the judge to the deployments it allowed for the request. A request whose policy cannot be determined is not judged, and that includes a request whose policy restricts code traffic when the gateway attached no policy to it, since its code traffic label is then unknown. Eval runs, scheduled runs, the playground, red team targets, shadow evaluations and every judge call are never scored, and neither are requests with message logging turned off. When response repair re-asks a model, only the reply the caller finally received is scored, and the correction turns are left out of the scored conversation. Anthropic Messages and Responses requests that a request-rewriting guardrail changed are counted as unscorable, because their logged conversation predates the guardrail. Chat completions are scored on the conversation after guardrails.
Each replica runs at most ONLINE_EVAL_MAX_CONCURRENT_TASKS scoring tasks at once, 32 by default, and buffers at most ONLINE_EVAL_MAX_BUFFERED_ROWS score rows, 10000 by default, between spend flushes. A sampled request that arrives while all of them are busy is shed and counted, never queued behind the others. Score rows and daily counters are written in bulk with the spend flush, so they appear a few seconds after the request. A score row keeps the score, the verdict, the judge cost and any error. The judge's reason is stored only while store_prompts_in_spend_logs is on, cut to 1000 characters, and the request and response text are never stored with the score.
| Route | What it does |
|---|---|
POST /eval/online/rules | Creates a rule. Returns 409 when the name is taken. |
GET /eval/online/rules | Lists rules, filterable by enabled, each with today's counters (scored, errors, not_sampled, shed, over_budget, unscorable) and judge spend. |
GET /eval/online/rules/{rule_id} | Returns one rule with today's counters. |
PATCH /eval/online/rules/{rule_id} | Changes the fields sent. scorers may only grow, existing scorers keep their position and type and only their settings may change, so their history stays comparable. Scorers are checked again only when scorers is sent, so a rule whose judge model is no longer served can still be paused. |
DELETE /eval/online/rules/{rule_id} | Deletes the rule and its counters. Its scores stop being listed. |
GET /eval/online/scores | Score rows newest first, filterable by request_id, rule_id, model_group, scorer_index, passed, start and end, at most 200 per call. |
GET /eval/online/summary | Per rule, model group and scorer, the scored and error counts, mean score, pass rate and judge cost per hour or day bucket between start and end. The span is capped at 31 days, and at 7 days for hour buckets. Error rows count only as errors. |
Rule changes reach every replica within 30 seconds, and the replica that served the change applies it at once. Nothing is scored while the gateway has no license. The run ledger also lists the online scores of each request in a run, without the judge's reason.
Every 5 minutes each replica checks the rules that have an alert. For every model group and scorer it compares the pass rate over the last window_minutes with the window before, and raises one eval_regression alert per rule, listing every regressed series, when a pass rate is under min_pass_rate or fell by more than regression_threshold. A series with fewer than min_scored scored requests in the window is too thin to alert on. One replica claims the alert, so it is sent once, and a rule alerts at most once per window. Every regressed series also lands in the alerts inbox as an eval_regression alert, even when no alerting destination is set up, where it can be acknowledged, assigned and resolved. See online evals and regression alerts.
Online scoring never scores a request whose content is redacted, which includes every request under zero data retention, and it keeps the judge's reason only when store_prompts_in_spend_logs is on. Scores, pass rates and judge costs work without stored prompts, as What Spanway stores explains.
Score rows are deleted by the spend log cleanup job once they are older than maximum_online_eval_score_retention_period, or older than maximum_spend_logs_retention_period when that is shorter, so a judge's reason never outlives the request it describes. With neither set, scores are kept.
curl -X POST "$SPANWAY_URL/eval/online/rules" \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
-d '{"name": "support refunds", "match": {"tags": ["support"]}, "sample_percentage": 5, "scorers": [{"type": "contains", "substrings": ["refund"]}]}'
curl "$SPANWAY_URL/eval/online/summary?start=2026-10-11T00:00:00Z&end=2026-10-18T00:00:00Z&bucket=day" \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY"
End-user feedback
An app can record what its users thought of a response without Lens. POST /eval/feedback takes the request_id of a gateway request as its spend log row and the Logs page show it, a score from 0 to 1, a label, or both, an optional comment of up to 2000 characters and an optional end_user, the app's own id for the person rating, which defaults to the request's logged end user. Any virtual key may call it, but only for requests sent with that key or another key of the same team. Every other request id answers 404, whether it exists or not, so a key cannot probe for other teams' traffic. Rating a request again for the same end user replaces the earlier rating, and different end users each keep their own. A request logged with an end user is rated only for that end user, so a different end_user answers 400. A request logged without one takes ratings from at most 20 end users, and a new one past that answers 409. When the rating key, its team or its organization requires zero data retention, the gateway drops the comment and keeps the score, label and ids.
Feedback needs spend logs. The gateway looks the request up in its spend log row, which the proxy writes in batches about ten seconds after the response, so rating a response the moment it arrives can answer 404. Retry a 404 a few times over about half a minute. A gateway with spend logs turned off cannot record feedback.
curl -X POST "$GATEWAY/eval/feedback" -H "Authorization: Bearer $APP_KEY" \
-H "Content-Type: application/json" \
-d '{"request_id": "req-123", "score": 0, "label": "wrong answer", "end_user": "user-42"}'
A rating belongs to the team and organization of the request, so GET /eval/feedback, narrowed by request_id or session_id, and DELETE /eval/feedback/{feedback_id} follow the ownership rules. The spend log filters of datasets from logs, datasets from sessions and review queues take has_feedback to keep only rated (or only unrated) requests and min_feedback_score and max_feedback_score to keep ratings in a range, so POST /eval/review/queues/{queue_id}/from_logs with max_feedback_score: 0.3 queues the responses users disliked for human review. These filters are applied in the same query as the time window and the caller's team or organization, so every rating counts. A data subject export includes the feedback recorded under the subject's id as end user, and erasing the subject deletes it. The spend log cleanup job deletes ratings older than maximum_eval_feedback_retention_period, or older than maximum_spend_logs_retention_period when that is shorter, so feedback never outlives the requests it rates.
Human review
People you assign can label eval results, sampled production responses and shadowed requests as pass or fail, and the calibration report shows how often each judge agrees with them. Labelled items export to a golden dataset. Human review and judge calibration covers queues, the reviewer workflow, calibration and who can see what.
Red teaming
A red-team run points the attack engine at one target_model. You choose the vulnerabilities to probe, for example bias, toxicity, PII leakage, prompt leakage, SQL or shell injection, SSRF, excessive agency, or the agent-specific classes such as role-based access abuse, and optionally the attack techniques, single-turn or multi-turn. GET /eval/redteam/catalogue lists both with descriptions. A simulator_model generates the attacks and an evaluation_model judges whether the target resisted. Both are gateway models.
POST /eval/redteam/runs starts the run and GET /eval/redteam/runs/{run_id} returns an overall pass rate plus a breakdown by vulnerability type and by attack, each listed lowest pass rate first. GET /eval/redteam/runs/{run_id}/results shows every attack prompt, the target's reply, and the judge's reason, so each finding can be reproduced and fixed with a guardrail or a system prompt change. Attacks reach the target through every guardrail that applies to the caller, as a real request would, and an attack a guardrail blocks is recorded as defended with a score of 1 and the reason that a guardrail blocked it, so the pass rate shows the protection your guardrails add. The attack simulator and the evaluator skip guardrails, because writing and judging attacks is their job, but their spend still counts against the caller's budgets.
Framework mapping
The run summary also has by_framework, which groups the results by the categories of the OWASP Top 10 for LLMs 2025 (LLM_01 to LLM_10), the OWASP Top 10 for Agentic Applications 2026 (ASI_01 to ASI_10), the NIST AI Risk Management Framework measure functions (measure_1 to measure_4), the six MITRE ATLAS tactics (reconnaissance to impact) and the EU AI Act Article 5 prohibited practices and Annex III high-risk areas. A result counts toward every category that lists its vulnerability type, so one finding can appear under several frameworks and several categories. Each entry has framework, category, a display name, total, passed and pass_rate, with errored cases counted in total only, and the Admin UI shows the same table on the run detail. Runs completed before this mapping existed have an empty by_framework. Every result and every run also carries a cvss_score with a severity word, scored by what the vulnerability type exposes and how easy the attack is, and every run and vulnerability type carries its worst finding as max_cvss_score with max_severity. The compliance report checks that a run has completed and that its worst finding is rated below high. Red team frameworks and severity explains both, with a scenario and the steps to follow.
{
"framework": "OWASP Top 10 for LLMs 2025",
"category": "LLM_02",
"name": "LLM02:2025 Sensitive Information Disclosure",
"total": 4,
"passed": 3,
"pass_rate": 0.75
}
Provider evals through the gateway
Some teams already grade with their model provider's own evals service and only want the gateway in front of it, so the calls use the gateway's provider accounts and show up in its logs. The /v1/evals routes do that. They pass the OpenAI-compatible evals API through to the provider unchanged, and they are separate from the gateway's own /eval runs above: the provider stores the evaluation, runs the graders and keeps the results, and nothing appears on the Evals page.
A data team that keeps its graders at OpenAI points its script at the gateway instead of the provider. Steps:
- Ask a proxy admin for a key. Only a proxy admin key may call these routes, or a key whose
allowed_routeslists the route. - Create the evaluation, then start a run on it, as the provider's API describes.
- Read the run and its results with
GET /v1/evals/{eval_id}/runs/{run_id}.
curl -X POST "$SPANWAY_URL/v1/evals" \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
-H "x-spanway-model: gpt-5.5" \
-d '{"name": "Support ticket labels", "data_source_config": {"type": "custom", "item_schema": {"type": "object", "properties": {"ticket": {"type": "string"}, "label": {"type": "string"}}}}, "testing_criteria": [{"type": "string_check", "name": "label matches", "input": "{{ sample.output_text }}", "reference": "{{ item.label }}", "operation": "eq"}]}'
The answer is the provider's evaluation object with its id. The routes are POST and GET /v1/evals, GET, POST and DELETE /v1/evals/{eval_id}, POST /v1/evals/{eval_id}/cancel, POST and GET /v1/evals/{eval_id}/runs and GET, POST and DELETE /v1/evals/{eval_id}/runs/{run_id}. The provider is OpenAI unless the custom_llm_provider query parameter names another, and the provider account comes from the gateway model named in the x-spanway-model header, the model query parameter or the model body field. They need no license. Errors are the provider's own, passed through in the gateway's error shape, and the gateway refuses a missing key, or a key that is not a proxy admin and does not list the route, with an authentication error before anything reaches the provider.
Permissions and audit
Proxy admins create, run and delete. Admin viewers read, including log previews, session previews, transcripts, schedules, online rules, online scores and shadow results. A custom role can be granted evals.read, which opens reading datasets, scorers, runs, results, transcripts, schedules, online scores and red team runs of the holder's team, or evals.write, which opens creating, importing, changing and deleting datasets and cancelling and deleting runs and red team runs. A role with only evals.read is refused on every write, including writes to paths it can read. Some routes stay with proxy admins whatever the custom role holds. Starting a run or a red team run, creating, changing, deleting or running a schedule, and creating, changing or deleting an online rule, stay there because eval traffic goes through the router without the caller key's model access checks, even though its budgets, rate limits and guardrails apply. CI keys are the exception, the gateway checks those for every run they start. The log and session previews and creating a dataset from logs or from sessions stay there because they read request bodies of every team. Remote scorers, the scorer dry run and the playground are proxy admin only, and no custom role permission opens them, since the playground sends completions through the router like a run. Comparing runs and reading a run's verdict are reads, open to admin viewers and to evals.read. A CI key can start runs on its allowlisted datasets and read, cancel and get the verdict of the runs it started, and nothing else, whatever role it carries. Dataset, run, red team run, schedule, online rule and remote scorer creation, changes, secret rotations, cancellation and deletion, and runs started with run_now, are written to the audit log with the acting user, never with a signing secret. The audit row of a dataset from sessions records the source, the number of sessions and the skipped counts, never message content. A cancel with a reason stores it as cancel_reason next to the run's fields. A run whose answers come from outside the gateway (outputs_source: submitted) writes updated on its run for every batch of answers, with the scored, error and already submitted counts and never the answers, and again when it is finished, with the run before and after. Deleting end-user feedback writes deleted on Spanway_EvalFeedback.
Some eval actions write no audit row on purpose. Recording end-user feedback with POST /eval/feedback is runtime data from the app's own users, kept with its key, team and time in the feedback table like a spend log row. Claiming, labelling and skipping a review item are kept with the reviewer and the time on the item itself, as Human review explains. In the Admin UI, open Logs, then the Audit Logs tab, and pick Eval datasets, Eval runs, Eval schedules, Remote scorers, Online eval rules, Eval feedback, Review queues or Red team runs in the Table filter to see these rows.
Ownership
Every dataset, run, schedule, red team run and review queue has an owner. Proxy admins and admin viewers act for the operator, and anyone else who reaches an eval route, custom role holders and CI keys included, acts for the team of the key they call with. Org admins are refused by the eval routes unless a custom role lets them in, and then act for their organization. A key with neither a team nor an organization is refused with a 403. What a caller creates is owned by its team or organization, or by the operator when an admin creates it, and a scheduled run, a dataset a schedule draws from logs and the results of a run belong to the owner of the schedule or run. The operator sees and changes everything. A team sees only its own objects, an organization sees its own and those of its teams, and anything else answers 404 exactly like a missing id, so ids never leak between teams. Dataset and schedule names are unique per owner, so two teams can each have a nightly schedule. A team or organization that draws a dataset from spend logs or sessions only ever reads its own rows, and asking for another team's rows is a 400. A CI key can run its own team's datasets and the operator's datasets on its allowlist, never another team's, and its baseline is looked up among its own team's runs. Runs created before ownership existed, CI runs aside, belong to the operator, and so do review queues created before they had an owner.
Online rules, online score summaries and shadow results cover every team on the gateway, so only proxy admins and admin viewers can read them, and a custom role holder gets a 403. A custom role holder acting for a team reads only the online scores of that team's requests, and one acting for an organization is refused. A review queue belongs to the team that created it, so another team's custom role holder can neither list, read, change, fill nor export it. Reviewers are not affected, they work from the queues that name them.
Admin UI
The Evals page sits under Developer Tools and has nine tabs. It needs a license that includes evals, and without one it shows which feature to add. Proxy admins and admin viewers see every tab. A custom role holder who opens the page sees the Datasets, Runs, Schedules, Review, Feedback and Red team tabs for their own team, and a role the server refuses is told to ask for evals.read. The Review page for reviewers needs the same license. Datasets lists and creates datasets and shows their items and their versions, where an earlier version's items can be read and the version deleted, conversations turn by turn, and its From logs button previews spend logs with the filters above and samples them into a dataset. From sessions takes pasted session ids or Lens trace ids, previews the conversations with their turn and tool call counts and what would be skipped, and creates the dataset. Runs starts comparisons in any mode, optionally through a managed prompt or a template with sampling params, polls them while they are active, and opens a detail view with the per-model summary and the filterable results, where opening a row of a conversational run loads its transcript with every tool call, its result, any call no fixture answered, and a link to the run ledger. Scorers registers remote scorers, shows the signing secret once, rotates it, enables, disables and deletes them, and dry-runs any scorer against one output. Picking the remote scorer type in a run or schedule offers the enabled remote scorers. Schedules manages scheduled runs and shows each one's last run and regression verdict. Online manages online rules with today's counters and judge spend, offers only the scorers live traffic can use, warns when a judged rule samples every request, keeps saved scorers in place when a rule is edited, and shows a rule's pass rate, mean score, errors and judge cost per model group and scorer over the last 7 days. The log drawer of a scored request lists its online scores. A model's page shows its online pass rate, errors and judge cost per rule and scorer over the last 7 days, and the Model Leaderboard shows the same for every model group. Both stay hidden until something has been scored. Shadow lists shadow evaluation verdicts. Feedback lists end-user ratings, narrowed to one request or session, and lets a proxy admin delete one. Review manages human review queues, see Human review: create a queue with its reviewers and labels per item, fill it from a run, from logs or from shadow results, read and delete items, open one item with what reviewers saw and their labels, delete an item, check calibration against the scorer, and export the agreed labels to a dataset. Red team does the same as Runs for vulnerability scans.
The Runs tab has three views. Runs is the list above. Compare picks a dataset and two to four arms, or opens from the Compare button on a run to set its models side by side. It also opens from the runs list, where ticking two to four runs of one dataset and one mode enables Compare and makes every model of those runs an arm, as long as that comes to four arms or fewer. It shows per-arm metrics with signed deltas, the warnings, and the items with filters, sorting and paging. Opening an item shows each arm's output with the words that changed from the baseline marked. The arms are kept in the URL, so a comparison can be shared as a link. Playground, shown to proxy admins only, picks a dataset, a sample with its seed, up to three models, a blank template or a managed prompt, sampling params and an optional scorer, counts pairs against the limit of 30, and shows the outputs in a grid with what the first item was sent as. Pin as baseline keeps the current results and shows each later result's score change against them, in the browser only. Save as run opens the new run form with the same setup, which then runs on every item of the dataset.
Errors
Eval routes answer errors as {"detail": {"error": "<message>"}}.
| Status | Message | Meaning and fix |
|---|---|---|
| 403 | The 'evals' feature needs a Spanway enterprise license. You must be a Spanway Enterprise user to use this feature. ... | The gateway has no valid Enterprise license. Set SPANWAY_LICENSE. |
| 403 | Your Spanway license does not include the 'evals' feature. Contact sales@spanway.ai to add it. | The license is valid but lacks evals. Add the feature to the license. |
| 403 | Only proxy admins can read this resource or Only proxy admins can change this resource | A viewer tried a write, a custom role lacks evals.read or evals.write, or the route is for proxy admins only, see Permissions and audit. |
| 422 | Value error, send exactly one of dataset_id and dataset_name | Name the dataset one way only. |
| 400 | models needs at least one model, or a logged run scores the stored conversations, so it takes no models | Match the models to the mode. |
| 400 | A scorer message such as contains needs substrings or an expected output on the item | The scorer settings or the items lack what it reads. Fix the scorer or the items. |
| 404 | dataset_id=<id> not found, run_id=<id> not found, dataset <id> has no version <n> | The id is wrong or belongs to another team, which answers 404 like a missing id. |
| 409 | a dataset named '<name>' already exists | Names are unique per owner. Choose another name. |
| 409 | A version or scorer is still in use | The current dataset version, a version a running run uses, or a remote scorer an active run or rule uses cannot be deleted. Wait for the run or cancel it. |
| 429 | playground is busy | The replica already runs four playground requests. Retry shortly. |
| 500 | DB not connected | Set DATABASE_URL. |
| 501 | Lens is not configured on this proxy, set SPANWAY_LENS_URL | Datasets from Lens traces need Lens. |
| 400 | red teaming needs the evals extra installed on the proxy | Starting a red team run on a gateway image without the optional eval components. Use an image that includes them, see red team errors. |
| 400 | scorer <type> needs the evals extra installed on the proxy | A run, schedule or online rule uses a judged metric on a gateway image without the optional eval components. Use an image that includes them, or pick a native scorer such as contains. |
| 400 | self_hosted needs <host> in general_settings.eval_self_hosted_scorer_hosts | A remote scorer was registered with "self_hosted": true on a host the operator has not listed. Add the host to eval_self_hosted_scorer_hosts, or register it without self_hosted. |
| 501 | synthetic datasets need the evals extra installed on the proxy | Synthetic datasets from documents need the optional eval components. Use an image that includes them. |
| 502 | The generation failure, for example the model produced no usable items | The model that writes synthetic items failed or wrote nothing usable. Try another model or other documents. |
| 500 | no models are configured on the proxy | Synthetic datasets and red team runs need at least one model. Add one in Models + Endpoints. |
Related
Logs
| Level | Line | Meaning |
|---|---|---|
| INFO | evals: fired <n> scheduled run(s) | The schedule job started the runs that were due. Normal. |
| WARNING | evals: schedule <id> disabled, <reason> | A schedule turned itself off, for example because its dataset or scorer is gone. Fix what the reason names and turn the schedule on again. Action needed. |
| WARNING | evals: schedule <id> skipped, <reason> | One fire was skipped, for example because the previous run is still active. Normal once, look into it when it repeats. |
| WARNING | online scoring: rule refresh failed, keeping the last rules | A replica could not reload the online rules from the database and keeps scoring with the rules it had. Check the database connection. |
| WARNING | online scoring: judge spend counter failed for <rule_id>: <error> or online scoring: unavailable counter failed for <rule_id>: <error> | A replica could not update a shared online scoring counter, so a judged rule can pass its daily budget a little later than it should. Check Redis. |
Every line comes from the gateway's normal log at the level shown, and none of them carries prompt or answer text.
Related
- Evals page for every control of the Admin UI.
- Gating pull requests on evals to block a merge on a failing run.
- Human review and judge calibration to label results by hand.
- Shadow evals to score a candidate auto router against live traffic.
- Error reference for errors outside the eval routes.