Python SDK
Run benchmarks, compare models and read results from Python 3.12 or 3.13. The SDK is the evalrouter-sdk package. It depends only on httpx and pydantic and has no terminal interface. The command line is a separate package that installs the same SDK version.
On this page
python -m pip install evalrouter-sdkfrom evalrouter import EvalRouter
client = EvalRouter() # EVALROUTER_API_KEY and EVALROUTER_BASE_URL from the environment
run = client.runs.create(benchmark="gsm8k", model="gpt-5", max_cost=5, wait=True)
print(run.score)The async client, AsyncEvalRouter, has the same calls, awaited. The client's benchmark and model lists read the catalog.
Upgrade from 0.4#
From 0.5.0 the SDK is evalrouter-sdk and the evalrouter package is the command line only. The API refuses 0.4.x clients with HTTP 426 and the upgrade command.
| Where the SDK is installed | Upgrade |
|---|---|
| An environment with pip | pip |
| A uv-created environment (no pip) | uv |
| A uv project | uv |
| The CLI as a uv tool | uv tool upgrade evalrouter |
Then depend on evalrouter-sdk in your requirements. Upgrading only evalrouter-sdk in place leaves the old 0.4 command line behind, broken.
Run a benchmark#
- Names, not IDs. The benchmark and model take a slug or an unambiguous name, and
"gsm8k@2"pins a version. Exact IDs work too. max_costis the run's spending cap in USD. New work stops when the cap or your balance can't fund the next call; calls already running finish and are charged. EvalRouter refuses the run before it starts only when the cap is below the quote's minimum cap. Without it, your wallet balance limits the run.wait=Truereturns the finished run. Without it, wait later withrun.wait().- Idempotent. Repeating a create never starts a second run.
Several models in one run#
run = client.runs.create(benchmark="gsm8k", subjects=["gpt-5", "claude-sonnet-5"], wait=True)
ranking = run.compare()The subjects list runs two to eight models on the same tasks with one spending cap, or your wallet. Each name resolves like a single model. The comparison ranks the models on the tasks every model finished:
| Field | Meaning |
|---|---|
profile_id, metric, tasks_compared | What was compared |
| Per model | Rank (1= for a tie), score and 95% interval |
summary | The top two as one line |
pairs | Every pairwise difference |
A run that stopped early (cap reached, out of credit or cancelled) carries the reason in run.interruption. Continuing it with run.continue_() prices only its unfinished tasks and starts the run that completes it, reusing finished ones at no charge. A dry run returns that quote first.
Quote, then start#
Use a quote when a person or application reviews the cost first:
quote = client.runs.create(benchmark="gsm8k", model="gpt-5", max_cost=5, dry_run=True)
# Review the quote's spending cap and plan. Nothing has started.
run = client.runs.create(quote_id=quote.id, max_cost=5)
run = client.runs.wait(run.id, timeout=3600)
result = client.runs.results(run.id)To build the request yourself, client.quotes.create(body) takes the same body as the quotes endpoint. Its max_charge_microusd is in micro-USD (1 USD = 1,000,000), so "1000000" is $1. The convenience parameters max_cost and budget_usd take USD. Waiting is polling. A local timeout raises WaitTimeout and never cancels the server work, so read the run, or cancel it explicitly, before starting another.
Evaluate an agent on your machine#
The agents module runs your agent locally. EvalRouter does four things for each task:
- It delivers the task.
- It meters every model call through the run's gateway (managed models only).
- It grades the submission with the benchmark's own grader.
- It records the trajectory.
The agent can be:
- an ACP Registry agent,
registry_agent("opencode") - a local ACP command,
local_agent("my-agent, which needs the--acp") evalrouter-sdk[agents]extra - an agent written in Python:
from evalrouter import EvalRouter, agents
class Solver(agents.Agent):
name = "my solver"
async def run(self, context):
task = await context.task.get()
reply = await context.gateway.chat(messages=task["inputs"]["messages"])
await context.task.submit(reply["choices"][0]["message"]["content"])
await context.task.done()
client = EvalRouter()
evaluation = agents.quote(
client,
agent=Solver(),
model="ADMITTED_ROUTE_ID",
tasks=agents.benchmark("eval://PROVIDER/NAME/VERSION"),
coverage={"mode": "sample", "sample_count": 3, "seed": 42},
budget_usd="2",
)
# Review evaluation.quote before starting; nothing is charged until start().
run = evaluation.start()
for event in run.events(): # or: async for event in run.events_async()
print(event.type, event.task_ref, event.failure_code or "")
print(run.wait()["status"], run.results())One call, agents.evaluate(...), does all of this. Its result reports whether the run succeeded. A failed, partial or abandoned run comes back marked unsuccessful, as a wait returns it, and is not raised. The CLI's agent runs use the same functions and exit 0 only for a completed run (1 when it failed, 4 otherwise).
Tasks, context and resuming
| Source of tasks | Call |
|---|---|
| A benchmark | agents.benchmark(REF) |
| An environment version | agents. |
| A private benchmark | agents.private_benchmark(ID) |
| A suite | A saved suite version |
| Context | What it does |
|---|---|
context.task.get() | Read the task |
context.task.submit(...) | Submit the answer text, or nothing for file and repository tasks, whose files or diff are collected from context.workspace |
context.task.done() | Finish the task |
context.tools.list(), context.tools.call(...) | List and call every task tool |
context.gateway | OpenAI chat-compatible. gateway.openai() returns an AsyncOpenAI client when openai is installed. |
| Run control | What it does |
|---|---|
| Leaving the event loop early | Finishes the attempt in flight as an interrupted controller |
agents. | Continues the run with the same agent |
run.cancel() | Stops the run |
run.costs(), run.export("csv"), run.trajectories() | Read the finalized results |
agents. | Compare finalized runs |
Agent traces
Each attempt's trace is one span tree: the agent, the model turns and the tool calls each turn requested. The SDK sends it while the attempt runs, about every half second. The SDK records gateway calls and task tool calls automatically.
| Add to the trace | Call |
|---|---|
| Your own spans | with |
| Checkpoints | context. |
| Test results | context., optionally split SWE-bench style with groups= |
| Command results | context. |
| An OpenTelemetry framework (LangGraph or the OpenAI Agents SDK, through OpenInference, OpenLLMetry or the GenAI conventions) | provider. |
| LangGraph checkpoints | context. |
Choose what the trace records with a trace= argument when quoting or evaluating. It takes a level and the kinds to include:
| Level | Records |
|---|---|
off | Nothing |
metadata | Agent spans with their counts and results only |
spans (default) | The tree, metadata only |
content | Also tool inputs and outputs, agent messages and file diffs, with secrets redacted and each field bounded to 8 KiB, in the SDK and again on the server |
By default the trace includes every kind:
model_turns,tool_calls,command_outputfile_diffs,agent_messages
Where the platform turns content off, the API refuses a content-level quote with client_trace_level_unavailable. Add your own redaction patterns with trace_redact=[r"acct-\d+"] when executing. They never leave your machine. The CLI takes the same choices as trace level, include and redact flags.
Import OpenTelemetry traces (preview)
Available from the first release after 0.5.3. Upload traces you already exported with OpenTelemetry into a trace source. Each trace comes back stored, unchanged or rejected with a code. See Import OpenTelemetry files for formats, limits and codes.
| Import | Call |
|---|---|
| Files and folders, plain or gzip, grouped by trace and split into requests for you | client. |
| One OTLP JSON request (at most 20 traces and 10,000 spans) | client. |
import_otlp_file returns a dict with stored, unchanged, rejected, traces, files_read, files_skipped and file_errors. Running it again is safe: traces already stored come back unchanged.
Names, progress and reports#
The SDK resolves the same names the command line accepts, without prompting:
bench = client.benchmarks.resolve_benchmark("gpqa-diamond")
model = client.benchmarks.resolve_model("ADMITTED_MODEL_NAME", benchmark=bench)- The benchmark resolver returns the one quotable version for a slug, display name,
slug@version, eval reference or private benchmark ID. - The model resolver returns the quote's model body for a route ID, model name or connection, matching only models that benchmark version can run.
- Several matches raise
ambiguous_benchmarkorambiguous_model, and the message lists them. Use the exact slug or route ID. No match raisesbenchmark_not_foundormodel_not_found. A model the benchmark refuses raises the API's refusal code.
Following a run yields its events in order until the run ends. It retries transient API failures and only reads, so stopping the loop never cancels the run. Pass after= the last sequence you processed to resume without gaps, and ignore event types you don't recognise.
for event in client.runs.follow(run_id):
print(event["sequence"], event["type"])
print(client.runs.report_url(run_id))The report link comes from the web_url= argument, the EVALROUTER_WEB_URL variable or the API address, and is empty when unknown. Charts are drawn by the web app and the command line. The SDK returns the data behind them (results, comparisons and exports), so plot it with your own library if you need a picture in code.
Stability tiers
Stable resources keep their behaviour within a major version. Preview resources ship in the same package but are outside that promise. Any release may change or remove them. Each preview method says so in its docstring.
| Tier | Groups |
|---|---|
| Stable | benchmarks (with uploads, imports, private, evals and environments), models, connections, quotes, runs (with events, attempts and samples), comparisons, result_groups, api_keys, workspaces, account, wallet, agents (the ACP Registry agents you can run, read offline), feedback (report bugs and missing features) |
| Preview | recommendations, releases, suites, traces, trace_integrations, trace_discovery, datasets, schedules, tune, tune_monitors, improvements, remote_scorers, workload_evaluators, and individually marked methods on runs |
Errors and retries#
Read an error's code and status, not its human-readable message. Every error derives from EvalRouterError.
| Error | When |
|---|---|
APIStatusError subclasses | HTTP failures: BadRequestError, AuthenticationError, PaymentRequiredError, PermissionDeniedError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError, InternalServerError |
APIConnectionError, APITimeoutError | Transport failures |
ClientUpgradeRequired | HTTP 426 for a release the API no longer serves. Its upgrade is the command to run. |
When a response marks an operation as deprecated (with a Deprecation or Sunset header), the SDK warns once per process. It retries supported reads and idempotent submission and cancellation requests. It never blindly repeats quote creation, connection verification or other side effects.
Use the preview traces group for capture settings and scoring. Use the types shipped with your pinned release and the OpenAPI schema for exact payload limits. See Save traces to a dataset for capture.