CALIBER
Quickstart
Build & integrate

CALIBER Python SDK

Install, authenticate, scope to a project, and call the management API from Python — with every snippet taken from the executable examples the SDK test suite runs.

DeveloperTutorialGA
PrerequisitesPython 3.10+
Reviewed 2026-10-15 · current main branch docs contract

caliber-sdk is a typed Python client for the CALIBER management API. Installing it does not install the CALIBER server — no mlflow, no sqlalchemy, no starlette. That isolation is the reason it is a separate distribution, and CI fails the build if a server dependency ever appears in the wheel metadata.

Every code block on this page is extracted from sdk/caliber-sdk/examples/ at build time. The SDK test suite executes those functions, so a snippet here cannot drift from working code: if a signature changes, either the docs change with it or the build fails.

This page explains the Python abstraction. If you need the raw wire contract, use the REST API overview, the authentication and conventions guide, and the HTTP reference.

At a glance

DimensionWhere the SDK stands
Runtime dependencieshttpx and typing-extensions. Nothing else.
TypingShips py.typed; mypy --strict clean.
AuthPersonal access token (recommended), or a trusted-proxy header.
ErrorsNon-2xx becomes a typed exception carrying status, detail, method, URL, and a request id.
RetriesIdempotent methods only (GET, HEAD, OPTIONS), on a transport error or a 429, 502, 503 or 504. Two retries by default (max_retries), exponential backoff, honouring a numeric Retry-After.
Long-running workWaiters that poll with backoff and never sleep past your deadline.
CoverageEvery GA surface, plus client.raw for anything not yet modelled.
Project accessTyped client.projects.list_members(), add_member(), update_member(), and remove_member() methods.

Install

The packages are not on PyPI yet. Install them from the 0.1.0a1 release wheels (the Alpha install page says where to get them), into a virtual environment:

pip install --find-links ./wheels caliber-sdk

--find-links points pip at the directory holding the downloaded wheels. Installing from an index by name finds nothing until the packages are published.

Quickstart

Construct a client, confirm who you are, and read what the deployment supports:

def quickstart(caliber: CaliberClient) -> dict[str, Any]:
    """Report who you are and which API surfaces are GA on this deployment."""
    identity = caliber.me.get()
    if identity.is_anonymous:
        # /me answers "who am I" rather than requiring a credential, so an
        # invalid token shows up here as anonymous instead of an exception.
        raise SystemExit("no usable credential — check CALIBER_TOKEN")

    capabilities = caliber.capabilities_info.get()
    return {
        "user_id": identity.user_id,
        "scopes": identity.scopes,
        "ga_surfaces": sorted(capabilities.sdk_stability.get("ga", [])),
        "queue_enabled": capabilities.workflow_runs.queue_enabled,
    }
From sdk/caliber-sdk/examples/quickstart.py — executed by the SDK test suite.

Two things worth noticing. me.get() reports identity rather than requiring it — an invalid or revoked credential comes back as an anonymous identity, not an exception — so the check is on the value, not a try. And capabilities answers "may I call this?" without downloading the full OpenAPI document.

client.health() and client.readiness() are the liveness and dependency probes. /health is the one route with a bare body (status, version, db), so health() returns it as is; it never carries a data wrapper to strip. Both raise a CaliberServerError on a 503 (a failed database probe, or a required dependency that is not ready, such as an unmigrated database), and the decoded body is on exc.payload.

Configuration

Everything can come from the environment, so a CI job needs no argument plumbing of its own:

VariableMeaning
CALIBER_BASE_URLdeployment URL
CALIBER_TOKENpersonal access token
CALIBER_PROJECTactive project/workspace, sent as X-CALIBER-Project
CALIBER_USERtrusted-header identity, only for trusted_header deployments

An explicit argument always wins over the environment, and a token always wins over a trusted header — the token is a real credential and the header is only an assertion, so silently preferring the weaker one would be the wrong surprise.

If you are wiring the SDK into CI/CD, the configuration usually lands in a YAML workflow rather than an interactive shell:

name: release-readiness
on:
  workflow_dispatch:

jobs:
  score-release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install --find-links ./wheels caliber-sdk
      - env:
          CALIBER_BASE_URL: https://caliber.example.com
          CALIBER_TOKEN: ${{ secrets.CALIBER_TOKEN }}
          CALIBER_PROJECT: release-governance
        run: python scripts/score_release.py

That example stays deliberately small: the point is that the SDK can be dropped into a normal build job without a server-side Python environment.

Project access

Projects now report the caller's effective role and permissions, and the sync client includes typed membership management. Use the project response as the authorization-aware feature check before showing a write or publish action:

project = client.projects.get("PRJ-1")
if "resource.write.runtime" not in project.permissions:
    raise RuntimeError(f"project role {project.access_role!r} cannot write")

members = client.projects.list_members(project.project_id)
client.projects.update_member(project.project_id, "@bob", role="reviewer")

The four project roles are owner, editor, reviewer, and viewer. Only an owner (who also holds the caliber.operator scope) can add, update, or remove members. remove_member() deactivates the membership and returns True when the server confirms the removal. The async client exposes the same four membership methods on AsyncCaliberClient.projects.

Authentication

Personal access tokens are the supported credential for automation. Sessions are the wrong tool for a script: they come from password login, expire on a human timescale, and carry the user's full authority.

def issue_scoped_token(caliber: CaliberClient, *, name: str = "ci") -> dict[str, Any]:
    """Create a token limited to operator scope.

    The scope list is a *ceiling*: the effective authority is the intersection
    with what the owner holds when the request is made. Requesting more than
    you hold is refused outright rather than silently narrowed, so a token
    never claims authority it cannot exercise.
    """
    issued = caliber.auth.tokens.create(name, scopes=["caliber.operator"])
    # The plaintext exists exactly once. There is no endpoint that returns it
    # again — store it now or rotate to get a new one.
    secret = issued.token

    live = [token.token_id for token in caliber.auth.tokens.list() if token.active]
    caliber.auth.tokens.revoke(issued.token_id)
    return {"token_id": issued.token_id, "secret_len": len(secret), "live_before_revoke": live}
From sdk/caliber-sdk/examples/tokens.py — executed by the SDK test suite.

The first token has to come from somewhere other than the SDK, since issuing one needs a credential. Sign in to the web app and open Settings → API tokens to create it: choose the scopes, copy the secret (shown once), and pass it as CALIBER_TOKEN or token=. The same page lists, rotates and revokes your tokens.

Scopes are a ceiling, not a grant. The effective authority is what the token requested intersected with what its owner holds at request time. So a token cannot exceed its owner, and demoting the owner narrows every token they hold — immediately, without revoking anything. Omit scopes to inherit the owner's.

Requesting a scope you do not hold is refused at issue time (403) rather than quietly narrowed, because a token that claims authority it can never exercise fails far from its cause.

Pass project_id to tokens.create() to bind a token to one project you can already see. A bound token that names a different project is refused with a 403, and one that names none acts in its bound project. Use a bound token for CI that imports Workspace revisions: those routes refuse an unbound personal access token.

CSRF

Handled for you. CSRF enforcement is off by default on the server; where it is enabled it covers bearer-token writes as well. If a write is refused for want of a token, the client fetches one and replays the request exactly once. A 403 that is not about CSRF is not mistaken for one, so a genuine permission failure surfaces immediately instead of looping.

Authoring versus deploying

The refinement loop depends on being able to register a candidate without it going live. The SDK keeps that separation explicit: registering a version never moves an alias, and promotion is its own call and its own audit event.

def prompt_lifecycle(
    caliber: CaliberClient, *, agent_id: str = "intake-classifier"
From sdk/caliber-sdk/examples/prompt_lifecycle.py — executed by the SDK test suite.

Evidence and scoring

def build_and_score(caliber: CaliberClient, *, owner: str = "@you") -> dict[str, Any]:
    """Create a dataset, add a row, define a judge, and run an evaluation."""
    dataset = caliber.eval_datasets.create("intake-golden", owner=owner)
    caliber.eval_datasets.add_example(
        dataset.dataset_id,
        input={"ticket": "I was charged twice"},
        expected={"intent": "billing"},
    )

    # Instructions must reference an evaluation variable. A judge with no
    # variable grades nothing — it returns the same verdict every time — so
    # the server rejects it rather than letting you collect meaningless scores.
    judge = caliber.judges.create(
        "valid-intent",
        instructions="Given {{ inputs }} and {{ outputs }}, return true if intent is allowed.",
        feedback_value_type="bool",
    )

    # A judge is selected as a scorer by name (``Judge.<id>``), not by a bare
    # ``judge_id`` field -- the request schema has no such field and rejects it.
    evaluation = caliber.evaluations.create(dataset.dataset_id, scorers=[f"Judge.{judge.judge_id}"])
    return {
        "dataset_id": dataset.dataset_id,
        "judge_id": judge.judge_id,
        "evaluation_id": evaluation.evaluation_id,
    }
From sdk/caliber-sdk/examples/evaluation.py — executed by the SDK test suite.

Judge instructions must reference at least one evaluation variable — {{ inputs }}, {{ outputs }}, {{ expectations }}, {{ conversation }}, or {{ trace }}. The server enforces it because a judge with no variable grades nothing: it returns the same verdict for every example, and the resulting scorecard would look like evidence while measuring nothing.

Flagging and verifying a concern

client.verification_queue is for a concern raised separately from an already-running job — Stage ① Verify. It does not create a refinement job: today's job-creation paths (prompt optimization, skill calibration, workflow calibration) still create and self-verify their own item in one step, so this resource is for the case where flagging and confirming are two different moments, possibly by two different people.

def flag_and_verify(caliber: CaliberClient, *, agent_id: str = "support-agent") -> dict[str, Any]:
    """Flag a concern, list pending items, then confirm it's real."""
    item = caliber.verification_queue.create(
        agent_id,
        category="hallucination",
        free_text="Cited a policy section that doesn't exist.",
        severity="critical",
    )

    # A different reviewer (or the same one, later) lists what's pending and
    # decides — a separate step from the one that flagged it.
    pending = caliber.verification_queue.list(status="pending", agent_id=agent_id)
    assert any(row.item_id == item.item_id for row in pending)

    verified = caliber.verification_queue.verify(
        item.item_id, verification_notes="Confirmed against the source doc."
    )
    return {"item_id": verified.item_id, "status": verified.status}
From sdk/caliber-sdk/examples/verification_queue.py — executed by the SDK test suite.

Running workflows

def run_and_wait(
    caliber: CaliberClient, *, workflow_id: str, alias: str = "prod"
From sdk/caliber-sdk/examples/workflow_run.py — executed by the SDK test suite.

Targeting an alias rather than a version id is the point of deploying one: the caller does not change when a new version is promoted.

Submission is the single mutating call the SDK will not retry for you. It cannot know whether a failure happened before or after the run was created, and duplicating a run is worse than surfacing an error — pass an idempotency_key to make your own retry safe.

Exporting and importing a sealed workflow release

def clone_sealed_release(
    caliber: CaliberClient,
    *,
    version_id: str,
    new_name: str,
From sdk/caliber-sdk/examples/workflow_bundle.py — executed by the SDK test suite.

The deployment bundle carries the resolved workflow definition, compiled program, embedded prompt and skill content, dependency lock, and an integrity digest. The SDK checks status before download, previews the bundle against the destination workspace, and imports only after dependency preflight succeeds. Secret values, external executables, servers, and object bytes never enter the bundle.

Deploying, rolling back, and gate verdicts

def promote_and_rollback(
    caliber: CaliberClient,
    *,
    workflow_id: str,
    live_version_id: str,
    candidate_version_id: str,
    alias: str = "staging",
From sdk/caliber-sdk/examples/workflow_deployment.py — executed by the SDK test suite.

Rollback undoes the last promotion — it does not invent a prior version out of nothing. A deployment alias keeps its own checkpoint stack: the first promotion on a fresh alias has nothing to checkpoint, and only the second one gives rollback something real to restore. caliberctl workflow promote / rollback wrap exactly these two calls.

Attach advisory release evidence to a version with a gate verdict:

def record_gate_verdict(caliber: CaliberClient, *, version_id: str, passed: bool) -> dict[str, Any]:
    """Attach advisory release evidence to a version.

    Advisory, not enforced: CALIBER does not block a promotion on this by
    itself (see `ARCHITECTURE.md` Sec 4's "Gate semantics" column) -- it is
    a recorded verdict for the Version panel and for release tooling that
    chooses to check it, such as `caliberctl gate-verdict record`.
    """
    state = "pass" if passed else "fail"
    verdict = caliber.gate_verdicts.record("workflow", version_id, state=state)
    assert isinstance(verdict, dict)
    return verdict
From sdk/caliber-sdk/examples/workflow_deployment.py — executed by the SDK test suite.

Advisory means what it says — CALIBER does not block a promotion on a verdict by itself. It is release evidence for tooling that chooses to check it (the web app does not read it), like caliberctl gate-verdict record, which maps a fail state to its own non-zero exit code precisely because that tooling does choose to act on it.

Waiting on long-running work

Runs, calibration jobs, and evaluations are asynchronous. The waiters poll with capped exponential backoff and never sleep past the deadline you gave them.

They differ on failure, deliberately:

CallOn a terminal failure
workflows.runs.wait()raises WorkflowRunFailed
tools.wait_for_calibration()returns the job
evaluations.wait()returns the evaluation

A script whose run failed almost always wants to stop. A calibration score or an evaluation metric, by contrast, is the measurement — a low one is the result, not an error in the call.

Errors

CaliberError
├── CaliberConfigError        the client was built with unusable configuration
├── CaliberTransportError     no HTTP response at all (DNS, refused, timeout)
├── CaliberDecodeError        a 2xx payload had the wrong shape (strict decoding only)
└── CaliberAPIError           the server answered with a non-2xx
    ├── CaliberValidationError    400 or 422 with a structured field list
    ├── CaliberAuthenticationError 401
    ├── CaliberPermissionError     403
    ├── CaliberNotFoundError       404
    ├── CaliberConflictError       409
    ├── CaliberPreconditionError   412 (stale ETag / compare-and-set)
    ├── CaliberRateLimitError      429
    └── CaliberServerError         5xx

CaliberTransportError is separate from CaliberAPIError because there is no server verdict to inspect — and because retrying is often right in one case and wrong in the other.

A validation failure prints the field and the server's reason:

[400] request body validation failed (POST .../judges) request_id=… —
instructions: instructions must reference at least one evaluation variable

The structured body behind that exception is JSON, and the SDK preserves it on the typed error object:

{
  "detail": "request body validation failed",
  "status_code": 400,
  "errors": [
    {
      "loc": ["instructions"],
      "msg": "instructions must reference at least one evaluation variable",
      "type": "value_error"
    }
  ]
}

loc is a path, not a field name — it is a list because the failure may sit inside a nested object, as in ["manifest", "nodes", 0, "tool_ref"]. That is why CaliberValidationError.errors hands you the list unchanged, and why its __str__ joins the path with dots rather than printing only the last segment.

Some routes additionally set a machine-readable reason_code alongside detail, so a caller can switch on a stable string instead of parsing the human-readable message:

{
  "detail": "resource_type_adapter_unavailable: no adapter registered for 'widget'",
  "status_code": 409,
  "reason_code": "resource_type_adapter_unavailable"
}

reason_code is optional and additive — most routes have not been migrated to set it yet, so CaliberAPIError.reason_code is None for those, and a caller must not assume it is always populated:

try:
    caliber.workspaces.revisions.snapshot(project_id, resources=[...])
except CaliberAPIError as exc:
    if exc.reason_code == "resource_type_adapter_unavailable":
        ...  # handle this one case specifically
    elif exc.reason_code is not None:
        ...  # some other migrated, named failure
    else:
        raise  # not yet a stable code -- fall back to detail/status_code

Feature flags and disabled areas

The server gates the areas the alpha does not stand behind behind four flags: Aria (aria, on by default), MCP servers and OpenAPI integrations (integrations, off), cookbooks (cookbooks, off) and release-candidate signoff with Workspace releases (release_candidates, off). The resources that wrap them (caliber.aria, caliber.mcp_servers, caliber.openapi_integrations, caliber.cookbooks, the candidate and report-job methods of caliber.releases, and caliber.workspaces.releases) still exist in the SDK, but against a server with the flag off every one of those calls raises CaliberNotFoundError (404) whose reason_code is feature_disabled and whose detail names the variable to set, for example CALIBER_FEATURE_COOKBOOKS.

Feature detection should read the capabilities response rather than provoke that error. GET /capabilities returns features, an object keyed by the four ids; each entry has enabled, env_var, label and stability (preview or record_only). The SDK decodes it as Capabilities.features, and Capabilities.feature_enabled(id) answers a single question. A server that predates the flags returns no features, and an unknown id counts as off.

from caliber_sdk import CaliberNotFoundError

features = caliber.capabilities_info.get()
if features.feature_enabled("cookbooks"):
    recipes = caliber.cookbooks.list()

try:
    caliber.aria.capabilities()
except CaliberNotFoundError as exc:
    if exc.reason_code == "feature_disabled":
        ...  # Aria is off in this deployment; exc.detail names CALIBER_FEATURE_ARIA
    else:
        raise  # an ordinary 404

The live Releases board, the timeline and release operations are core and not behind a flag. See Feature flags for what turning each one on means.

Anything not yet modelled

client.raw reaches any endpoint under /ajax-api/2.0/mlflow/caliber:

caliber.raw.get("/observability/traces")
caliber.raw.post("/cookbooks/01/install", json={"name": "My install"})
for item in caliber.raw.paginate("/workflows", limit=50):
    ...

This is permanent, not scaffolding. A typed façade that lags the server would otherwise make new endpoints unreachable until the SDK caught up.

Forward compatibility

Unknown response fields are kept in extra rather than dropped, and missing ones fall back to defaults rather than raising. A newer server does not break an older client, and an older server does not break a newer one.

CALIBER : Contextual Adaptive Lifecycle for Intelligent Build, Evaluation, and Refinement — this page is generated from the authoritative Markdown sources in docs/ and the repository-level ARCHITECTURE.md.