Reference
Python SDK
pip install synaptra-sdk: connect a harness, register its tools, report runs, follow long runs live and cap their spend. Standard library only, Python 3.9+, so it runs anywhere Python does. Using TypeScript? See the TypeScript SDK.
Install and connect
pip install synaptra-sdk
export SYNAPTRA_TOKEN=syn_... # from Connect → API tokensnpm install synaptra-sdk
export SYNAPTRA_TOKEN=syn_... # from Connect → API tokensimport os
from synaptra_sdk import Harness
h = Harness.connect("support-bot", url="https://synaptra.my",
token=os.environ["SYNAPTRA_TOKEN"])
print(h.next_step)import { Harness } from "synaptra-sdk";
const h = await Harness.connect("support-bot", {
url: "https://synaptra.my",
token: process.env.SYNAPTRA_TOKEN,
});
console.log(await h.nextStep);url falls back to SYNAPTRA_URL, then https://synaptra.my. Give the site, not the API: a trailing /api is accepted and dropped, since every path carries it. token falls back to SYNAPTRA_TOKEN: an API token from Connect → API tokens. Plain http is refused except to localhost (set SYNAPTRA_ALLOW_HTTP=1 for a private network), and redirects are never followed, so the token can't be carried elsewhere.
Harness
| Call | Does |
|---|---|
Harness.create(name, description="", objective="", metric="score", direction="max", bar=None, template=None, id=None, url=None, token=None, *, max_cost_usd=None) | A new harness from the Synaptra base harness. direction: max or min; template: harness, llm_agent or pipeline; max_cost_usd caps the harness's recorded spend. |
Harness.connect(id, url=None, token=None) | An existing harness. |
h.refresh() | Reads the harness again; returns its data. |
h.readiness | The readiness checklist (scorer, test set, runner, bar, baseline, first closed experiment), read fresh. |
h.next_step | What to do next, in a sentence, read fresh. |
h.tools(include_removed=False) | The registered tools and hooks. |
h.versions() | Every version, each with its spec (every page). |
h.export() | The harness as portable JSON (synaptra.harness/1). |
h.set_status("parked" | "active") | Parks the harness or makes it active again. |
Registering
| Call | Does |
|---|---|
@h.tool or @h.tool(name=None, description=None, schema=None, config=None) | Registers a function as an action tool. Schema from the signature, description from the docstring. |
@h.scorer | Registers the scorer: what turns one output into the metric. It runs on your side. |
h.dataset(name="test_set", path=None, items=None, size=None, *, description="", config=None) | Registers the test set. With items, its size and SHA-256 fingerprint are sent; the items never are. |
h.runner(cmd) | Registers the run command, with {variant}, {tier}, {task} placeholders. Recorded, never run. |
h.register(name, kind, description="", schema=None, config=None) | Registers anything: kind action, scorer, dataset or runner. |
h.remove_tool(tool_id) | Soft-removes a tool: it stays on record. |
@h.tool
def kb_search(query: str, k: int = 5) -> list:
"""Search the help centre and return the top k articles."""
...
@h.scorer
def exact(output: str, expected: str) -> float:
return float(output.strip() == expected.strip())
h.dataset("golden", items=golden_rows) # sends size + fingerprint only
h.runner("python eval.py --variant {variant} --tier {tier}")await h.tool(
{
name: "kb_search",
description: "Search the help centre and return the top k articles.",
schema: {
type: "object",
properties: { query: { type: "string" }, k: { type: "integer", default: 5 } },
required: ["query"],
},
},
kbSearch,
);
await h.scorer({ name: "exact" }, ({ output, expected }) => Number(output.trim() === expected.trim()));
await h.dataset("golden", { items: goldenRows }); // sends size + fingerprint only
await h.runner("node eval.js --variant {variant} --tier {tier}");The loop
| Call | Does |
|---|---|
h.propose(title, variant, predictions, hypothesis, *, treatment_axes=None, max_cost_usd=None, idempotency_key=None) | Opens an experiment with the numbers you expect per tier, before anything runs. hypothesis is required: what you expect the change to do, and why. Returns the experiment (its id). |
h.gate(variant, tier, n_runs=None, experiment_id=None) | May variant run on tier now? allowed, reasons, warnings, estimated_cost_usd, passes_own_gate, budget. A refusal is an answer, not an error. |
h.report(rows, experiment_id=None, variant=None, tier=None, *, idempotency_key=None, batch_size=250) | Sends rows in batches of 250, each with its own Idempotency-Key, so a retried report never counts twice. See Reporting runs. |
h.close(experiment_id, decision, note, variant=None, override_reason=None, *, idempotency_key=None) | adopt, iterate, reject or kill, with a note saying why (required). Returns {experiment, harness_version} (the new version on adopt, else None). Raises GateRefused when the adopted variant fails its gate. |
e = h.propose("Search before answering", "search-first",
{"T0": {"pass_rate": 1.0}, "T1": {"mean_resolved": 0.78}},
hypothesis="Replies miss policy details the help centre has",
max_cost_usd=5)
gate = h.gate("search-first", "T1", n_runs=60, experiment_id=e["id"])
if gate["allowed"]:
h.report(run_t1("search-first"), experiment_id=e["id"], variant="search-first", tier="T1")
out = h.close(e["id"], "adopt", note="Beat the incumbent on the dev set and the held-out test set")
print(out["harness_version"])const e = await h.propose({
title: "Search before answering",
variant: "search-first",
hypothesis: "Replies miss policy details the help centre has",
predictions: { T0: { pass_rate: 1.0 }, T1: { mean_resolved: 0.78 } },
maxCostUsd: 5,
});
const gate = await h.gate({ variant: "search-first", tier: "T1", nRuns: 60, experimentId: e.id });
if (gate.allowed)
await h.report(await runT1("search-first"), { experimentId: e.id, variant: "search-first", tier: "T1" });
const { harnessVersion } = await h.close({
experimentId: e.id,
decision: "adopt",
note: "Beat the incumbent on the dev set and the held-out test set",
});
console.log(harnessVersion);Reporting runs
h.report(rows, experiment_id=None, variant=None, tier=None) sends rows back. Each row is a dict:
| Field | Required | Meaning |
|---|---|---|
task | yes | The task's id in your test set. |
metrics | yes | e.g. {"accuracy": 1.0}. Must include the harness's metric. |
variant, tier | yes (or as arguments) | Which variant ran, on which tier. |
cost_usd, seconds | no | What it cost and how long it took, in seconds. |
status | no | ok, invalid (the harness broke: not a fail) or provisional (still resolving). |
meta | no | Anything else; meta.axes tags draws (e.g. {"seed": 2}). The SDK adds the host, the Python version and the client version. |
rows = [{"task": t.id, "metrics": {"accuracy": score(t)}, "cost_usd": t.cost,
"meta": {"axes": {"seed": seed}}} for t in results]
h.report(rows, experiment_id=42, variant="prompt-v2", tier="T1",
idempotency_key=f"exp42-prompt-v2-T1-seed{seed}")const rows = results.map((t) => ({
task: t.id, metrics: { accuracy: score(t) }, cost_usd: t.cost, meta: { axes: { seed } },
}));
await h.report(rows, { experimentId: 42, variant: "prompt-v2", tier: "T1",
idempotencyKey: `exp42-prompt-v2-T1-seed${seed}` });- Batching. Rows go 250 per request (the API takes at most 5,000). With one batch you get the API's answer as is; with several,
{"batches": [...]}. - Idempotency. Every write (
POST,PATCH,DELETE) carries anIdempotency-Keythat stays the same across the client's retries. Passidempotency_keyto make a report safe to retry from another process too: batch n of several uses<key>-<n>. The same key with different rows is409 CONFLICT.
Live runs and metering
Two companions, also standard-library only: track logs metrics from inside a long run so you can follow it live and stop it early, and Meter caps spending while a run happens.
from synaptra_sdk import track
from synaptra_sdk.meter import Meter, BudgetExceeded
with track.init("support-bot", name="prompt-v2 T1", experiment_id=42,
alerts=[{"metric": "loss", "rises_for": 5, "stop": True}]) as run, \
Meter(experiment_id=42) as m: # cap = the experiment's max_cost_usd
for step, batch in enumerate(batches):
m.allow(0.02) # refuse a call that would cross the cap
loss = train_step(batch)
m.charge(0.018, item="step")
run.log({"loss": loss}, step=step)
if run.should_stop():
breakimport { track, Meter } from "synaptra-sdk";
await using run = await track.init({ harnessId: "support-bot", name: "prompt-v2 T1", experimentId: 42,
alerts: [{ metric: "loss", rises_for: 5, stop: true }] });
await using m = await Meter.open({ experimentId: 42 }); // cap = the experiment's max_cost_usd
for (const [step, batch] of batches.entries()) {
m.allow(0.02); // refuse a call that would cross the cap
const loss = await trainStep(batch);
m.charge(0.018, { item: "step" });
run.log({ loss }, { step });
if (run.shouldStop()) break;
}run.log()never waits for the network: records are sent every few seconds and when the run ends. A NaN or infinite value stops the run; so do your alert rules with"stop": True.- Someone can stop a run from the app, or with
track.stop(run_id, reason): the reason is required.run.should_stop()turns true once the request reaches the run. m.allow(est)refuses a call before it's made: the hard stop.m.charge(usd)records money spent and raisesBudgetExceededonce the total crosses the cap.m.charge_tokens(model, tokens_in, tokens_out)prices a call fromprices. Report the runs afterwards withcost_usd0: the meter already counted it.- If Synaptra can't be reached, records and spend totals wait in
~/.synaptra/buffer(SYNAPTRA_BUFFER_DIR) and go later withsynaptra_sdk.flush()orpython -m synaptra_sdk flush.python -m synaptra_sdk whoamichecks a token.
Required fields
Three things are refused before anything is sent (ValueError), because the record is worthless without them: a hypothesis on propose, a note on close, and a reason on track.stop.
Errors
Calls raise HarnessClientError or a subclass, with the HTTP status (.status), the API's code (.code) and its plain-language .detail. Branch on the class and show detail to people.
| Class | Status and code | When |
|---|---|---|
BadRequestError | 400 BAD_REQUEST | The body or a parameter is wrong. Fix the request. |
AuthError | 401 UNAUTHORIZED, 403 FORBIDDEN | No token, or a revoked or wrong one. |
NotFoundError | 404 NOT_FOUND | No such harness, experiment or run in this workspace. |
GateRefused (a ConflictError) | 409 GATE | The adopted variant fails its gate; detail gives the reasons. |
ConflictError | 409 CONFLICT | It exists already, or an Idempotency-Key was reused with a different body. |
QuotaError | 429 QUOTA | A quota is full. .retry_after (seconds) is set only when waiting helps, e.g. the daily run quota. |
RateLimitError (a QuotaError) | 429 RATE_LIMITED | Too many requests this minute, still refused after the retries. |
ServerError | 5xx INTERNAL | Something broke on our side, still failing after the retries. |
SynaptraConnectionError | none (.status is None) | Synaptra couldn't be reached. |
Rate limits (429 RATE_LIMITED), server errors and network errors are retried first, with backoff, honouring Retry-After and keeping the same Idempotency-Key, so a retried write never counts twice. The error is raised only when the retries run out. A 429 QUOTA is raised at once unless its Retry-After is within the client's longest wait (60 seconds): a per-day quota frees up at midnight UTC, which is your call, not a sleep inside a request. The token is never logged or put in an error message. See Errors and rate limits.
Something unclear or missing? Email support@synaptra.my.