SynaptraDocs

    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

    Terminal
    pip install synaptra-sdk
    export SYNAPTRA_TOKEN=syn_...   # from Connect → API tokens
    Terminal
    npm install synaptra-sdk
    export SYNAPTRA_TOKEN=syn_...   # from Connect → API tokens
    connect.py
    import os
    from synaptra_sdk import Harness
    
    h = Harness.connect("support-bot", url="https://synaptra.my",
                        token=os.environ["SYNAPTRA_TOKEN"])
    print(h.next_step)
    connect.ts
    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

    CallDoes
    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.readinessThe readiness checklist (scorer, test set, runner, bar, baseline, first closed experiment), read fresh.
    h.next_stepWhat 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

    CallDoes
    @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.scorerRegisters 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.
    Python
    @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}")
    TypeScript
    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

    CallDoes
    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.
    Python
    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"])
    TypeScript
    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:

    FieldRequiredMeaning
    taskyesThe task's id in your test set.
    metricsyese.g. {"accuracy": 1.0}. Must include the harness's metric.
    variant, tieryes (or as arguments)Which variant ran, on which tier.
    cost_usd, secondsnoWhat it cost and how long it took, in seconds.
    statusnook, invalid (the harness broke: not a fail) or provisional (still resolving).
    metanoAnything else; meta.axes tags draws (e.g. {"seed": 2}). The SDK adds the host, the Python version and the client version.
    Python
    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}")
    TypeScript
    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 an Idempotency-Key that stays the same across the client's retries. Pass idempotency_key to make a report safe to retry from another process too: batch n of several uses <key>-<n>. The same key with different rows is 409 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.

    Python
    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():
                break
    TypeScript
    import { 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 raises BudgetExceeded once the total crosses the cap. m.charge_tokens(model, tokens_in, tokens_out) prices a call from prices. Report the runs afterwards with cost_usd 0: 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 with synaptra_sdk.flush() or python -m synaptra_sdk flush. python -m synaptra_sdk whoami checks 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.

    ClassStatus and codeWhen
    BadRequestError400 BAD_REQUESTThe body or a parameter is wrong. Fix the request.
    AuthError401 UNAUTHORIZED, 403 FORBIDDENNo token, or a revoked or wrong one.
    NotFoundError404 NOT_FOUNDNo such harness, experiment or run in this workspace.
    GateRefused (a ConflictError)409 GATEThe adopted variant fails its gate; detail gives the reasons.
    ConflictError409 CONFLICTIt exists already, or an Idempotency-Key was reused with a different body.
    QuotaError429 QUOTAA quota is full. .retry_after (seconds) is set only when waiting helps, e.g. the daily run quota.
    RateLimitError (a QuotaError)429 RATE_LIMITEDToo many requests this minute, still refused after the retries.
    ServerError5xx INTERNALSomething broke on our side, still failing after the retries.
    SynaptraConnectionErrornone (.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.