SDK recipes
Full runnable cookbook implementations that use only caliber-sdk: inspect readiness, install the maintained recipe, and finish the scenario through typed SDK calls and raw fallbacks where needed.
Disabled by default. The cookbooks are a preview area and are off by default; enable with
CALIBER_FEATURE_COOKBOOKS=trueon the server and restart it. Recipes 03 to 08, 18 and 20 install their catalog entry withcaliber.cookbooks.install, and recipes 01 and 10 list it, so against a default server they fail with a 404 whosereason_codeisfeature_disabled. Some recipes use other preview areas as well: recipes 05 and 19 needCALIBER_FEATURE_INTEGRATIONS(MCP servers and OpenAPI integrations) and recipes 11 and 21 needCALIBER_FEATURE_RELEASE_CANDIDATES. Recipes 12 to 15 and 17 use Aria, which ships on (CALIBER_FEATURE_ARIAdefaults to true); recipe 20 needs a stack started with--real-llmrouted at its stand-in gateway. Readfeaturesfrom the capabilities response first (see the SDK guide). See also Feature flags.
Each recipe is the SDK counterpart of a lab under docs-site/cookbooks/, which was run for real against a disposable server (scripts/cookbook-env.sh up NAME --flags ...); the lab's README holds the exact setup, the expected ok lines, and what is simulated. On the alpha's default simulated model and evaluator the scripts assert structure and wiring (for example that Evaluations refuses with 400 evaluation requires a real LLM provider), never a score. Each script prints one ok line per verified outcome and exits 0 only if all of them held; run it with PYTHONPATH=sdk/caliber-sdk caliber/.venv/bin/python sdk/caliber-sdk/examples/cookbooks/cookbook_NN_*.py from a checkout (caliber/.venv is the virtual environment that make install creates inside caliber/; the root make setup makes a different one at .venv/).
These recipes are the SDK-native counterparts to the platform cookbook gallery. Each example uses only caliber-sdk plus Python's standard library.
Design rule:
- use the built-in cookbook installer when the example extends one of the versioned platform recipes CALIBER already ships;
- create standalone SDK automation examples directly through typed resources when there is no corresponding installable workflow recipe;
- use typed SDK resources — never
client.raw— for configuration, execution, file persistence, and evidence capture.client.rawremains the SDK's permanent escape hatch for a route the typed layer has not wrapped yet (see the SDK guide), but none of the recipes below currently need it.
Every code block on this page is generated from the source files under sdk/caliber-sdk/examples/cookbooks/ at build time. The example test suite executes those files so the published docs stay tied to runnable SDK code.
For setup and typed client behavior, use the SDK guide and the SDK API reference. This page is only for end-to-end runnable examples.
Offline replay recovery check
For the installed Beta governed evidence-review journey, the run-scoped SDK and CLI calls are submit -> approvals/approval -> decide -> resume -> evidence -> replay. The proposal is nested in the approval view; the server has no standalone proposal resource. The maintained installed example is examples/cookbooks/cookbook_22_governed_evidence_review.py and the operator replay command is:
caliberctl workflow run replay RUN_ID
The command preserves the server's matches_original field and fails when it is false. It never treats request_changes metadata as an executable route.
For a run that already has a B09.3 observation set and an immutable admission manifest, an operator can perform the bounded B09.4 comparison with the same project-scoped credentials. This route is deliberately a raw HTTP example: there is no parallel cookbook storage format and no live fallback.
curl --fail-with-body -sS \
-X POST "$CALIBER_BASE_URL/ajax-api/2.0/mlflow/caliber/workflow-runs/$RUN_ID/replay" \
-H "Authorization: Bearer $CALIBER_TOKEN" \
-H "X-CALIBER-Project: $CALIBER_PROJECT_ID" \
-H "Content-Type: application/json" \
--data '{"observation_ids":["OBS-deadbeef"]}'
HTTP 200 is a ReplayReport; it compares stable decision semantics and does not call a provider, downstream, dispatcher or effect. A 409 such as observation_scope: one or more observations are outside the replay scope or observation_integrity: an observation failed its storage integrity check is an explicit refusal. Re-select the exact project/principal-scoped ids or restore the immutable object from backup; never respond by starting a live run. Unsupported shapes are refused rather than approximated.
Cookbook implementations
Each script on this page finishes its scenario entirely through typed SDK calls. Recipes 03 to 08, 10 and 18 install their versioned entry from the built-in cookbook catalog, recipe 01 checks that its entry is listed, the others drive the lab's own prompts, skills, workflows or assets directly, and recipe 17 is a standalone SDK automation that creates its own project and assets. client.raw is the SDK's permanent escape hatch for anything not yet wrapped; a few scripts use it for a readiness probe, an invalid payload or a route the typed layer does not cover, and each summary below says so. Some scripts sign test accounts in with plain httpx calls, since the SDK acts as one token.
The code blocks are full files, not snippets. You can run them directly once CALIBER_BASE_URL and CALIBER_TOKEN are set.
export CALIBER_BASE_URL=https://caliber.example.com
export CALIBER_TOKEN=calpat_...
python sdk/caliber-sdk/examples/cookbooks/cookbook_01_trustworthy_intake_classifier.py
Cookbook 01 — Trustworthy Intake Classifier
Author and promote a strict-JSON intake prompt, import the 44-case labelled test set, register a weaker v2, then calibrate the live prompt, apply the candidate and roll it back, verifying the registry alias, live board, release timeline and audit log at each step; it exits 0 only if all 26 checks hold. It needs CALIBER_FEATURE_COOKBOOKS=true, an operator or admin token and MLFLOW_TRACKING_URI; on the default simulated stack evaluation is refused with 400 (the script asserts that refusal) and calibration evidence is canned and marked simulated, while a real model gives a scorecard that catches the v2 regression (--skip-release stops after that). It uses client.raw for /readiness and for the two /evaluations failure probes, and a plain httpx login to mint the viewer token.
SDK surfaces: cookbooks, prompts, datasets, evaluations, jobs, releases, audit, auth
- Check readiness and that Cookbook 01 is listed with guided steps, then create the strict-JSON prompt v1 and promote it, verifying the
prodalias in the MLflow registry. - Import the 44-case labelled test set from the JSONL file and register a weaker v2 that is not made live.
- Evaluate v1 and v2 and catch the regression against the baseline (44/44 strict JSON against 0/44); on a simulated model verify the 400 refusal instead, and verify that evaluating a missing test set is a 404.
- Calibrate the live prompt through the typed prompts and jobs resources, wait for
candidate_ready, and read its evidence (44 examples, dataset version,simulated: true) and diff. - Exercise the failure paths: a viewer's apply is 403, a candidate below the gate is
rejectedand its apply is 409; then apply the candidate and verify the alias, live board, release timeline and audit log all name you. - Roll back and verify the alias returned to v1 in the registry, on the live board and in the audit log.
"""Cookbook 01: release a prompt change you can trust, end to end, with the SDK.
This is the executable form of ``docs-site/cookbooks/01-prompt-regression-lab/README.md``. It runs
the alpha's one promise against a real CALIBER server and exits 0 only when every documented
outcome was verified:
1. author a prompt (v1, strict JSON) and make it live;
2. import a labelled test set from ``assets/dataset/intake-classifier.jsonl``;
3. register a weaker v2 (the regression) without making it live;
4. evaluate v1 and v2 on the test set and compare them. This needs a model: with the simulated LLM
the evaluation is refused (400) and the script verifies that refusal instead, because CALIBER
never invents a scorecard;
5. calibrate the live prompt and wait for the candidate; read its evidence and diff;
6. exercise the failure paths: a viewer cannot apply (403), a gate that fails blocks the candidate
(409 on apply), evaluating a missing test set is a 404;
7. apply the candidate, then verify the live alias moved in the MLflow registry, the live board,
the release timeline and the audit log, each naming who applied it;
8. roll back and verify the alias returned.
The script reads ``GET /readiness`` and runs in one of two modes. When ``simulated`` lists
``llm``/``eval`` (the alpha default) the refusal and the ``simulated`` evidence markers are
verified. When it is empty (a real model: a hosted provider or a local Ollama) the evaluations
really run, and only *invariants* are asserted (answers parse as the contract, scores are in
range, the evidence has the real example count and is not marked simulated), never an exact score
or answer, because a model's output varies. A failed evaluation or calibration is reported as
``evaluation failed: <error>`` / ``calibration failed: <error>`` with the server's own message.
Environment (see the README): ``CALIBER_BASE_URL`` (the server root, for example
``http://127.0.0.1:5001``, without the API path), ``CALIBER_TOKEN`` (an operator or admin
token), ``MLFLOW_TRACKING_URI`` (to read the registry directly). Optional: ``COOKBOOK_01_ASSETS``
(a different assets directory); ``COOKBOOK_01_HTTP_TIMEOUT`` (seconds a synchronous evaluation may
take, default 900); ``COOKBOOK_01_CALIBRATION_TIMEOUT`` (seconds to wait for the candidate, default
1500 on a real model); ``COOKBOOK_01_MIN_SCORE`` and ``COOKBOOK_01_MAX_REGRESSION`` (the calibration
gate on a real model; unset means the product defaults, 0.85 and 0.02).
python sdk/caliber-sdk/examples/cookbooks/cookbook_01_trustworthy_intake_classifier.py
python ... --skip-release # evaluation and regression only (a stand-in model, see README)
python ... --expect-regression # also assert the weaker v2 breaks the contract (stand-in model)
python ... --accept-rejection # a real run the gate rejects, with its reason, is verified
python ... --cleanup # delete what earlier runs created
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import time
from collections.abc import Callable
from pathlib import Path
from typing import Any
import httpx
from caliber_sdk import CaliberClient
from caliber_sdk.errors import CaliberAPIError
from caliber_sdk.transport import API_PREFIX
NAME_PREFIX = "cookbook-01-"
ALLOWED_INTENTS = frozenset({"billing", "how_to", "bug", "account", "feature_request", "unknown"})
ALLOWED_PRIORITIES = frozenset({"low", "medium", "high", "urgent"})
SCHEMA_KEYS = frozenset({"intent", "priority", "confidence", "needs_review", "reason"})
EVAL_SCORERS = ["token_f1"]
#: A candidate may not lose more than this much pass rate against the baseline.
MAX_PASS_RATE_DROP = 0.05
#: On a real model a share of answers may stray from the contract; below this the prompt is not
#: working at all and the lab stops. (A stand-in or a strong model scores 1.0.)
MIN_CONTRACT_RATE = 0.9
#: The v2 prompt may not *beat* the baseline on the scorecard by more than this. The text-overlap
#: scorecard wobbles by a row or two on 44 cases (1 row is 0.023), and a strong hosted model can
#: answer the weaker wording just as well, so only a clear win for v2 is a contradiction.
SCORE_NOISE = 0.05
VIEWER_USER = "cookbook01-viewer"
VIEWER_PASSWORD = "cookbook01-viewer-pass"
class LabVerificationError(AssertionError):
"""At least one documented outcome of the lab did not hold."""
def default_assets_dir() -> Path:
override = os.environ.get("COOKBOOK_01_ASSETS")
if override:
return Path(override)
return (
Path(__file__).resolve().parents[4] / "docs-site/cookbooks/01-prompt-regression-lab/assets"
)
def prompt_body(path: Path) -> str:
"""The template: everything below the YAML front matter of a prompt asset file."""
text = path.read_text(encoding="utf-8")
if text.startswith("---"):
text = text.split("\n---\n", 1)[1]
return text.strip() + "\n"
def load_dataset(path: Path) -> list[dict[str, Any]]:
rows = [
json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()
]
for row in rows:
if "input" not in row or "expected" not in row:
raise LabVerificationError(f"{path.name}: row {row.get('id')} lacks input/expected")
return rows
def calibration_scorers(assets: Path) -> list[dict[str, Any]]:
"""The calibration scorer: MLflow's ``Guidelines`` judge, configured from the asset file.
``Correctness`` (the form's default) needs an ``expected_response``/``expected_facts`` per
example, which this test set does not have (its labels are ``intent``/``priority``/
``needs_review``), so on a real judge it scores nothing and the run fails. ``Guidelines``
judges the answer against written rules and needs only the input and the output.
"""
config = json.loads((assets / "calibration/guidelines.json").read_text(encoding="utf-8"))
return [{"name": "Guidelines", "config": config}]
def gate_from_env() -> dict[str, float] | None:
"""Gate overrides for a real calibration run (``None``: the product defaults, 0.85 / 0.02).
A small local model is a noisy judge (the same baseline scored 0.52 and 0.39 on two runs), so
the README lowers both bars for it and says so; a hosted model uses the defaults.
"""
gate: dict[str, float] = {}
if value := os.environ.get("COOKBOOK_01_MIN_SCORE"):
gate["min_aggregate_score"] = float(value)
if value := os.environ.get("COOKBOOK_01_MAX_REGRESSION"):
gate["max_regression_delta"] = float(value)
return gate or None
def evaluation_failure(item: Any) -> str | None:
"""``evaluation failed: <server error>`` when a scored run did not complete, else ``None``.
The server answers 201 with ``status: failed`` and an ``error_message`` (a refused connection,
a model that does not exist, a rejected key) and an empty aggregate; reading ``aggregate``
first dies with a ``KeyError`` that hides the cause.
"""
if item.status == "completed":
return None
return f"evaluation failed: {item.error_message or item.error or item.status}"
def contract_report(predictions: list[str], expected: list[dict[str, Any]]) -> dict[str, Any]:
"""Deterministic rule checks over the model's raw answers.
* ``valid_json``: the whole answer parses as one JSON object (prose or a code fence fails);
* ``allowed_intent_values`` / ``allowed_priority_values``: the enums the prompt promises;
* ``schema_keys``: exactly intent, priority, confidence, needs_review, reason;
* ``label_agreement``: intent, priority and needs_review all equal the labelled expectation.
"""
counts = {
"valid_json": 0,
"allowed_intent_values": 0,
"allowed_priority_values": 0,
"schema_keys": 0,
"label_agreement": 0,
}
contract_ok: list[bool] = []
for raw, gold in zip(predictions, expected, strict=True):
try:
record = json.loads(raw)
except (TypeError, ValueError):
record = None
if not isinstance(record, dict):
contract_ok.append(False)
continue
counts["valid_json"] += 1
intent_ok = record.get("intent") in ALLOWED_INTENTS
priority_ok = record.get("priority") in ALLOWED_PRIORITIES
keys_ok = set(record) == SCHEMA_KEYS
counts["allowed_intent_values"] += intent_ok
counts["allowed_priority_values"] += priority_ok
counts["schema_keys"] += keys_ok
counts["label_agreement"] += all(record.get(key) == value for key, value in gold.items())
contract_ok.append(intent_ok and priority_ok and keys_ok)
return {"n": len(predictions), **counts, "contract_ok": contract_ok}
def registry_alias_version(name: str, alias: str = "prod") -> int | None:
"""The version the MLflow registry says ``alias`` points at (read straight from MLflow)."""
base = os.environ["MLFLOW_TRACKING_URI"].rstrip("/")
response = httpx.get(
f"{base}/ajax-api/2.0/mlflow/registered-models/alias",
params={"name": name, "alias": alias},
timeout=30,
)
if response.status_code == 404:
return None
response.raise_for_status()
return int(response.json()["model_version"]["version"])
def make_viewer_client(admin: CaliberClient, base_url: str) -> CaliberClient:
"""A client signed in as a read-only account (created if it does not exist yet)."""
try:
admin.auth.accounts.create(VIEWER_USER, VIEWER_PASSWORD)
except CaliberAPIError as exc:
if "exist" not in str(exc).lower():
raise
# A previous run's cleanup may have disabled the account; signing in needs it enabled.
admin.auth.accounts.update(VIEWER_USER, disabled=False)
with httpx.Client(base_url=base_url.rstrip("/") + API_PREFIX, timeout=30) as http:
login = http.post("/auth/login", json={"user_id": VIEWER_USER, "password": VIEWER_PASSWORD})
login.raise_for_status()
issued = http.post("/auth/tokens", json={"name": "cookbook-01-viewer"})
issued.raise_for_status()
token = issued.json()["data"]["token"]
return CaliberClient(base_url, token=token)
def status_of(call: Callable[[], Any]) -> tuple[int | None, str]:
"""Run ``call`` expecting an API error: ``(status_code, detail)``; ``(None, '')`` on success."""
try:
call()
except CaliberAPIError as exc:
return exc.status_code, str(exc)
return None, ""
def run(
caliber: CaliberClient,
*,
assets: Path | None = None,
suffix: str | None = None,
viewer: CaliberClient | None = None,
registry: Callable[[str], int | None] = registry_alias_version,
skip_release: bool = False,
expect_regression: bool = False,
accept_rejection: bool = False,
poll_interval: float = 2.0,
calibration_timeout: float | None = None,
) -> dict[str, Any]:
assets = assets or default_assets_dir()
suffix = suffix or time.strftime("%Y%m%d%H%M%S")
prompt_name = f"{NAME_PREFIX}intake-classifier-{suffix}"
results: dict[str, Any] = {"prompt_name": prompt_name}
checks: dict[str, bool] = {}
def check(name: str, ok: bool, detail: Any = "") -> None:
checks[name] = bool(ok)
print(
f"{'ok ' if ok else 'FAIL'} {name}" + (f" [{detail}]" if detail != "" else ""),
flush=True,
)
me = caliber.me.get().user_id
results["actor"] = me
readiness = caliber.raw.get("/readiness")
simulated_parts = set(readiness.get("simulated") or [])
llm_simulated = "llm" in simulated_parts
eval_simulated = "eval" in simulated_parts
results["llm_simulated"] = llm_simulated
results["eval_simulated"] = eval_simulated
if calibration_timeout is None:
calibration_timeout = float(
os.environ.get("COOKBOOK_01_CALIBRATION_TIMEOUT", 300 if eval_simulated else 1500)
)
# The Cookbooks gallery (feature flag `cookbooks`) lists this recipe with its guided steps.
recipe = next((item for item in caliber.cookbooks.list() if item.id == "01"), None)
check(
"cookbook 01 is listed with guided steps",
recipe is not None and len(recipe.steps) > 0,
f"{len(recipe.steps) if recipe else 0} steps",
)
# 1. Author v1 (strict JSON) and make it live.
strong = prompt_body(assets / "prompts/intake-classifier.md")
weak = prompt_body(assets / "prompts/intake-classifier-weak.md")
caliber.prompts.create(prompt_name, strong, commit_message="v1 strict-JSON intake classifier")
caliber.prompts.promote(prompt_name, 1)
check("v1 is live in the MLflow registry", registry(prompt_name) == 1)
# 2. Import the labelled test set from the file: one example per JSONL line.
rows = load_dataset(assets / "dataset/intake-classifier.jsonl")
dataset = caliber.eval_datasets.create(
f"{NAME_PREFIX}intake-golden-{suffix}",
owner=me,
description="44 labelled support messages (Cookbook 01)",
)
for row in rows:
caliber.eval_datasets.add_example(
dataset.dataset_id,
input=row["input"],
expected=row["expected"],
tags=row.get("tags", []),
)
stored = caliber.eval_datasets.examples(dataset.dataset_id)
check(
"every row of the file was imported", len(stored) == len(rows), f"{len(stored)}/{len(rows)}"
)
results.update(dataset_id=dataset.dataset_id, examples=len(stored))
dataset_version = caliber.eval_datasets.get(dataset.dataset_id).version
results["dataset_version"] = dataset_version
# 3. The regression: a weaker v2 is registered but never promoted.
v2 = caliber.prompts.register_version(
prompt_name, weak, commit_message="v2 dropped the JSON-only rules (intentional regression)"
)
check("v2 registered", v2["version"] == 2)
check("v2 is NOT live (registering is not deploying)", registry(prompt_name) == 1)
# 4. Evaluate v1 and v2 and catch the regression, or verify the honest refusal.
expected = [row["expected"] for row in rows]
if llm_simulated:
status, detail = status_of(
lambda: caliber.raw.post(
"/evaluations",
json={
"dataset_id": dataset.dataset_id,
"predict_target": "prompt",
"subject_ref": f"{prompt_name}@1",
"scorers": EVAL_SCORERS,
},
)
)
check(
"evaluation is refused on a simulated model (400)",
status == 400 and "real LLM" in detail,
detail[:70],
)
results["evaluation"] = "refused: needs a real model"
else:
runs = {}
for version, label in ((1, "baseline v1"), (2, "candidate v2 (weaker)")):
runs[version] = caliber.evaluations.create(
dataset.dataset_id,
predict_target="prompt",
subject_ref=f"{prompt_name}@{version}",
scorers=EVAL_SCORERS,
label=label,
)
baseline, weaker = runs[1], runs[2]
for item in (baseline, weaker):
failure = evaluation_failure(item)
check(
f"evaluation {item.label} completed on every example",
failure is None
and item.n_examples == len(rows)
and not any(row.get("error") for row in item.results or []),
failure or item.run_id,
)
if failure: # nothing below can be read from a run that did not complete
_finish(checks)
n = len(rows)
needed = int(MIN_CONTRACT_RATE * n)
report_1 = contract_report([r["prediction"] for r in baseline.results], expected)
report_2 = contract_report([r["prediction"] for r in weaker.results], expected)
check(
"v1 answers are valid JSON (the contract)",
report_1["valid_json"] >= needed,
f"{report_1['valid_json']}/{n}, at least {needed} needed",
)
check(
"v1 uses only allowed intents and priorities",
min(report_1["allowed_intent_values"], report_1["allowed_priority_values"]) >= needed,
f"{report_1['allowed_intent_values']}/{n} intents, "
f"{report_1['allowed_priority_values']}/{n} priorities",
)
check("v1 has exactly the schema keys", report_1["schema_keys"] >= needed)
f1_1 = baseline.aggregate.get("token_f1")
f1_2 = weaker.aggregate.get("token_f1")
check(
"the platform scorecard scored both runs (token_f1 in 0..1)",
all(isinstance(v, int | float) and 0 <= v <= 1 for v in (f1_1, f1_2))
and all(0 <= (r.pass_rate or 0) <= 1 for r in (baseline, weaker)),
f"token_f1 {f1_1} -> {f1_2}, pass rate {baseline.pass_rate} -> {weaker.pass_rate}",
)
if not checks["the platform scorecard scored both runs (token_f1 in 0..1)"]:
_finish(checks)
if not isinstance(f1_1, int | float) or not isinstance(f1_2, int | float):
raise SystemExit("verification failed: the scorecard has no token_f1")
drop = (baseline.pass_rate or 0) - (weaker.pass_rate or 0)
check(
"the weaker v2 does not beat the baseline on the scorecard",
f1_2 <= f1_1 + SCORE_NOISE and drop > -SCORE_NOISE,
f"token_f1 {f1_1:.3f} -> {f1_2:.3f}, pass rate {baseline.pass_rate:.2f} -> "
f"{weaker.pass_rate:.2f}",
)
regressed = [
row["id"]
for row, ok_1, ok_2 in zip(
rows, report_1["contract_ok"], report_2["contract_ok"], strict=True
)
if ok_1 and not ok_2
]
# Informational, not asserted: what the weaker prompt did to *this* model. A stand-in model
# breaks the contract on every row; a real instruction-tuned model usually does not, and
# then the scorecard drop (wordier answers) is the only signal.
print(
f"info v2 broke the contract on {len(regressed)}/{n} answers; "
f"JSON-valid v1 {report_1['valid_json']}/{n}, v2 {report_2['valid_json']}/{n}; "
f"labels agreeing v1 {report_1['label_agreement']}/{n}, "
f"v2 {report_2['label_agreement']}/{n}"
)
gate_fires = drop > MAX_PASS_RATE_DROP
print(
f"info regression gate (allowed pass-rate drop {MAX_PASS_RATE_DROP}): "
f"{'FAILS v2' if gate_fires else 'does not fire'} (actual drop {drop:.2f})"
)
if expect_regression:
check(
"v2 breaks the JSON contract on every answer",
report_2["valid_json"] == 0,
f"{report_2['valid_json']}/{n} valid",
)
check(
"every example that met the contract on v1 regressed on v2",
len(regressed) == report_1["valid_json"] == n,
len(regressed),
)
check(
"the platform scorecard drops against the baseline",
f1_2 < f1_1 and gate_fires,
f"token_f1 {f1_1:.3f} -> {f1_2:.3f}",
)
check(
"the regression gate fails v2",
gate_fires,
f"allowed drop {MAX_PASS_RATE_DROP}, actual {drop:.2f}",
)
results["evaluation"] = {
"baseline_run_id": baseline.run_id,
"candidate_run_id": weaker.run_id,
"contract_v1": {k: v for k, v in report_1.items() if k != "contract_ok"},
"contract_v2": {k: v for k, v in report_2.items() if k != "contract_ok"},
"token_f1": [f1_1, f1_2],
"pass_rate": [baseline.pass_rate, weaker.pass_rate],
"regressed_examples": len(regressed),
"gate_fires": gate_fires,
}
# Failure: scoring a test set that does not exist is a 404, not an empty scorecard.
status, detail = status_of(
lambda: caliber.raw.post(
"/evaluations",
json={
"dataset_id": "ED-does-not-exist",
"predict_target": "prompt",
"subject_ref": f"{prompt_name}@1",
"scorers": EVAL_SCORERS,
},
)
)
check("evaluating a missing test set is a 404", status == 404, detail[:70])
if skip_release:
results["checks"] = checks
_finish(checks)
return results
# 5. Calibrate the live prompt and wait for the candidate.
scorers = calibration_scorers(assets)
gate = None if eval_simulated else gate_from_env()
request: dict[str, Any] = {
"agent_id": prompt_name,
"eval_dataset_id": dataset.dataset_id,
"optimizer_type": "MetaPrompt",
"scorers": scorers,
"prompt_alias": "prod",
}
if gate:
request["gate"] = gate
calibration = caliber.prompts.create_calibration_run(**request)
job = caliber.jobs.wait(
calibration["job"]["job_id"],
timeout=calibration_timeout,
interval=poll_interval,
max_interval=poll_interval,
)
if job.status == "failed":
check("calibration did not fail", False, f"calibration failed: {job.error_message}")
_finish(checks)
if job.status == "rejected":
# A real run can honestly end here: the gate decides, and a small model is a noisy judge.
status, detail = status_of(lambda: caliber.jobs.apply(job.job_id))
check("a rejected candidate cannot be applied (409)", status == 409, detail[:70])
evidence = job.eval_results or {}
if accept_rejection and not eval_simulated:
# The honest outcome of a real run under the product's own gate: the judge decided
# the candidate is not good enough. Verify the rejection is real and explained, and
# stop: nothing was applied, so there is no release to verify.
reasons = (evidence.get("gate") or {}).get("reasons") or []
check(
"the gate rejected the candidate and says why",
bool(job.error_message) and bool(reasons),
job.error_message,
)
check(
"the rejection rests on real evidence (not simulated, the real example count)",
evidence.get("simulated") is False
and evidence.get("provider") not in (None, "fake")
and evidence.get("n_examples") == len(rows),
f"provider={evidence.get('provider')} simulated={evidence.get('simulated')} "
f"n_examples={evidence.get('n_examples')}",
)
results.update(job_id=job.job_id, rejected=True, rejection=job.error_message)
results["checks"] = checks
_finish(checks)
print(
"note the calibration was rejected by the gate (a real outcome); nothing was "
"applied. Rerun with COOKBOOK_01_MAX_REGRESSION / COOKBOOK_01_MIN_SCORE to "
"exercise Apply, the release screens and rollback."
)
return results
check(
"calibration reached candidate_ready",
False,
f"rejected by the gate: {job.error_message} (loosen it with COOKBOOK_01_MIN_SCORE / "
"COOKBOOK_01_MAX_REGRESSION, accept it with --accept-rejection, or rerun: the judge "
"varies)",
)
_finish(checks)
check("calibration reached candidate_ready", job.status == "candidate_ready", job.status)
evidence = job.eval_results or {}
candidate = job.candidate or {}
unchanged = candidate.get("content") == candidate.get("baseline_content")
if eval_simulated:
check(
"the candidate differs from the live prompt",
bool(candidate.get("content")) and not unchanged,
candidate.get("diff_summary"),
)
else:
# A real optimizer may honestly find nothing to change in a prompt that is already good
# (a strong hosted model did, `+0 / -0 lines`): that is reported, not a failure.
check(
"the optimizer returned a candidate",
bool(candidate.get("content")),
candidate.get("diff_summary"),
)
if unchanged:
print(
"info the optimizer proposed no edit (the candidate equals the live prompt); "
"applying it would register an identical version",
flush=True,
)
check(
"the evidence reports the real test-set size and version",
evidence.get("n_examples") == len(rows)
and evidence.get("eval_dataset_version") == dataset_version,
f"{evidence.get('n_examples')} examples, dataset v{evidence.get('eval_dataset_version')}",
)
check("the gate passed", (evidence.get("gate") or {}).get("passed") is True)
if eval_simulated:
check(
"the evidence is marked simulated",
evidence.get("simulated") is True and evidence.get("provider") == "fake",
f"provider={evidence.get('provider')} simulated={evidence.get('simulated')}",
)
else:
baseline_score = (evidence.get("baseline") or {}).get("overall")
candidate_score = (evidence.get("candidate") or {}).get("overall")
check(
"the evidence is real: not marked simulated, with measured scores",
evidence.get("simulated") is False
and evidence.get("provider") not in (None, "fake")
and all(
isinstance(v, int | float) and 0 <= v <= 1
for v in (baseline_score, candidate_score)
),
f"provider={evidence.get('provider')} simulated={evidence.get('simulated')} "
f"baseline {baseline_score} -> candidate {candidate_score}",
)
results.update(
job_id=job.job_id,
candidate_diff=candidate.get("diff_summary"),
evidence={
"provider": evidence.get("provider"),
"simulated": evidence.get("simulated"),
"n_examples": evidence.get("n_examples"),
"baseline": (evidence.get("baseline") or {}).get("overall"),
"candidate": (evidence.get("candidate") or {}).get("overall"),
},
)
# 6. Failure paths. A viewer cannot apply; a failing gate blocks the candidate.
if viewer is not None:
status, detail = status_of(lambda: viewer.jobs.apply(job.job_id))
check("a viewer cannot apply (403)", status == 403, detail[:70])
if eval_simulated:
# The simulated evaluator scores every candidate 0.94, so a 0.99 bar always fails. (A real
# judge could score 1.0, so this check is not made there.)
strict = caliber.prompts.create_calibration_run(
**{**request, "gate": {"min_aggregate_score": 0.99}}
)
blocked = caliber.jobs.wait(
strict["job"]["job_id"],
timeout=calibration_timeout,
interval=poll_interval,
max_interval=poll_interval,
)
check(
"a candidate below the gate is rejected", blocked.status == "rejected", blocked.status
)
status, detail = status_of(lambda: caliber.jobs.apply(blocked.job_id))
check("applying a job that is not candidate_ready is a 409", status == 409, detail[:70])
results["blocked_job_id"] = blocked.job_id
# 7. Apply, then verify the release everywhere, naming who did it.
applied = caliber.jobs.apply(job.job_id)
new_version = int(applied["promotion"]["artifact_ref"].rsplit("/", 1)[1])
results["applied_version"] = new_version
check("apply registered a new version", new_version == 3, f"v{new_version}")
check(
"the live alias moved in the MLflow registry",
registry(prompt_name) == new_version,
f"prod -> v{registry(prompt_name)}",
)
versions: dict[int, dict[str, Any]] = {}
for row in _version_rows(caliber, prompt_name):
versions[row["version"]] = row
provenance = versions[new_version].get("provenance") or {}
check(
"the registry version carries the job and the evaluation provenance",
provenance.get("job_id") == job.job_id
and provenance.get("eval_simulated") == ("true" if eval_simulated else "false"),
f"job {provenance.get('job_id')}, eval_simulated={provenance.get('eval_simulated')}",
)
live = [
row
for row in caliber.releases.live()
if row["artifact_type"] == "prompt" and row["artifact_id"] == prompt_name
]
check(
"the live board shows the new version, applied by you",
len(live) == 1 and live[0]["version_id"] == f"v{new_version}" and live[0]["by"] == me,
f"{live[0]['version_id']} by {live[0]['by']}" if live else None,
)
timeline = [
event
for event in caliber.releases.timeline(limit=50, entity_type="prompt")
if event["entity_id"] == prompt_name
]
check(
"the release timeline shows the promotion by you",
bool(timeline)
and timeline[0]["action"] == "promote_prompt"
and timeline[0]["actor"] == me
and timeline[0]["details"]["to_version"] == new_version,
(
f"v{timeline[0]['details']['from_version']} -> v{timeline[0]['details']['to_version']} "
f"by {timeline[0]['actor']}"
)
if timeline
else None,
)
audit_promote = caliber.audit.list(entity_id=prompt_name, action="promote_prompt")
audit_apply = caliber.audit.list(entity_id=job.job_id, action="apply_candidate")
check(
"the audit log has the promotion and the apply, both by you",
any(e.actor == me and e.details.get("job_id") == job.job_id for e in audit_promote)
and any(e.actor == me for e in audit_apply),
)
status, detail = status_of(lambda: caliber.jobs.apply(job.job_id))
check("applying the same job twice is a 409", status == 409, detail[:70])
# 8. Roll back and verify the alias returned.
rolled = caliber.prompts.rollback(prompt_name)
check(
"rollback restores v1", rolled["version"] == 1 and rolled["rolled_back_from"] == new_version
)
check(
"the live alias returned to v1 in the MLflow registry",
registry(prompt_name) == 1,
f"prod -> v{registry(prompt_name)}",
)
live = [
row
for row in caliber.releases.live()
if row["artifact_type"] == "prompt" and row["artifact_id"] == prompt_name
]
check("the live board shows v1 again", len(live) == 1 and live[0]["version_id"] == "v1")
audit_rollback = caliber.audit.list(entity_id=prompt_name, action="rollback_prompt")
check(
"the audit log records the rollback by you",
any(e.actor == me and e.details.get("to_version") == 1 for e in audit_rollback),
)
results["checks"] = checks
_finish(checks)
return results
def _version_rows(caliber: CaliberClient, name: str) -> list[dict[str, Any]]:
payload = caliber.prompts.versions(name)
return list(payload) if isinstance(payload, list) else list(payload.get("data", []))
def _finish(checks: dict[str, bool]) -> None:
failed = [name for name, ok in checks.items() if not ok]
print(f"\n{len(checks) - len(failed)}/{len(checks)} checks passed")
if failed:
raise LabVerificationError("failed: " + "; ".join(failed))
def cleanup(caliber: CaliberClient) -> None:
"""Delete what earlier runs created: prompts and archive test sets named ``cookbook-01-*``."""
for prompt in caliber.prompts.list():
name: str = getattr(prompt, "name", None) or prompt.agent_id
if name.startswith(NAME_PREFIX):
caliber.prompts.delete(name)
print(f"deleted prompt {name}")
for dataset in caliber.eval_datasets.list():
if dataset.name.startswith(NAME_PREFIX):
caliber.eval_datasets.update(dataset.dataset_id, status="archived")
print(f"archived test set {dataset.name}")
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
parser.add_argument(
"--skip-release",
action="store_true",
help="stop after evaluation and regression (no calibration, apply or rollback)",
)
parser.add_argument(
"--expect-regression",
action="store_true",
help="also assert that the weaker v2 breaks the JSON contract (true of the stand-in model, "
"not of every real model)",
)
parser.add_argument(
"--accept-rejection",
action="store_true",
help="on a real model, treat a calibration the gate rejects (with a reason and real "
"evidence) as a verified outcome and stop there, instead of a failure",
)
parser.add_argument("--cleanup", action="store_true", help="delete what earlier runs created")
parser.add_argument("--suffix", help="name suffix (default: a timestamp)")
args = parser.parse_args(argv)
# A scored run is synchronous: the server answers when every example has been answered, which
# takes minutes on a real model, so the default 30 s client timeout would cut it off.
with CaliberClient(
os.environ["CALIBER_BASE_URL"],
token=os.environ["CALIBER_TOKEN"],
timeout=float(os.environ.get("COOKBOOK_01_HTTP_TIMEOUT", "900")),
) as caliber:
if args.cleanup:
cleanup(caliber)
return 0
viewer = (
None
if args.skip_release
else make_viewer_client(caliber, os.environ["CALIBER_BASE_URL"])
)
try:
result = run(
caliber,
suffix=args.suffix,
viewer=viewer,
skip_release=args.skip_release,
expect_regression=args.expect_regression,
accept_rejection=args.accept_rejection,
)
except LabVerificationError as exc:
print(f"\nVERIFICATION FAILED: {exc}", file=sys.stderr)
return 1
finally:
if viewer is not None:
viewer.close()
print(json.dumps(result, indent=2, sort_keys=True, default=str))
return 0
if __name__ == "__main__":
sys.exit(main())sdk/caliber-sdk/examples/cookbooks/cookbook_01_trustworthy_intake_classifier.py — executed by the SDK example test suite.Cookbook 02 — Precision Skills
Author the support-tone skill from the lab's asset files, preview its rendering, run two rounds of trigger-selection cases (30/40 with the starter phrases, 40/40 after tightening) and pin round 2 as the baseline, then calibrate, apply, roll back, export and re-import the skill package, and prove the failure paths and archive; it exits 0 only when every documented outcome holds. It needs an admin token plus a plain lab02-viewer account for the 403 checks and does not install the cookbook; skill calibration has no test set, so under the default simulated providers the candidate and scores are canned and the script asserts wiring only, while trigger selection is deterministic and needs no model. It uses client.raw only to post the invalid skill payloads, and a plain httpx login to mint the viewer token.
SDK surfaces: skills, jobs, auth
- Create the skill from the asset file (version 1, six starter exclusion phrases) and preview its rendering with all variables, then only one, checking the unresolved variables.
- Run trigger round 1 (30/40 right, below the 0.95 gate), tighten the trigger phrases without bumping the version, then run round 2 (40/40) and pin it as the baseline test run.
- Calibrate the skill, wait for
candidate_ready(simulated: true,n_examples: 0), apply it as version 2, and roll back to the original text as version 3 (history 3, 2, 1). - Export the package ZIP, check re-import under the same name is 409, import it under a new name, and show it keeps the instructions but not the tags, category or trigger phrases.
- Prove the failure paths: a viewer's apply, calibrate, rollback and create are each 403, invalid skill content is 400, a duplicate name is 409, and calibrating with no baseline pinned still works.
- Archive every skill the run created and confirm each leaves the default list.
"""Cookbook 02 (Precision Skills), run end to end against a real server.
The lab's whole API path, from the dataset files to a verified outcome:
author the skill -> render preview -> trigger round 1 (misses) -> tighten the trigger
phrases -> trigger round 2 (clean) -> record + pin the baseline -> calibrate -> review
the candidate -> apply -> roll back -> export and re-import the package -> failure
paths (a viewer, invalid content, a calibration with no baseline) -> archive.
It exits 0 only when every documented outcome is verified. The assets it reads are the
lab's own files under ``docs-site/cookbooks/02-skill-trigger-packaging-lab/assets/``.
Run it from the repository root, against a server that has a ``caliber.admin`` and
``caliber.operator`` token (the ``scripts/cookbook-env.sh`` stack signs in as ``admin``)::
export CALIBER_BASE_URL=http://127.0.0.1:5001
export CALIBER_TOKEN=calpat_...
PYTHONPATH=sdk/caliber-sdk caliber/.venv/bin/python \
-m examples.cookbooks.cookbook_02_precision_skills
Two modes, detected from ``GET /readiness`` (``simulated`` empty means a real provider):
* Simulated stack (the default): the candidate text and the scores are canned, and a skill
calibration needs no test set. The script asserts the wiring (a candidate is produced, flagged
simulated, with ``n_examples`` 0, and it applies and rolls back as versions), never a score.
* Real provider (``scripts/cookbook-env.sh up NAME --flags cookbooks --real-llm``): the script
loads the 8-row skill test set, calibrates against it with a note about what to fix, and
asserts invariants only: ``simulated`` is false, ``n_examples`` is the size of the test set, the
scores are in range, the candidate differs from the skill and applies and rolls back. A
calibration with no test set is asserted to fail with the evaluator's own error. It never
asserts generated text or an exact score.
Trigger selection is deterministic and needs no model in either mode.
"""
from __future__ import annotations
import io
import json
import os
import secrets
import zipfile
from collections.abc import Callable
from pathlib import Path
from typing import Any
import httpx
from caliber_sdk import CaliberClient
from caliber_sdk.errors import CaliberAPIError
from caliber_sdk.transport import API_PREFIX
from examples.cookbooks._helpers import env_client
SKILL_FILE = "skills/support-tone-and-citation.md"
TIGHTENED_FILE = "skills/trigger-phrases.json"
INVALID_FILE = "skills/invalid-skills.json"
CASES_FILE = "dataset/trigger-cases.jsonl"
RENDER_FILE = "dataset/render-vars.json"
TEST_SET_FILE = "dataset/skill-eval-cases.jsonl"
NOTES_FILE = "skills/calibration-notes.txt"
#: ``trigger_accuracy_min`` in the lab's ``verification.yaml``.
TRIGGER_ACCURACY_MIN = 0.95
VIEWER_USER = "lab02-viewer"
VIEWER_PASSWORD = "lab02-viewer-pw-1"
def assets_dir() -> Path:
override = os.environ.get("COOKBOOK_02_ASSETS")
if override:
return Path(override)
repo_root = Path(__file__).resolve().parents[4]
return repo_root / "docs-site/cookbooks/02-skill-trigger-packaging-lab/assets"
def load_skill(assets: Path) -> tuple[dict[str, Any], str]:
"""The skill asset: its frontmatter (name, summary, tags, ...) and the body below it."""
try:
import yaml # type: ignore[import-untyped,unused-ignore]
except ImportError as exc: # pragma: no cover - environment
raise SystemExit("this example reads YAML frontmatter: pip install pyyaml") from exc
text = (assets / SKILL_FILE).read_text(encoding="utf-8")
_, frontmatter, body = text.split("---\n", 2)
return yaml.safe_load(frontmatter), body.strip()
def load_cases(assets: Path) -> list[dict[str, Any]]:
lines = (assets / CASES_FILE).read_text(encoding="utf-8").splitlines()
return [json.loads(line) for line in lines if line.strip()]
def load_test_set(assets: Path) -> list[dict[str, Any]]:
"""The skill's test set: reply cases, each ``{id, tags, input, expected}``."""
lines = (assets / TEST_SET_FILE).read_text(encoding="utf-8").splitlines()
return [json.loads(line) for line in lines if line.strip()]
def failure_text(job: Any) -> str:
"""The server's reason a job stopped (``error_message``; older payloads say ``error``)."""
return str(job.error_message or job.error or "")
def is_real_stack(caliber: CaliberClient) -> bool:
"""True when the server runs real providers (``/readiness`` lists nothing as simulated)."""
return not (caliber.readiness() or {}).get("simulated")
def create_test_set(
caliber: CaliberClient, name: str, owner: str, rows: list[dict[str, Any]]
) -> str:
"""Import the test-set file as an eval dataset and return its id."""
dataset = caliber.eval_datasets.create(name, owner=owner, description="Support reply cases")
for row in rows:
caliber.eval_datasets.add_example(
dataset.dataset_id, input=row["input"], expected=row["expected"], tags=row["tags"]
)
return str(dataset.dataset_id)
#: Provider errors worth one more attempt: the model refused, was rate limited or timed out.
TRANSIENT_MARKERS = ("429", "rate limit", "timed out", "timeout", "temporarily", "overloaded")
#: A real calibration is model-dependent: up to two retries when the gate rejects the candidate
#: (eight test rows are coarse; a single flipped row can trip it) or the provider hiccups. More
#: than that is a real failure and is reported.
REAL_CALIBRATION_ATTEMPTS = 3
def calibrate_for_real(
caliber: CaliberClient, skill_id: str, test_set_id: str, notes: str
) -> tuple[Any, int]:
"""Calibrate against the test set until a candidate is ready; returns ``(job, attempts)``."""
last: Any = None
for attempt in range(1, REAL_CALIBRATION_ATTEMPTS + 1):
queued = caliber.skills.calibrate(skill_id, eval_dataset_id=test_set_id, notes=notes)
last = caliber.jobs.wait(queued["job"]["job_id"], timeout=600)
if last.status == "candidate_ready":
return last, attempt
error = failure_text(last).lower()
retryable = last.status == "rejected" or any(m in error for m in TRANSIENT_MARKERS)
if not retryable:
break
raise AssertionError(
f"{last.job_id} ended as {last.status!r} after {attempt} attempt(s): {failure_text(last)}"
)
def real_evidence(job: Any, test_set_id: str, n_rows: int) -> dict[str, Any]:
"""Assert the invariants of real calibration evidence and return what the report shows."""
evidence = job.eval_results or {}
assert evidence.get("simulated") is False, evidence
assert evidence.get("provider") not in (None, "fake"), evidence
assert evidence.get("n_examples") == n_rows, evidence
assert evidence.get("eval_dataset_id") == test_set_id, evidence
candidate = evidence["candidate"]["overall"]
baseline = evidence["baseline"]["overall"]
assert 0.0 <= candidate <= 1.0 and 0.0 <= baseline <= 1.0, evidence
assert evidence["gate"]["passed"] is True, evidence
return {
"candidate_overall": candidate,
"baseline_overall": baseline,
"dimensions": sorted(evidence["candidate"]["dimensions"]),
"diff_summary": (job.candidate or {}).get("diff_summary"),
}
def run_cases(
caliber: CaliberClient, skill_id: str, cases: list[dict[str, Any]], *, context: bool = True
) -> list[dict[str, Any]]:
"""Check every case with the real selector and judge it against its expectation.
``context=False`` sends the message alone, which is what the Skills page's Scenario Sets
runner does; ``True`` also sends the case's ``artifact_type`` and ``session_goal``.
"""
rows = []
for case in cases:
inputs = case["inputs"]
selection = caliber.skills.test_selection(
skill_id,
inputs["user_message"],
artifact_type=inputs.get("artifact_type") if context else None,
session_goal=inputs.get("session_goal") if context else None,
)
expected = case["expectations"]["is_selected"]
rows.append(
{
"id": case["id"],
"expected": expected,
"selected": selection.is_selected,
"score": selection.selection_score,
"reason": selection.selection_reason,
"ok": selection.is_selected == expected,
"inputs": inputs,
}
)
return rows
def tally(rows: list[dict[str, Any]]) -> dict[str, Any]:
wrong = [row for row in rows if not row["ok"]]
return {
"cases": len(rows),
"correct": len(rows) - len(wrong),
"accuracy": round((len(rows) - len(wrong)) / len(rows), 3),
"false_positives": sorted(row["id"] for row in wrong if row["selected"]),
"false_negatives": sorted(row["id"] for row in wrong if not row["selected"]),
}
def save_run(
caliber: CaliberClient, skill_id: str, version: int, rows: list[dict[str, Any]]
) -> str:
"""Persist a round as a durable ``selection`` run, the way the Trigger Tests page does."""
results = [
{
"name": row["id"],
"input": {"user_message": row["inputs"]["user_message"]},
"output": {"is_selected": row["selected"], "selection_score": row["score"]},
"verdict": "pass" if row["ok"] else "fail",
"score": 1.0 if row["ok"] else 0.0,
"reasoning": row["reason"],
}
for row in rows
]
run = caliber.skills.create_test_run(
skill_id=skill_id, kind="selection", skill_version=version, results=results
)
return str(run["test_run_id"])
def reason_of(exc: CaliberAPIError) -> str:
"""The server's reason, without the request line and id the exception also carries."""
errors = getattr(exc, "errors", None)
if errors:
return "; ".join(
f"{'.'.join(str(part) for part in item.get('loc', []))}: {item.get('msg')}"
for item in errors
)
return exc.detail or str(exc)
def expect_status(label: str, status: int, call: Callable[[], Any]) -> str:
"""Run ``call`` and require it to fail with HTTP ``status``; return the server's reason."""
try:
call()
except CaliberAPIError as exc:
assert exc.status_code == status, f"{label}: expected {status}, got {exc.status_code}"
return f"{status} {reason_of(exc)}"
raise AssertionError(f"{label}: expected HTTP {status}, but the call succeeded")
def wait_for_candidate(caliber: CaliberClient, job_id: str) -> Any:
job = caliber.jobs.wait(job_id, timeout=120)
assert job.status == "candidate_ready", f"{job_id} ended as {job.status!r}: {failure_text(job)}"
return job
def make_viewer_client(admin: CaliberClient) -> CaliberClient:
"""A client signed in as a plain account: ``caliber.viewer`` scope only.
The account is created (or its password reset and re-enabled) through the admin client, it
signs in once with its password, and the script keeps only a personal access token.
"""
base_url = os.environ["CALIBER_BASE_URL"]
try:
admin.auth.accounts.create(VIEWER_USER, VIEWER_PASSWORD)
except CaliberAPIError:
admin.auth.accounts.update(VIEWER_USER, password=VIEWER_PASSWORD, disabled=False)
with httpx.Client(base_url=base_url.rstrip("/") + API_PREFIX, timeout=30) as http:
login = http.post("/auth/login", json={"user_id": VIEWER_USER, "password": VIEWER_PASSWORD})
login.raise_for_status()
issued = http.post("/auth/tokens", json={"name": "lab02-viewer"})
issued.raise_for_status()
token = issued.json()["data"]["token"]
return CaliberClient(base_url, token=token)
def run(
caliber: CaliberClient,
*,
viewer: CaliberClient | None = None,
skill_name: str | None = None,
) -> dict[str, Any]:
assets = assets_dir()
spec, content = load_skill(assets)
cases = load_cases(assets)
tightened = json.loads((assets / TIGHTENED_FILE).read_text(encoding="utf-8"))["test_triggers"]
render = json.loads((assets / RENDER_FILE).read_text(encoding="utf-8"))
suffix = secrets.token_hex(3)
name = skill_name or f"{spec['name']}-{suffix}"
owner = caliber.me.get().user_id
created: list[str] = []
report: dict[str, Any] = {"skill_name": name, "cases": len(cases)}
# 1. Author. The skill starts with only the six starter exclusion phrases from the asset.
skill = caliber.skills.create(
name,
owner=owner,
content=content,
summary=spec["summary"],
category=spec["category"],
tags=spec["tags"],
skill_metadata={"test_triggers": {"should_not_trigger": spec["should_not_trigger"]}},
)
created.append(skill.skill_id)
skill_id = skill.skill_id
assert skill.version == 1
report["skill_id"] = skill_id
# 2. Render preview: every variable supplied, then only one.
full = caliber.skills.render(skill_id, variables=render["variables"])
assert full.unresolved_variables == render["expected"]["unresolved_variables"] == []
assert (
"[KB-1042]" in full.rendered_content and "non-technical customer" in full.rendered_content
)
partial = caliber.skills.render(skill_id, variables=render["partial"]["variables"])
assert partial.unresolved_variables == render["partial"]["expected"]["unresolved_variables"]
report["render"] = {
"detected_variables": full.detected_variables,
"unresolved": full.unresolved_variables,
"word_count": full.word_count,
"partial_unresolved": partial.unresolved_variables,
}
# 3. Trigger round 1, with the starter phrases only.
round1 = run_cases(caliber, skill_id, cases)
report["round1"] = tally(round1)
assert report["round1"]["accuracy"] < TRIGGER_ACCURACY_MIN, (
"round 1 was expected to miss cases: the starter phrases are deliberately incomplete"
)
round1_run = save_run(caliber, skill_id, skill.version or 1, round1)
# 4. Tighten: replace the trigger phrases with the tightened set (summary and tags stay).
updated = caliber.skills.update(
skill_id, skill_metadata={**skill.skill_metadata, "test_triggers": tightened}
)
assert updated.version == 1, "trigger phrases are metadata: they must not bump the version"
# 5. Trigger round 2, then record it and pin it as the baseline.
round2 = run_cases(caliber, skill_id, cases)
report["round2"] = tally(round2)
assert report["round2"]["accuracy"] >= TRIGGER_ACCURACY_MIN, report["round2"]
message_only = tally(run_cases(caliber, skill_id, cases, context=False))
assert message_only["accuracy"] >= TRIGGER_ACCURACY_MIN, message_only
report["round2_message_only"] = message_only
baseline_run = save_run(caliber, skill_id, 1, round2)
caliber.skills.set_baseline(skill_id, test_run_id=baseline_run)
workspace = caliber.skills.workspace(skill_id)
assert workspace["baseline_run_id"] == baseline_run
report["runs"] = {"round1": round1_run, "baseline": baseline_run}
# 6. Calibrate (a refinement job) and review the candidate. On a simulated stack the
# evidence is canned and needs no test set; on a real one the candidate is scored against
# the skill's test set, so the script imports it first.
real = is_real_stack(caliber)
report["mode"] = "real" if real else "simulated"
test_rows = load_test_set(assets)
attempts = 1
if real:
test_set_id = create_test_set(caliber, f"{name}-replies", owner, test_rows)
notes = (assets / NOTES_FILE).read_text(encoding="utf-8").strip()
job, attempts = calibrate_for_real(caliber, skill_id, test_set_id, notes)
job_id = job.job_id
else:
queued = caliber.skills.calibrate(skill_id)
job_id = queued["job"]["job_id"]
job = wait_for_candidate(caliber, job_id)
assert job.candidate and job.candidate["content"] != content
assert job.candidate["baseline_content"].strip() == content
evidence = job.eval_results or {}
calibration: dict[str, Any] = {
"job_id": job_id,
"status": job.status,
"simulated": evidence.get("simulated"),
"provider": evidence.get("provider"),
"n_examples": evidence.get("n_examples"),
"gate_passed": (evidence.get("gate") or {}).get("passed"),
}
if real:
calibration.update(real_evidence(job, test_set_id, len(test_rows)))
calibration["attempts"] = attempts
else:
assert evidence.get("n_examples") == 0, "a skill calibration has no test set"
report["calibration"] = calibration
# 7. Apply, 8. roll back. Versions only ever move forward.
applied = caliber.jobs.apply(job_id)
assert applied["status"] == "applied"
after_apply = caliber.skills.get(skill_id)
assert after_apply.version == 2 and after_apply.content != content
rolled = caliber.skills.rollback(skill_id)
after_rollback = caliber.skills.get(skill_id)
assert after_rollback.version == 3
assert (after_rollback.content or "").strip() == content
assert rolled["version"] == 3
history = caliber.skills.versions(skill_id)
assert [v.version_number for v in history] == [3, 2, 1]
assert history[0].content == history[2].content
report["versions"] = {"after_apply": 2, "after_rollback": 3, "history": [3, 2, 1]}
# 9. Package: export, then import under a new name and compare behaviour. (A third strategy,
# ``merge``, updates the same-named skill in place and is admin-only; the README shows it.)
archive = caliber.skills.package_zip(skill_id)
members = sorted(zipfile.ZipFile(io.BytesIO(archive)).namelist())
assert members == [f"{name}/SKILL.md", f"{name}/agents/openai.yaml"], members
conflict = expect_status(
"re-import under the same name",
409,
lambda: caliber.skills.import_package_zip(f"{name}.zip", archive),
)
copy_name = f"{name}-copy"
copy_row = caliber.skills.import_package_zip(
f"{name}.zip", archive, conflict_strategy="rename", rename_to=copy_name
)
copy_id = copy_row["skill_id"]
created.append(copy_id)
copy = caliber.skills.get(copy_id)
assert copy.content == (after_rollback.content or "").strip()
assert caliber.skills.render(
copy_id, variables=render["variables"]
).rendered_content.strip() == (
caliber.skills.render(skill_id, variables=render["variables"]).rendered_content.strip()
)
# The package carries name, description, content and the OpenAI interface. It does not carry
# tags, category or trigger phrases, and the summary is shortened to the 64-character
# interface line, so the copy decides some cases differently until those are put back.
assert copy.tags == [] and copy.category == "custom"
assert "test_triggers" not in copy.skill_metadata
before = run_cases(caliber, copy_id, cases)
source_decisions = {row["id"]: row["selected"] for row in round2}
differing_before = sorted(
row["id"] for row in before if row["selected"] != source_decisions[row["id"]]
)
caliber.skills.update(
copy_id,
tags=spec["tags"],
category=spec["category"],
summary=spec["summary"],
skill_metadata={**copy.skill_metadata, "test_triggers": tightened},
)
after = run_cases(caliber, copy_id, cases)
differing_after = sorted(
row["id"] for row in after if row["selected"] != source_decisions[row["id"]]
)
assert differing_after == [], differing_after
report["package"] = {
"members": members,
"reimport_same_name": conflict,
"copy_name": copy_name,
"content_identical": True,
"decisions_differing_before_metadata_restored": differing_before,
"decisions_differing_after_metadata_restored": differing_after,
}
# 10a. A viewer cannot change anything (the 403 names the missing scope).
failures: dict[str, Any] = {}
if viewer is not None:
failures["viewer"] = {
"apply": expect_status("viewer apply", 403, lambda: viewer.jobs.apply(job_id)),
"calibrate": expect_status(
"viewer calibrate", 403, lambda: viewer.skills.calibrate(skill_id)
),
"rollback": expect_status(
"viewer rollback", 403, lambda: viewer.skills.rollback(skill_id)
),
"create": expect_status(
"viewer create",
403,
lambda: viewer.skills.create("viewer-skill", owner="x", content="x"),
),
}
# 10b. Invalid skill content is rejected before anything is stored.
invalid = json.loads((assets / INVALID_FILE).read_text(encoding="utf-8"))
failures["invalid"] = {}
for item in invalid:
reason = expect_status(
item["label"],
item["status"],
lambda payload=item["payload"]: caliber.raw.post( # type: ignore[misc]
"/skills", json=payload
),
)
assert item["expect"] in reason, (item["label"], reason)
failures["invalid"][item["label"]] = reason
duplicate = expect_status(
"duplicate name", 409, lambda: caliber.skills.create(name, owner=owner, content="x")
)
failures["invalid"]["name already in use"] = duplicate
# 10c. Calibrating with no baseline pinned: allowed, nothing to compare. Simulated: the same
# canned evidence. Real: it still scores against the test set, and with no test set at all
# the run fails with the evaluator's own error.
# The real evaluator gates on an absolute score, so the real run uses the lab's own
# instructions (a one-line skill scores below the gate on the support cases).
bare = caliber.skills.create(
f"{name}-bare",
owner=owner,
content=content if real else "Reply kindly to {{ who }}.",
summary=spec["summary"] if real else None,
)
created.append(bare.skill_id)
assert caliber.skills.workspace(bare.skill_id)["baseline_run_id"] is None
if real:
bare_job, _ = calibrate_for_real(caliber, bare.skill_id, test_set_id, notes)
assert bare_job.eval_results and bare_job.eval_results.get("simulated") is False
no_test_set = caliber.jobs.wait(
caliber.skills.calibrate(bare.skill_id)["job"]["job_id"], timeout=600
)
assert no_test_set.status == "failed", no_test_set.status
assert "no active examples" in failure_text(no_test_set), failure_text(no_test_set)
failures["no_test_set"] = {"job_id": no_test_set.job_id, "status": no_test_set.status}
else:
bare_job = wait_for_candidate(
caliber, caliber.skills.calibrate(bare.skill_id)["job"]["job_id"]
)
assert bare_job.eval_results and bare_job.eval_results.get("simulated") is True
failures["no_baseline"] = {
"job_id": bare_job.job_id,
"status": bare_job.status,
"baseline_run_id": caliber.skills.workspace(bare.skill_id)["baseline_run_id"],
}
report["failures"] = failures
# 11. Archive everything this run created; an archived skill leaves the default list.
for skill_id_to_archive in created:
caliber.skills.update(skill_id_to_archive, status="archived")
active = {s.skill_id for s in caliber.skills.list()}
assert not active & set(created), "an archived skill must leave the default list"
assert all(caliber.skills.get(sid).status == "archived" for sid in created)
report["archived"] = len(created)
report["verified"] = True
return report
def main() -> None:
with env_client() as caliber:
viewer = make_viewer_client(caliber)
with viewer:
report = run(
caliber, viewer=viewer, skill_name=os.environ.get("COOKBOOK_02_SKILL_NAME")
)
print(json.dumps(report, indent=2, sort_keys=True))
if __name__ == "__main__":
main()sdk/caliber-sdk/examples/cookbooks/cookbook_02_precision_skills.py — executed by the SDK example test suite.Cookbook 03 — Policy-Safe Decision Tool
Register a deterministic read tool (decide_refund) and a write tool (initiate_refund) in a project, sandbox-test them, run and pin the 49-fixture calibration as the baseline, provoke a one-case regression, then import a refund workflow whose write step needs a second person's approval and drive approve, reject, deny and manual-review runs, checking the audit trail and where the sandbox boundary stops. It needs an admin token, the cookbooks flag (for the last step, installing the gallery starter) and CALIBER_APPROVER_USERS including approver1; it creates approver1 and viewer1 accounts, does not use a model, and the simulated providers play no part. It uses client.raw once, to read /system/effects, and plain httpx to sign the two accounts in.
SDK surfaces: projects, tools, workflows, audit, auth, cookbooks
- Create a project, add
approver1as reviewer andviewer1as viewer, and register the two tools; a write tool withoutrequires_approvalis refused with 400. - Sandbox-test the tools (the read tool runs live in a subprocess, the write tool is mocked) and check viewer and approver scopes get 403.
- Save the 49 fixtures and calibrate to 49/49, record the suite run and pin it as the baseline, then run a regression drill whose single wrong fixture shows as exactly one regression against that baseline.
- Import the refund-decision workflow and run it through the approval gate: the run waits at the
refundnode, the initiator's own approval is 403,approver1approves, Resume is needed, then exactly one refund fires; a rejected run fails withapproval_rejected, and a deny decision completes with no approval. - Read the audit trail and the effect ledger, then probe the sandbox boundary: a stalled tool is killed, a large file write is refused, the environment is empty, and the network is still reachable.
- Install the Cookbook 03 gallery starter and verify its draft holds a decision table and a Human Approval node.
"""Cookbook 03: a deterministic refund-policy tool, hardened, then used behind an approval gate.
Runs the whole lab against a real CALIBER server and exits 0 only when every documented
outcome was observed:
* register a read tool (``decide_refund``) and a write tool (``initiate_refund``) in a workspace;
* run both in the sandbox (the read tool live in a subprocess, the write tool mocked);
* save the 49 fixture cases, calibrate, record the run and pin it as the baseline;
* provoke a regression and see it against the baseline;
* import a workflow that decides, routes and issues the refund only after a second person approves;
* approve, reject, deny and manual-review runs; self-approval and weak roles refused;
* read the audit trail, and see where the sandbox's process boundary stops.
Environment: ``CALIBER_BASE_URL`` (the server root) and ``CALIBER_TOKEN`` (a token for an admin
account). Optional ``LAB03_SUFFIX`` makes every name unique so the script can be re-run on a
stack that already holds an earlier run. ``--cleanup`` removes what a run created.
The server needs the lab's accounts to carry platform scopes: ``CALIBER_APPROVER_USERS`` must
include ``approver1`` (see the README).
"""
from __future__ import annotations
import json
import os
import sys
import time
from contextlib import ExitStack
from pathlib import Path
from typing import Any
import httpx
from caliber_sdk import CaliberClient
from caliber_sdk.errors import CaliberAPIError, CaliberError
LAB_DIR = Path(__file__).resolve().parents[4] / "docs-site/cookbooks/03-tool-hardening-contract-lab"
ASSETS = LAB_DIR / "assets"
APPROVER = ("approver1", "lab03-approver1-password")
VIEWER = ("viewer1", "lab03-viewer1-password")
API_PREFIX = "/ajax-api/2.0/mlflow/caliber"
SETTLED = frozenset(
{"waiting_approval", "completed", "succeeded", "failed", "cancelled", "timed_out"}
)
FINISHED = frozenset({"completed", "succeeded", "failed", "cancelled", "timed_out"})
def say(message: str) -> None:
print(message, flush=True)
def check(condition: object, message: str) -> None:
if not condition:
raise AssertionError(message)
say(f" ok {message}")
def expect_status(status: int, action: Any, message: str) -> CaliberAPIError:
try:
action()
except CaliberAPIError as exc:
check(exc.status_code == status, f"{message} -> HTTP {exc.status_code}")
return exc
raise AssertionError(f"{message}: expected HTTP {status}, the call succeeded")
def load_dataset() -> list[dict[str, Any]]:
path = ASSETS / "dataset/refund-fixtures.jsonl"
return [json.loads(line) for line in path.read_text().splitlines() if line.strip()]
def fixture_cases(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Tool fixtures: the exact JSON the tool must return, compared as sorted-key JSON."""
return [
{
"name": f"{row['id']} {row['name']}",
"input": row["inputs"],
"assertion": {
"type": "equals",
"value": json.dumps(row["expectations"], sort_keys=True),
},
}
for row in rows
]
def tool_body(filename: str, suffix: str) -> dict[str, Any]:
body: dict[str, Any] = json.loads((ASSETS / "tools" / filename).read_text())
body["name"] = f"{body['name']}{suffix}"
return body
def register(caliber: CaliberClient, body: dict[str, Any]) -> Any:
body = dict(body)
name, version = body.pop("name"), body.pop("version")
module, callable_name = body.pop("module_path"), body.pop("callable_name")
return caliber.tools.register(
name,
version=version,
module_path=module,
callable_name=callable_name,
input_schema=body.pop("input_schema", None),
output_schema=body.pop("output_schema", None),
**body,
)
def workflow_yaml(suffix: str) -> str:
text = (ASSETS / "workflow/refund-decision.workflow.yaml").read_text()
for name in ("decide_refund", "initiate_refund"):
text = text.replace(name, f"{name}{suffix}")
return text
def settle(caliber: CaliberClient, run_id: str, states: frozenset[str] = SETTLED) -> Any:
deadline = time.monotonic() + 120
while time.monotonic() < deadline:
run = caliber.workflows.runs.get(run_id)
if run.status in states:
return run
time.sleep(1)
raise AssertionError(f"run {run_id} did not settle (last status {run.status!r})")
def steps_of(run: Any) -> list[dict[str, Any]]:
return list((run.extra.get("summary") or {}).get("steps") or [])
def refund_calls(run: Any) -> list[dict[str, Any]]:
return [
call
for step in steps_of(run)
if step["node_id"] == "refund"
for call in step.get("tool_calls") or []
]
def submit_case(
caliber: CaliberClient, version_id: str, row: dict[str, Any], **override: Any
) -> Any:
case = {**row["inputs"], **override}
run = caliber.workflows.runs.submit(workflow_version_id=version_id, input=json.dumps(case))
return settle(caliber, run.workflow_run_id)
def login_client(
base_url: str, user: str, password: str, *, timeout: float = 60.0
) -> CaliberClient:
"""Sign in as ``user`` and mint a personal access token (a script cannot reuse a cookie)."""
api = base_url.rstrip("/") + API_PREFIX
login = httpx.post(f"{api}/auth/login", json={"user_id": user, "password": password})
login.raise_for_status()
issued = httpx.post(
f"{api}/auth/tokens", json={"name": f"cookbook-03-{user}"}, cookies=login.cookies
)
issued.raise_for_status()
return CaliberClient(base_url, token=issued.json()["data"]["token"], timeout=timeout)
def ensure_accounts(admin: CaliberClient) -> None:
for user, password in (APPROVER, VIEWER):
try:
admin.auth.accounts.create(user, password)
say(f" created account {user}")
except CaliberError:
admin.auth.accounts.update(user, password=password)
say(f" account {user} already existed; password reset to the lab value")
def run(
admin: CaliberClient,
*,
approver: CaliberClient,
viewer: CaliberClient,
suffix: str = "",
) -> dict[str, Any]:
rows = load_dataset()
cases = fixture_cases(rows)
by_id = {row["id"]: row for row in rows}
summary: dict[str, Any] = {"fixtures": len(cases)}
say("== 1. workspace and people")
project = admin.projects.create(
f"refund-ops{suffix}", description="Cookbook 03 refund operations"
)
admin.projects.add_member(project.project_id, APPROVER[0], role="reviewer")
admin.projects.add_member(project.project_id, VIEWER[0], role="viewer")
summary["project_id"] = project.project_id
say(f" workspace {project.project_id}: admin owns it, approver1 reviews, viewer1 reads")
with ExitStack() as scope:
for client in (admin, approver, viewer):
scope.enter_context(client.workspace_scope(project.project_id))
say("== 2. register the tools")
decide = register(admin, tool_body("decide-refund.tool.json", suffix))
refund = register(admin, tool_body("initiate-refund.tool.json", suffix))
check(
decide.side_effect_level == "read" and decide.allow_in_preview,
"decide_refund is a read tool allowed in preview",
)
check(
refund.side_effect_level == "write" and refund.requires_approval,
"initiate_refund is a write tool with requires_approval",
)
check(
not decide.builtin and decide.availability == "available",
"registered tool carries no Built-in label and is available",
)
unsafe = tool_body("initiate-refund.tool.json", f"_unsafe{suffix}")
unsafe.pop("requires_approval")
error = expect_status(
400,
lambda: register(admin, unsafe),
"a write tool without requires_approval is rejected",
)
check("requires_approval" in str(error), "the rejection names requires_approval")
summary["tools"] = {"decide_refund": decide.tool_id, "initiate_refund": refund.tool_id}
say("== 3. sandbox")
sample = by_id["R01"]["inputs"]
live = admin.tools.test_invoke(decide.tool_id, input=sample)
check(
live["isolation"] == "subprocess" and live["mocked"] is False,
"decide_refund ran live in a subprocess",
)
check(live["output"] == by_id["R01"]["expectations"], f"live output is {live['output']}")
mock = admin.tools.test_invoke(
refund.tool_id, input={"order_id": "ord_1007", "amount": 49.0}
)
check(
mock["mocked"] is True and mock["isolation"] == "mocked",
"initiate_refund was mocked, not called",
)
bad = admin.tools.test_invoke(
decide.tool_id, input={"order_state": "delivered", "bogus": 1}
)
check(
bad["error"] and "unexpected keyword argument" in bad["error"],
"an unknown field is a tool error, not a decision",
)
expect_status(
403,
lambda: viewer.tools.test_invoke(decide.tool_id, input=sample),
"viewer1 cannot run a tool",
)
expect_status(
403,
lambda: approver.tools.test_invoke(decide.tool_id, input=sample),
"approver1 (no operator scope) cannot run a tool",
)
say("== 4. fixtures, calibration, test run, baseline")
admin.tools.save_test_cases(decide.tool_id, cases)
expect_status(
403, lambda: viewer.tools.calibrate(decide.tool_id), "viewer1 cannot calibrate"
)
started = time.monotonic()
scored = admin.tools.calibrate(decide.tool_id)
seconds = round(time.monotonic() - started)
total, passed = scored.extra["total"], scored.extra["passed"]
check(
(total, passed, scored.pass_rate) == (len(cases), len(cases), 1.0),
f"calibration {passed}/{total} passed, pass_rate {scored.pass_rate} ({seconds}s)",
)
def record(result: Any) -> Any:
return admin.tools.create_test_run(
tool_id=decide.tool_id,
kind="suite",
tool_version=decide.version,
results=[
{
"name": item["name"],
"input": next(c["input"] for c in cases if c["name"] == item["name"]),
"output": item["output"],
"error": item["error"],
"verdict": "pass" if item["passed"] else "fail",
"score": 1 if item["passed"] else 0,
"duration_ms": item["duration_ms"],
"reasoning": "Assertion satisfied."
if item["passed"]
else "Assertion failed.",
}
for item in result.extra["cases"]
],
)
baseline = record(scored)
check(
baseline["passed_count"] == len(cases) and baseline["kind"] == "suite",
f"suite run {baseline['test_run_id']} recorded",
)
admin.tools.set_baseline(decide.tool_id, test_run_id=baseline["test_run_id"])
workspace = admin.tools.workspace(decide.tool_id)
check(
workspace["baseline_run_id"] == baseline["test_run_id"],
"the run is pinned as the baseline",
)
summary["calibration"] = {"pass_rate": scored.pass_rate, "passed": passed, "total": total}
summary["baseline_run_id"] = baseline["test_run_id"]
say("== 5. regression drill")
wrong = "R09 amount boundary: exactly 200.00"
drill = [
c
for c in cases
if c["name"].startswith(("R01", "R02", "R05", "R06", "R09", "R10", "R35"))
]
broken = [dict(c) for c in drill]
for case in broken:
if case["name"].startswith("R09"):
case["assertion"] = {
"type": "equals",
"value": json.dumps(
{
"decision": "manual_review",
"reason_code": "AMOUNT_OVER_THRESHOLD",
"requires_approval": True,
},
sort_keys=True,
),
}
admin.tools.save_test_cases(decide.tool_id, broken)
drilled = admin.tools.calibrate(decide.tool_id)
failing = [c["name"] for c in drilled.extra["cases"] if not c["passed"]]
check(failing == [wrong], f"the drill fails exactly one case: {failing}")
later = record(drilled)
base_pass = {
r["name"]
for r in admin.tools.test_run(baseline["test_run_id"])["results"]
if r["verdict"] == "pass"
}
regressions = [
r["name"]
for r in admin.tools.test_run(later["test_run_id"])["results"]
if r["verdict"] == "fail" and r["name"] in base_pass
]
check(regressions == [wrong], "compared with the baseline, that case is the one regression")
admin.tools.save_test_cases(decide.tool_id, cases)
summary["regression"] = {"pass_rate": drilled.pass_rate, "regressed": regressions}
say("== 6. the workflow")
text = workflow_yaml(suffix)
preview = admin.workflows.preview_import(manifest_yaml=text)
check(
preview["ready_to_import"] and preview["validation"]["valid"], "import preview is valid"
)
warnings = [w["code"] for w in preview["validation"]["warnings"]]
check(warnings == ["write_tool_without_approval"], f"one advisory warning only: {warnings}")
workflow = admin.workflows.import_workflow(
manifest_yaml=text, name=f"refund-decision{suffix}"
)
version = admin.workflows.versions.list(workflow.workflow_id)[0]
summary["workflow_id"] = workflow.workflow_id
say("== 7. approve: a second person decides")
first = submit_case(admin, version.version_id, by_id["R01"])
check(
first.status == "waiting_approval" and first.extra["current_node_id"] == "refund",
"run paused at the refund node",
)
check(refund_calls(first) == [], "the refund has not been issued")
pending = approver.workflows.runs.approvals(first.workflow_run_id)
check(len(pending) == 1 and pending[0]["status"] == "pending", "one approval is pending")
check(
pending[0]["policy_snapshot"]["allow_self_approval"] is False
and pending[0]["policy_snapshot"]["required_role"] == "caliber.approver",
"policy: approver scope, no self-approval",
)
exc = expect_status(
403,
lambda: admin.workflows.runs.approve(first.workflow_run_id, reason="self"),
"the initiator cannot approve their own run",
)
check("second person" in str(exc), "the refusal says a second person must decide")
expect_status(
403,
lambda: viewer.workflows.runs.approve(first.workflow_run_id, reason="viewer"),
"viewer1 cannot approve",
)
approver.workflows.runs.approve(first.workflow_run_id, reason="within policy")
still = admin.workflows.runs.get(first.workflow_run_id)
decided = admin.workflows.runs.approvals(first.workflow_run_id)[0]
check(
still.status == "waiting_approval"
and decided["status"] == "approved"
and decided["decided_by"] == "approver1",
"approval recorded by approver1; the run still waits for Resume",
)
expect_status(
403,
lambda: approver.workflows.runs.resume(first.workflow_run_id),
"approver1 cannot Resume (needs operator)",
)
admin.workflows.runs.resume(first.workflow_run_id)
done = settle(admin, first.workflow_run_id, FINISHED)
calls = refund_calls(done)
check(
done.status == "completed" and len(calls) == 1,
"run completed with exactly one refund call",
)
issued = calls[0]["result"]
check(
issued
== {
"amount_usd": 49.0,
"order_id": by_id["R01"]["inputs"]["order_id"],
"refund_status": "initiated",
},
f"refund issued: {issued}",
)
summary["approved_run"] = {
"run_id": done.workflow_run_id,
"approved_by": decided["decided_by"],
"refund": issued,
}
say("== 8. reject")
second = submit_case(admin, version.version_id, by_id["R01"])
check(second.status == "waiting_approval", "second run paused")
approver.workflows.runs.reject(
second.workflow_run_id, reason="customer already refunded elsewhere"
)
rejected = settle(admin, second.workflow_run_id, FINISHED)
check(
rejected.status == "failed" and rejected.extra["error_code"] == "approval_rejected",
"run failed with approval_rejected",
)
check(refund_calls(rejected) == [], "the refund never ran")
summary["rejected_run"] = {
"run_id": rejected.workflow_run_id,
"error_code": rejected.extra["error_code"],
}
say("== 9. deny and manual review")
denied = submit_case(admin, version.version_id, by_id["R23"])
check(
denied.status == "completed" and refund_calls(denied) == [],
"a deny decision completes without any approval or refund",
)
verdict = json.loads(denied.extra["summary"]["output"])
check(
verdict["decision"] == "deny" and verdict["reason_code"] == "NOT_REFUNDABLE_STATE",
f"output is the decision: {verdict}",
)
check(
admin.workflows.runs.approvals(denied.workflow_run_id) == [],
"no approval was ever requested",
)
review = submit_case(admin, version.version_id, by_id["R11"])
check(review.status == "waiting_approval", "a manual_review decision pauses for approval")
approver.workflows.runs.approve(review.workflow_run_id, reason="manager confirmed")
admin.workflows.runs.resume(review.workflow_run_id)
review_done = settle(admin, review.workflow_run_id, FINISHED)
amount = refund_calls(review_done)[0]["result"]["amount_usd"]
check(
review_done.status == "completed" and amount == by_id["R11"]["inputs"]["amount"],
f"approved manual review refunded {amount}",
)
summary["denied_run"] = denied.workflow_run_id
summary["manual_review_run"] = {"run_id": review_done.workflow_run_id, "amount_usd": amount}
say("== 10. audit trail and effect ledger")
entries = admin.audit.list(limit=500)
actions = {(e.actor, e.action) for e in entries}
for want in (
("admin", "register_tool"),
("admin", "calibrate_tool"),
("admin", "create_tool_test_run"),
("admin", "set_tool_baseline"),
("admin", "import_workflow"),
("admin", "enqueue_workflow_run"),
("admin", "resume_workflow_run"),
("approver1", "approve_workflow_run_runtime_approval"),
):
check(want in actions, f"audit has {want[1]} by {want[0]}")
reject_actions = {a for actor, a in actions if actor == "approver1" and "reject" in a}
check(reject_actions, f"audit has the rejection by approver1: {sorted(reject_actions)}")
ledger = admin.raw.get(
"/system/effects", params={"status": "any", "workflow_run_id": done.workflow_run_id}
)
rows_n = len(ledger["effects"])
say(
f" effect ledger rows for the approved run: {rows_n} "
"(the ledger covers webhook and api_request nodes, not registered tools)"
)
summary["effect_ledger_rows"] = len(ledger["effects"])
say("== 11. where the sandbox boundary stops")
probe = admin.tools.register(
f"probe_python{suffix}",
version="1.0",
module_path="caliber.workflows.demo_tools",
callable_name="sandbox_python",
input_schema={"type": "object"},
output_schema={"type": "object"},
side_effect_level="read",
allow_in_preview=True,
)
slow = admin.tools.test_invoke(
probe.tool_id, input={"code": "import time; time.sleep(300)", "timeout_seconds": 600}
)
check(
slow["output"] is None and "timed out" in (slow["error"] or ""),
f"a stalled tool is killed: {slow['error']}",
)
big = admin.tools.test_invoke(
probe.tool_id,
input={"code": "open('big.bin','wb').write(b'x'*5000000)", "timeout_seconds": 10},
)
check(
"File too large" in big["output"]["stderr"], "the file-size limit stops a large write"
)
env_probe = admin.tools.test_invoke(
probe.tool_id,
input={"code": "import os; print(sorted(os.environ))", "timeout_seconds": 10},
)
check(
"OPENAI_API_KEY" not in env_probe["output"]["stdout"]
and "CALIBER" not in env_probe["output"]["stdout"],
"the child starts with an empty environment",
)
health = f"{os.environ.get('CALIBER_BASE_URL', '').rstrip('/')}{API_PREFIX}/health"
reach = admin.tools.test_invoke(
probe.tool_id,
input={
"code": (
"import urllib.request; "
f"print(urllib.request.urlopen('{health}', timeout=3).status)"
),
"timeout_seconds": 10,
},
)
check(
reach["output"]["stdout"].strip() == "200",
"BUT the child can still reach the network: this is a process boundary, not isolation",
)
summary["sandbox_probes"] = {
"timeout": slow["error"],
"file_limit": True,
"network_reachable": True,
}
say("== 12. the gallery starter")
installed = admin.cookbooks.install(
"03", name=f"Cookbook 03 starter{suffix}", acknowledge_prerequisites=True
)
manifest = admin.workflows.versions.get(installed["version"]["version_id"]).manifest
kinds = {n["type"] for n in manifest["nodes"].values()}
check(
{"data_transform", "human_approval"} <= kinds,
"the installed draft has a decision table and a Human Approval node",
)
summary["starter_workflow_id"] = installed["workflow"]["workflow_id"]
return summary
def cleanup(admin: CaliberClient, suffix: str) -> None:
for tool in admin.tools.list():
if tool.name in {
f"{n}{suffix}" for n in ("decide_refund", "initiate_refund", "probe_python")
}:
admin.tools.archive(tool.tool_id)
say(f"archived tool {tool.name}")
for workflow in admin.workflows.list():
if workflow.name in {f"refund-decision{suffix}", f"Cookbook 03 starter{suffix}"}:
admin.workflows.delete(workflow.workflow_id)
say(f"deleted workflow {workflow.name}")
for project in admin.projects.list():
if project.name == f"refund-ops{suffix}":
admin.projects.archive(project.project_id)
say(f"archived workspace {project.name}")
def main() -> None:
base_url = os.environ["CALIBER_BASE_URL"]
suffix = os.environ.get("LAB03_SUFFIX", "")
admin = CaliberClient(base_url, token=os.environ["CALIBER_TOKEN"], timeout=180)
if "--cleanup" in sys.argv:
cleanup(admin, suffix)
return
ensure_accounts(admin)
approver = login_client(base_url, *APPROVER)
viewer = login_client(base_url, *VIEWER)
result = run(admin, approver=approver, viewer=viewer, suffix=suffix)
say("== done")
print(json.dumps(result, indent=2, sort_keys=True))
if __name__ == "__main__":
main()sdk/caliber-sdk/examples/cookbooks/cookbook_03_policy_safe_decision_tool.py — executed by the SDK example test suite.Cookbook 04 — Document-to-JSON Pipeline
Upload 30 sample documents to an object-store bucket, install the built-in Document-to-JSON Pipeline in a project, run it once per document, and check every outcome against the lab's expectations: 16 valid invoices land as JSON in the output bucket, 13 invalid ones are held at the approval gate with exact schema errors, a duplicate is refused, and one held document is approved and one rejected, leaving exactly 17 output objects. It needs an admin token, the cookbooks flag, an S3-compatible object store behind the server and a reviewer account holding the operator and approver scopes; nothing calls a model, so simulated providers change nothing. It does not use client.raw; plain httpx signs the reviewer in.
SDK surfaces: cookbooks, projects, object_store, workflows, auth
- Check the recipe's configuration checks and that the object store answers, then create a project with a second person (
reviewer) in it. - Create the
doc-intakeanddoc-extractedbuckets and upload the 30 documents underincoming/. - Install the pipeline (it installs paused), validate the draft, resume it, and run it once per document with the object key as input; compare each extracted JSON field by field and each held document's schema errors by path.
- Verify a duplicate invoice and a key that matches no object both fail with a clear message.
- Exercise the approval gate: the account that started the run is refused with 403, the reviewer approves one held document (its JSON lands under
reviewed/) and rejects another (approval_rejected, nothing written). - Confirm the output bucket holds exactly the 17 expected objects.
"""Cookbook 04: a document-to-JSON intake pipeline over the object store.
Runs the whole lab against a real CALIBER server and exits 0 only when every documented outcome
was observed:
* a workspace for the lab, with a second person (``reviewer``) in it;
* two buckets, ``doc-intake`` and ``doc-extracted``, and the 30 sample documents uploaded to
``doc-intake/incoming/``;
* the built-in Document-to-JSON Pipeline installed as a draft, then resumed (it installs paused);
* one run per document: the run input is the object key. A valid invoice is written to
``doc-extracted/invoices/<invoice number>.json``; an invalid one stops at the approval gate; the
same invoice sent twice is refused by the output bucket;
* every document's outcome checked against ``assets/dataset/extraction-cases.jsonl``, the extracted
JSON compared field by field and the schema errors compared by path;
* the approval gate: the account that started a run cannot approve it (403), the reviewer approves
one document (the approved JSON lands under ``reviewed/``) and rejects another (the run fails
and nothing is written);
* a run for a key that does not exist fails with a clear message.
Environment: ``CALIBER_BASE_URL`` (the server root) and ``CALIBER_TOKEN`` (a token for an admin
account). The server must be started with the object store behind it
(``scripts/cookbook-env.sh up lab04 --flags cookbooks --s3``) and with ``reviewer`` holding the
operator and approver platform scopes (``CALIBER_OPERATOR_USERS`` and ``CALIBER_APPROVER_USERS``
both ``admin,reviewer``). Optional ``LAB04_SUFFIX`` sets the suffix that makes the workspace and
workflow names unique (default: the current time, so the script can be re-run on a stack that holds
an earlier run). ``--cleanup`` removes what runs created.
Nothing here calls a model: the extractor is a deterministic python_code node and the validation is
a JSON Schema, so the outcome is the same under the default simulated providers as under a real one.
"""
from __future__ import annotations
import json
import os
import sys
import time
from pathlib import Path
from typing import Any
import httpx
from caliber_sdk import CaliberClient
from caliber_sdk.errors import CaliberAPIError, CaliberError
from examples.cookbooks._helpers import PAUSED_OR_TERMINAL_RUN_STATES, get_recipe
LAB_DIR = (
Path(__file__).resolve().parents[4]
/ "docs-site/cookbooks/04-document-extraction-structuring-lab"
)
ASSETS = LAB_DIR / "assets"
INPUT_BUCKET = "doc-intake"
OUTPUT_BUCKET = "doc-extracted"
REVIEWER = ("reviewer", "reviewer-pass-123")
API_PREFIX = "/ajax-api/2.0/mlflow/caliber"
FINISHED = frozenset({"completed", "succeeded", "failed", "cancelled", "timed_out"})
class LabVerificationError(AssertionError):
"""A documented outcome did not hold."""
def say(message: str) -> None:
print(message, flush=True)
def check(condition: object, message: str) -> None:
if not condition:
raise LabVerificationError(message)
say(f" ok {message}")
def load_cases() -> list[dict[str, Any]]:
path = ASSETS / "dataset/extraction-cases.jsonl"
return [
json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()
]
def login_client(
base_url: str, user: str, password: str, *, timeout: float = 60.0
) -> CaliberClient:
"""Sign in as ``user`` and mint a personal access token (a script cannot reuse a cookie)."""
api = base_url.rstrip("/") + API_PREFIX
login = httpx.post(f"{api}/auth/login", json={"user_id": user, "password": password})
login.raise_for_status()
issued = httpx.post(
f"{api}/auth/tokens",
json={"name": f"cookbook-04-{user}", "scopes": ["caliber.operator", "caliber.approver"]},
cookies=login.cookies,
)
issued.raise_for_status()
return CaliberClient(base_url, token=issued.json()["data"]["token"], timeout=timeout)
def ensure_reviewer(admin: CaliberClient) -> None:
user, password = REVIEWER
try:
admin.auth.accounts.create(user, password)
say(f" created account {user}")
except CaliberError:
admin.auth.accounts.update(user, password=password)
say(f" account {user} already existed; password reset to the lab value")
def wait_for(
caliber: CaliberClient, run_id: str, *, until: frozenset[str], timeout: float = 120.0
) -> Any:
deadline = time.monotonic() + timeout
while True:
run = caliber.workflows.runs.get(run_id)
if run.status in until:
return run
if time.monotonic() > deadline:
raise LabVerificationError(f"run {run_id} stayed {run.status!r} for {timeout:.0f}s")
time.sleep(0.5)
def error_text(run: Any) -> str:
return str(run.extra.get("error_summary") or run.error or "")
def schema_errors(caliber: CaliberClient, run_id: str) -> list[dict[str, Any]]:
"""The JSON Schema errors the validate_schema node reported, read from the run's events."""
for event in caliber.workflows.runs.events(run_id, limit=200):
step = (event.get("payload") or {}).get("step") or {}
if (
event.get("event_type") == "workflow.run.step"
and step.get("node_id") == "validate_schema"
):
return list((step.get("output_by_port") or {}).get("metadata", {}).get("errors") or [])
return []
def reset_buckets(caliber: CaliberClient) -> None:
existing = {bucket.name for bucket in caliber.object_store.buckets()}
for bucket in (INPUT_BUCKET, OUTPUT_BUCKET):
if bucket not in existing:
caliber.object_store.create_bucket(bucket)
say(f" created bucket {bucket}")
keys = [o.key for o in caliber.object_store.objects(OUTPUT_BUCKET, recursive=True)]
if keys:
caliber.object_store.delete_objects(OUTPUT_BUCKET, keys=keys)
say(f" emptied {OUTPUT_BUCKET} ({len(keys)} objects)")
def upload_documents(caliber: CaliberClient, cases: list[dict[str, Any]]) -> None:
for case in cases:
key = case["inputs"]["key"]
filename = key.split("/", 1)[1]
caliber.object_store.upload(
INPUT_BUCKET,
filename=filename,
content=(ASSETS / "dataset/sources" / filename).read_bytes(),
key=key,
)
stored = {o.key for o in caliber.object_store.objects(INPUT_BUCKET, prefix="incoming/")}
check(
stored == {c["inputs"]["key"] for c in cases},
f"{len(cases)} documents are in {INPUT_BUCKET}/incoming/",
)
def start(caliber: CaliberClient, version_id: str, key: str) -> Any:
return caliber.workflows.runs.submit(workflow_version_id=version_id, input=key)
def read_json(caliber: CaliberClient, bucket: str, key: str) -> dict[str, Any]:
document: dict[str, Any] = json.loads(caliber.object_store.download(bucket, key))
return document
def verify_extracted(caliber: CaliberClient, case: dict[str, Any], run: Any) -> None:
expected = case["expectations"]["record"]
check(run.status == "completed", f"{case['id']} {case['inputs']['key']} completed")
stored = read_json(caliber, OUTPUT_BUCKET, f"invoices/{expected['invoice_number']}.json")
mismatched = [k for k, v in expected.items() if stored.get(k) != v]
check(
not mismatched,
f"{case['id']} invoices/{expected['invoice_number']}.json matches the expected JSON",
)
check(
stored["source_key"] == case["inputs"]["key"],
f"{case['id']} keeps its source key (lineage)",
)
def verify_held(caliber: CaliberClient, case: dict[str, Any], run: Any) -> None:
check(
run.status == "waiting_approval",
f"{case['id']} {case['inputs']['key']} is held for approval",
)
paths = sorted({e["path"] for e in schema_errors(caliber, run.workflow_run_id)})
wanted = sorted(case["expectations"]["errors"])
check(paths == wanted, f"{case['id']} reports schema errors at exactly {wanted} (got {paths})")
def run(
admin: CaliberClient,
*,
reviewer: CaliberClient,
suffix: str = "",
) -> dict[str, Any]:
cases = load_cases()
summary: dict[str, Any] = {"documents": len(cases)}
say("== 0. prerequisites")
recipe = get_recipe(admin, "04")
blockers = [
c["label"] for c in recipe.unmet_checks if c.get("status") == "configuration_required"
]
check(not blockers, f"the cookbook's configuration checks pass (blocked by: {blockers})")
status = admin.object_store.status()
check(status.get("connected") is True, f"the object store answers at {status.get('endpoint')}")
say("== 1. workspace and reviewer")
project = admin.projects.create(
f"invoice-intake{suffix}", description="Cookbook 04 invoice intake"
)
admin.projects.add_member(project.project_id, REVIEWER[0], role="reviewer")
summary["project_id"] = project.project_id
say("== 2. buckets and documents")
reset_buckets(admin)
upload_documents(admin, cases)
with admin.workspace_scope(project.project_id), reviewer.workspace_scope(project.project_id):
say("== 3. install the pipeline and resume it")
installed = admin.cookbooks.install(
"04",
name=f"doc-intake-to-json{suffix}",
acknowledge_prerequisites=bool(recipe.prerequisites),
)
workflow_id = installed["workflow"]["workflow_id"]
version_id = installed["version"]["version_id"]
check(installed["workflow"]["status"] == "paused", "the cookbook installs paused")
check(admin.workflows.versions.validate(version_id)["valid"], "the draft version validates")
admin.workflows.update(workflow_id, status="active")
summary.update(workflow_id=workflow_id, version_id=version_id)
say("== 4. one run per document")
first = [c for c in cases if c["expectations"]["outcome"] != "duplicate"]
runs = {c["id"]: start(admin, version_id, c["inputs"]["key"]) for c in first}
for case in first:
runs[case["id"]] = wait_for(
admin, runs[case["id"]].workflow_run_id, until=PAUSED_OR_TERMINAL_RUN_STATES
)
for case in first:
outcome = case["expectations"]["outcome"]
if outcome == "extracted":
verify_extracted(admin, case, runs[case["id"]])
else:
verify_held(admin, case, runs[case["id"]])
summary["extracted"] = sorted(
c["id"] for c in first if c["expectations"]["outcome"] == "extracted"
)
summary["held"] = sorted(
c["id"] for c in first if c["expectations"]["outcome"] == "needs_review"
)
say("== 5. a duplicate invoice is refused")
for case in (c for c in cases if c["expectations"]["outcome"] == "duplicate"):
dup = wait_for(
admin,
start(admin, version_id, case["inputs"]["key"]).workflow_run_id,
until=FINISHED,
)
check(dup.status == "failed", f"{case['id']} duplicate run failed")
check(
case["expectations"]["error_contains"] in error_text(dup),
f"it says why: {error_text(dup)}",
)
original = read_json(
admin, OUTPUT_BUCKET, f"invoices/{case['expectations']['duplicate_of']}.json"
)
check(
original["source_key"].endswith("inv-2026-0101-acme.txt"),
"the first invoice's JSON is untouched",
)
summary["duplicate_error"] = error_text(dup)
say("== 6. a key that matches no object")
missing = wait_for(
admin,
start(admin, version_id, "incoming/does-not-exist.txt").workflow_run_id,
until=FINISHED,
)
check(
missing.status == "failed" and "found 0" in error_text(missing),
f"fails clearly: {error_text(missing)}",
)
summary["missing_object_error"] = error_text(missing)
say("== 7. the approval gate")
approve_case = next(
c for c in first if c["inputs"]["key"].endswith("inv-2026-0115-no-total.txt")
)
reject_case = next(
c for c in first if c["inputs"]["key"].endswith("inv-2026-0117-no-vendor.txt")
)
approve_id = runs[approve_case["id"]].workflow_run_id
reject_id = runs[reject_case["id"]].workflow_run_id
try:
admin.workflows.runs.approve(approve_id, reason="self approval")
except CaliberAPIError as exc:
check(
exc.status_code == 403,
f"the account that started the run cannot approve it (HTTP {exc.status_code})",
)
summary["self_approval_error"] = str(exc)
else:
raise LabVerificationError("the initiator approved their own run")
reviewer.workflows.runs.approve(
approve_id, reason="vendor confirmed the missing total by phone"
)
reviewer.workflows.runs.resume(approve_id)
done = wait_for(admin, approve_id, until=FINISHED)
check(
done.status == "completed", f"{approve_case['id']} completes after approval and resume"
)
stem = approve_case["inputs"]["key"].split("/")[-1].rsplit(".", 1)[0]
approved = read_json(admin, OUTPUT_BUCKET, f"reviewed/{stem}.json")
check(
approved["review"]["decision"] == "approved",
f"reviewed/{stem}.json records the approval",
)
check(
[e["path"] for e in approved["review"]["schema_errors"]] == ["total"],
"the approved JSON keeps the schema errors it was approved with",
)
reviewer.workflows.runs.reject(reject_id, reason="not one of our suppliers")
rejected = wait_for(admin, reject_id, until=FINISHED)
check(rejected.status == "failed", f"{reject_case['id']} fails after rejection")
check(
rejected.extra.get("error_code") == "approval_rejected",
"its error code is approval_rejected",
)
say("== 8. what reached the output bucket")
stored = {o.key for o in admin.object_store.objects(OUTPUT_BUCKET, recursive=True)}
expected = {
f"invoices/{c['expectations']['record']['invoice_number']}.json"
for c in cases
if c["expectations"]["outcome"] == "extracted"
} | {f"reviewed/{stem}.json"}
check(
stored == expected,
f"{OUTPUT_BUCKET} holds exactly the {len(expected)} expected objects",
)
summary["output_objects"] = sorted(stored)
summary["still_waiting"] = len(summary["held"]) - 2
return summary
def cleanup(admin: CaliberClient) -> None:
"""Remove what runs created: the objects, the buckets and the workspaces (archived)."""
for bucket in (INPUT_BUCKET, OUTPUT_BUCKET):
try:
keys = [o.key for o in admin.object_store.objects(bucket, recursive=True)]
if keys:
admin.object_store.delete_objects(bucket, keys=keys)
# Folders created in the web app leave an empty marker object behind.
for folder in admin.object_store.folders(bucket):
admin.object_store.delete_objects(bucket, prefix=folder)
admin.object_store.delete_bucket(bucket)
say(f" removed bucket {bucket}")
except CaliberError as exc:
say(f" bucket {bucket}: {exc}")
for project in admin.projects.list():
if project.name.startswith("invoice-intake") and project.status == "active":
admin.projects.archive(project.project_id)
say(f" archived workspace {project.name}")
def main() -> None:
base_url = os.environ["CALIBER_BASE_URL"]
suffix = os.environ.get("LAB04_SUFFIX") or f"-{int(time.time())}"
admin = CaliberClient(base_url, token=os.environ["CALIBER_TOKEN"], timeout=180)
if "--cleanup" in sys.argv:
cleanup(admin)
return
ensure_reviewer(admin)
reviewer = login_client(base_url, *REVIEWER)
result = run(admin, reviewer=reviewer, suffix=suffix)
say("== done")
print(json.dumps(result, indent=2, sort_keys=True))
if __name__ == "__main__":
main()sdk/caliber-sdk/examples/cookbooks/cookbook_04_document_to_json_pipeline.py — executed by the SDK example test suite.Cookbook 05 — Governed Tool Connectivity
Register the lab's own stdio MCP server in a project, discover its six tools (all start unclassified and denied), classify them, then invoke a read tool, check refusals (blocked, unknown, rate limited) and prove from the server's ledger that a refused call never reached it, calibrate three read tools (16/16, 8/8, 4/4) and catch a deliberately wrong expectation, and run the write tool behind a workflow approval gate. It needs an admin token, the integrations and cookbooks flags, operator and approver accounts, and the MCP server script on the stdio allowlist; it runs a real MCP server and no model, so nothing is simulated. It does not use client.raw; plain httpx signs the lab accounts in.
SDK surfaces: projects, mcp_servers, workflows, observability, audit, auth, cookbooks
- Create a project with operator, approver and viewer accounts, register the stdio MCP server, run
test_connectionanddiscover_tools, and check the server-side refusals (an unclassified tool cannot be called, a write tool needsrequires_approval). - Classify every tool through
update_tool_policy, then invoke the allowed read tool and check the ledger shows exactly one execution. - Save 28 test cases and calibrate the three read tools, catch one wrong expectation (15/16, pass rate 0.9375), and check calibrating an approval-class, case-less or missing tool is refused (409, 400, 404).
- Check the refusals (blocked
create_release, unknowndrop_database, over the rate limit) and the tool's own errors, and that the ledger shows none of the refused calls ran. - Bind the write tool in an imported workflow: it stops at
waiting_approval, the initiator's approval is 403, and it runs once only after a second person approves and the run is resumed; a blocked tool in a workflow is refused at submit. - Check that
/bin/sh,python -cand loopback HTTP servers are registered but refused, then read the history, audit log andmcp.<server>.<tool>traces (a refusal leaves none) and install the gallery starter.
"""Cookbook 05: govern an MCP server's tools, from registration to the trace an invoke leaves.
Runs the whole lab against a real CALIBER server and a real MCP server (the lab's own
``assets/server/repo_tracker_mcp.py``, started by CALIBER over stdio) and exits 0 only when every
documented outcome was observed:
* register the server in a workspace (people and roles as in the README), discover its six tools;
* see that nothing is callable until classified, then classify each tool from
``tool-classification.jsonl``;
* invoke an allowed read tool, see the refusals (blocked, unknown, rate limited) and the tool's own
errors, and prove from the server's ledger that a refused call never reached it;
* save 28 test cases, calibrate three read tools, and catch a deliberately broken expectation;
* bind the write tool in a workflow and watch the approval gate hold it until a second person
decides;
* read the audit trail and the ``mcp.<server>.<tool>`` traces, and see which calls leave none.
Environment: ``CALIBER_BASE_URL`` (the server root) and ``CALIBER_TOKEN`` (a token for an admin
account). ``CALIBER_STATE_DIR`` (set by ``scripts/cookbook-env.sh``) or ``LAB05_LEDGER`` says
where the MCP server's call ledger lives (an absolute path, no spaces). Optional ``LAB05_SUFFIX``
makes every name unique so the script can be re-run on a stack that already holds an earlier run
(the rate-limit check needs a minute between runs). ``--cleanup`` removes what a run created.
The CALIBER server must be started with the lab's accounts as platform scopes and with the MCP
server script allowed to run as a stdio command; see the README.
"""
from __future__ import annotations
import json
import os
import sys
import time
from contextlib import ExitStack
from pathlib import Path
from typing import Any
import httpx
from caliber_sdk import CaliberClient
from caliber_sdk.errors import CaliberAPIError, CaliberError
LAB_DIR = (
Path(__file__).resolve().parents[4] / "docs-site/cookbooks/05-mcp-connectivity-governance-lab"
)
ASSETS = LAB_DIR / "assets"
SERVER_SCRIPT = ASSETS / "server/repo_tracker_mcp.py"
API_PREFIX = "/ajax-api/2.0/mlflow/caliber"
OPERATOR = ("lab05-operator", "lab05-operator-password")
APPROVER = ("lab05-approver", "lab05-approver-password")
VIEWER = ("lab05-viewer", "lab05-viewer-password")
WRITE_REPO = "acme/release-notes-bot"
SETTLED = frozenset(
{"waiting_approval", "completed", "succeeded", "failed", "cancelled", "timed_out"}
)
FINISHED = frozenset({"completed", "succeeded", "failed", "cancelled", "timed_out"})
EXPECTED_TOOLS = {
"search_repositories",
"list_issues",
"get_issue",
"scan_dependencies",
"issue_write",
"create_release",
}
def say(message: str) -> None:
print(message, flush=True)
def check(condition: object, message: str) -> None:
if not condition:
raise AssertionError(message)
say(f" ok {message}")
def expect_status(status: int, action: Any, message: str) -> CaliberAPIError:
try:
action()
except CaliberAPIError as exc:
check(exc.status_code == status, f"{message} -> HTTP {exc.status_code}")
return exc
raise AssertionError(f"{message}: expected HTTP {status}, the call succeeded")
def read_jsonl(name: str) -> list[dict[str, Any]]:
path = ASSETS / "dataset" / name
return [json.loads(line) for line in path.read_text().splitlines() if line.strip()]
def ledger_path() -> Path:
explicit = os.environ.get("LAB05_LEDGER")
if explicit:
return Path(explicit)
state = os.environ.get("CALIBER_STATE_DIR")
if not state:
raise SystemExit("set CALIBER_STATE_DIR (source the env.sh) or LAB05_LEDGER")
return Path(state) / "lab05-sdk-ledger.jsonl"
def ledger_entries(path: Path) -> list[dict[str, Any]]:
if not path.exists():
return []
return [json.loads(line) for line in path.read_text().splitlines() if line.strip()]
def executed(path: Path, tool: str) -> int:
"""How many times the MCP server itself executed ``tool`` (read from its own ledger)."""
return sum(1 for entry in ledger_entries(path) if entry["tool"] == tool)
def login_client(
base_url: str, user: str, password: str, *, timeout: float = 120.0
) -> CaliberClient:
"""Sign in as ``user`` and mint a personal access token (a script cannot reuse a cookie)."""
api = base_url.rstrip("/") + API_PREFIX
login = httpx.post(f"{api}/auth/login", json={"user_id": user, "password": password})
login.raise_for_status()
issued = httpx.post(
f"{api}/auth/tokens", json={"name": f"cookbook-05-{user}"}, cookies=login.cookies
)
issued.raise_for_status()
return CaliberClient(base_url, token=issued.json()["data"]["token"], timeout=timeout)
def ensure_accounts(admin: CaliberClient) -> None:
for user, password in (OPERATOR, APPROVER, VIEWER):
try:
admin.auth.accounts.create(user, password)
say(f" created account {user}")
except CaliberError:
admin.auth.accounts.update(user, password=password)
say(f" account {user} already existed; password reset to the lab value")
def server_args(ledger: Path) -> list[str]:
return [str(SERVER_SCRIPT), "--ledger", str(ledger)]
def workflow_yaml(server_id: str, tool: str, level: str, approval: bool) -> str:
text = (ASSETS / "workflow/file-issue.workflow.yaml").read_text()
for placeholder, value in (
("__SERVER_ID__", server_id),
("__TOOL__", tool),
("__LEVEL__", level),
("__APPROVAL__", "true" if approval else "false"),
):
text = text.replace(placeholder, value)
return text
def settle(caliber: CaliberClient, run_id: str, states: frozenset[str] = SETTLED) -> Any:
deadline = time.monotonic() + 120
run = caliber.workflows.runs.get(run_id)
while time.monotonic() < deadline:
run = caliber.workflows.runs.get(run_id)
if run.status in states:
return run
time.sleep(1)
raise AssertionError(f"run {run_id} did not settle (last status {run.status!r})")
def mcp_traces(admin: CaliberClient, prefix: str) -> list[Any]:
return [
trace
for trace in admin.observability.traces(limit=200)
if str(trace.extra.get("name", "")).startswith(prefix)
]
def trace_names(admin: CaliberClient, prefix: str) -> dict[str, int]:
"""Count the ``mcp.<server>.<tool>`` traces once MLflow has finished writing them."""
previous: dict[str, int] | None = None
for _ in range(20):
counts: dict[str, int] = {}
for trace in mcp_traces(admin, prefix):
name = str(trace.extra["name"])
counts[name] = counts.get(name, 0) + 1
if counts and counts == previous:
return counts
previous = counts
time.sleep(1.5)
return previous or {}
def run(
admin: CaliberClient,
*,
operator: CaliberClient,
approver: CaliberClient,
viewer: CaliberClient,
ledger: Path,
suffix: str = "",
) -> dict[str, Any]:
classification = {row["tool"]: row for row in read_jsonl("tool-classification.jsonl")}
cases = read_jsonl("calibration-cases.jsonl")
checks = {row["id"]: row for row in read_jsonl("invoke-checks.jsonl")}
summary: dict[str, Any] = {"calibration_cases": len(cases)}
ledger.parent.mkdir(parents=True, exist_ok=True)
ledger.write_text("")
name = f"repo-tracker{suffix}"
prefix = f"mcp.{name}."
say("== 1. workspace and people")
project = admin.projects.create(f"mcp-ops{suffix}", description="Cookbook 05 MCP governance")
admin.projects.add_member(project.project_id, OPERATOR[0], role="editor")
admin.projects.add_member(project.project_id, APPROVER[0], role="reviewer")
admin.projects.add_member(project.project_id, VIEWER[0], role="viewer")
summary["project_id"] = project.project_id
say(
f" workspace {project.project_id}: admin owns it, operator edits, "
"approver reviews, viewer reads"
)
with ExitStack() as scope:
for client in (admin, operator, approver, viewer):
scope.enter_context(client.workspace_scope(project.project_id))
say("== 2. register the MCP server")
expect_status(
403,
lambda: operator.mcp_servers.create(name, transport="stdio", command="${PYTHON}"),
"an operator without the admin scope cannot register a server",
)
server = admin.mcp_servers.create(
name,
description="Engineering repo tracker (the lab's own MCP server)",
transport="stdio",
command="${PYTHON}",
args=server_args(ledger),
)
check(server.status == "active", f"registered {server.server_id} ({server.transport})")
execution = server.extra["execution"]
check(
execution["ready"] and execution["boundary"] == "local_containment",
"readiness: ready, boundary local_containment (a child process, not a sandbox)",
)
check(
any("does not block filesystem or network" in w for w in execution["warnings"]),
"readiness warns that stdio containment does not block files or network",
)
expect_status(
409,
lambda: admin.mcp_servers.create(name, transport="stdio", command="${PYTHON}"),
"registering the same name twice is refused",
)
summary["server_id"] = server.server_id
sid = server.server_id
say("== 3. test the connection and discover the tools")
expect_status(
403,
lambda: viewer.mcp_servers.test_connection(sid),
"a viewer cannot test the connection",
)
probe = admin.mcp_servers.test_connection(sid)
names = {tool["name"] for tool in probe["tools"]}
check(
probe["success"] and names == EXPECTED_TOOLS,
f"connected: {len(names)} tools discovered",
)
check(
all(tool["input_schema"].get("properties") for tool in probe["tools"]),
"every tool carries an input schema",
)
write_schema = next(t for t in probe["tools"] if t["name"] == "issue_write")["input_schema"]
check(
set(write_schema["required"]) == {"repo", "title"},
f"issue_write requires {sorted(write_schema['required'])}",
)
refreshed = admin.mcp_servers.discover_tools(sid)
check(refreshed["tool_count"] == len(EXPECTED_TOOLS), "discover-tools agrees: 6 tools")
listing = admin.mcp_servers.tools(sid)["tools"]
check(
all(not t["classified"] and t["policy"]["allowed"] is False for t in listing),
"every discovered tool starts unclassified and denied",
)
summary["tools"] = sorted(names)
say("== 4. an unclassified tool cannot be called")
refusal = admin.mcp_servers.invoke_tool(sid, **_invoke(checks["F01"]))
check(
refusal["success"] is False
and checks["F01"]["expect"]["error_contains"] in refusal["error"],
f"refused: {refusal['error']}",
)
check(
executed(ledger, "search_repositories") == 0,
"the server's ledger is empty: nothing ran",
)
say("== 5. classify every tool")
unsafe = classification["issue_write"]
error = expect_status(
400,
lambda: admin.mcp_servers.update_tool_policy(
sid, "issue_write", allowed=True, side_effect_level="write", requires_approval=False
),
"an allowed write tool without requires_approval is rejected",
)
check("requires_approval" in str(error), "the rejection names requires_approval")
expect_status(
403,
lambda: operator.mcp_servers.update_tool_policy(
sid,
"search_repositories",
allowed=True,
side_effect_level="read",
requires_approval=False,
),
"an operator without the admin scope cannot classify",
)
for tool, row in classification.items():
policy = {
key: row[key]
for key in (
"allowed",
"side_effect_level",
"requires_approval",
"rate_limit_per_minute",
)
if key in row
}
admin.mcp_servers.update_tool_policy(sid, tool, **policy)
listing = {t["name"]: t for t in admin.mcp_servers.tools(sid)["tools"]}
check(all(t["classified"] for t in listing.values()), "all six tools are classified")
check(
all(
listing[tool]["policy"]["allowed"] == row["allowed"]
and listing[tool]["policy"]["side_effect_level"] == row["side_effect_level"]
and listing[tool]["policy"]["requires_approval"] == row["requires_approval"]
for tool, row in classification.items()
),
"the stored policies equal tool-classification.jsonl",
)
check(
unsafe["requires_approval"] and listing["issue_write"]["policy"]["requires_approval"],
"issue_write is allowed but requires approval",
)
check(
listing["create_release"]["policy"]["allowed"] is False,
"create_release (external_action) is blocked",
)
say("== 6. invoke an allowed read tool")
call = admin.mcp_servers.invoke_tool(
sid, "search_repositories", arguments={"query": "language:python topic:mcp"}
)
found = [item["full_name"] for item in call["result"]["items"]]
check(
call["success"] and found == ["acme/mcp-gateway", "acme/mcp-servers-internal"],
f"search returned {found} in {call['duration_ms']} ms",
)
check(
executed(ledger, "search_repositories") == 1, "the server's ledger shows one execution"
)
expect_status(
403,
lambda: viewer.mcp_servers.invoke_tool(
sid, "search_repositories", arguments={"query": "go"}
),
"a viewer cannot invoke a tool",
)
expect_status(
403,
lambda: operator.mcp_servers.invoke_tool(
sid, "search_repositories", arguments={"query": "go"}
),
"an operator without the admin scope cannot invoke a tool",
)
say("== 7. save test cases and calibrate the read tools")
by_tool: dict[str, list[dict[str, Any]]] = {}
for row in cases:
by_tool.setdefault(row["tool_name"], []).append(
{
"name": f"{row['id']} {row['name']}",
"input": row["input"],
"assertion": row["assertion"],
}
)
expect_status(
403,
lambda: viewer.mcp_servers.save_test_cases(
sid, "search_repositories", by_tool["search_repositories"]
),
"a viewer cannot save test cases",
)
rates: dict[str, Any] = {}
for tool, tool_cases in by_tool.items():
operator.mcp_servers.save_test_cases(sid, tool, tool_cases)
started = time.monotonic()
scored = operator.mcp_servers.calibrate_tool(sid, tool)
rates[tool] = {
"passed": scored["passed"],
"total": scored["total"],
"pass_rate": scored["pass_rate"],
}
check(
(scored["total"], scored["passed"], scored["pass_rate"])
== (len(tool_cases), len(tool_cases), 1.0),
f"{tool}: {scored['passed']}/{scored['total']} passed, "
f"pass_rate {scored['pass_rate']} "
f"({round(time.monotonic() - started)}s)",
)
summary["calibration"] = rates
broken = [dict(c) for c in by_tool["search_repositories"]]
wrong = broken[0]["name"]
broken[0]["assertion"] = {"type": "output_contains", "value": '"total_count": 9'}
operator.mcp_servers.save_test_cases(sid, "search_repositories", broken)
drilled = operator.mcp_servers.calibrate_tool(sid, "search_repositories")
failing = [c["name"] for c in drilled["cases"] if not c["passed"]]
check(
failing == [wrong] and drilled["pass_rate"] == 0.9375,
f"a wrong expectation fails exactly one case: {failing}, "
f"pass_rate {drilled['pass_rate']}",
)
operator.mcp_servers.save_test_cases(
sid, "search_repositories", by_tool["search_repositories"]
)
expect_status(
409,
lambda: operator.mcp_servers.calibrate_tool(sid, "issue_write"),
"a tool that requires approval cannot be calibrated (no approval checkpoint)",
)
expect_status(
400,
lambda: operator.mcp_servers.calibrate_tool(sid, "scan_dependencies"),
"a tool with no saved cases cannot be calibrated",
)
expect_status(
404,
lambda: operator.mcp_servers.calibrate_tool(sid, "drop_database"),
"calibrating a tool the server does not have is a 404",
)
before = {tool: executed(ledger, tool) for tool in EXPECTED_TOOLS}
say("== 8. refusals and failures")
results: dict[str, Any] = {}
for check_id in ("F02", "F03", "F05", "F06", "F07", "F08", "F09"):
row = checks[check_id]
started = time.monotonic()
got = admin.mcp_servers.invoke_tool(sid, **_invoke(row))
seconds = round(time.monotonic() - started)
results[check_id] = got
check(
got["success"] is False and row["expect"]["error_contains"] in got["error"],
f"{check_id} {row['what']} -> {row['expect']['error_contains']!r}"
+ (f" ({seconds}s)" if row.get("slow") else ""),
)
row = checks["F04"]
accepted = 1 # F09's timed-out call spent one of the three calls a minute
refused_after = None
for _ in range(5):
got = admin.mcp_servers.invoke_tool(sid, **_invoke(row))
if got["success"]:
accepted += 1
else:
refused_after = accepted
check(
row["expect"]["error_contains"] in got["error"],
f"F04 {row['what']} -> {got['error']}",
)
break
check(refused_after == 3, "the fourth call in the minute was the refused one")
check(
executed(ledger, "create_release") == 0 and before["create_release"] == 0,
"the blocked create_release never reached the server (ledger: 0 executions)",
)
check(
all(
executed(ledger, t) == before[t]
for t in ("create_release", "issue_write", "get_issue")
),
"no other refusal reached the server either",
)
say("== 9. an approval-class write tool, from the admin Playground")
row = checks["F10"]
written = admin.mcp_servers.invoke_tool(sid, **_invoke(row))
check(
written["success"]
and written["result"]
== {
"created": True,
"repo": WRITE_REPO,
"number": 1,
"title": row["arguments"]["title"],
},
f"direct invoke ran: {written['result']}",
)
check(
executed(ledger, "issue_write") == 1,
"the ledger records the write: the Playground is a break-glass surface, "
"not the approval gate",
)
issues = admin.mcp_servers.invoke_tool(
sid, "list_issues", arguments={"repo": WRITE_REPO, "state": "open"}
)
check(issues["result"]["total_count"] == 1, "list_issues shows the issue that was filed")
say("== 10. the approval gate in a workflow")
text = workflow_yaml(sid, "issue_write", "write", True)
preview = admin.workflows.preview_import(manifest_yaml=text)
dependency = preview["dependencies"][0]
check(
preview["ready_to_import"]
and dependency["kind"] == "mcp_tool"
and dependency["status"] == "resolved",
f"import preview resolves {dependency['reference']}",
)
workflow = admin.workflows.import_workflow(
manifest_yaml=text, name=f"mcp-file-issue{suffix}"
)
version = admin.workflows.versions.list(workflow.workflow_id)[0]
summary["workflow_id"] = workflow.workflow_id
payload = {
"repo": WRITE_REPO,
"title": "Release notes bot posts twice on re-run",
"body": "Filed by a workflow, after a second person approved it.",
"labels": ["bug"],
}
first = admin.workflows.runs.submit(
workflow_version_id=version.version_id, input=json.dumps(payload)
)
waiting = settle(admin, first.workflow_run_id)
check(
waiting.status == "waiting_approval"
and waiting.extra["current_node_id"] == "call_tool",
"the run paused at the call_tool node",
)
check(executed(ledger, "issue_write") == 1, "nothing was written while the run waited")
exc = expect_status(
403,
lambda: admin.workflows.runs.approve(first.workflow_run_id, reason="self"),
"the initiator cannot approve their own run",
)
check("second person" in str(exc), "the refusal says a second person must decide")
expect_status(
403,
lambda: viewer.workflows.runs.approve(first.workflow_run_id, reason="viewer"),
"a viewer cannot approve",
)
approver.workflows.runs.approve(first.workflow_run_id, reason="matches the release process")
check(executed(ledger, "issue_write") == 1, "approving alone does not run the tool")
admin.workflows.runs.resume(first.workflow_run_id)
done = settle(admin, first.workflow_run_id, FINISHED)
check(done.status == "completed", f"after Resume the run {done.status}")
check(executed(ledger, "issue_write") == 2, "the workflow's write executed exactly once")
issues = admin.mcp_servers.invoke_tool(
sid, "list_issues", arguments={"repo": WRITE_REPO, "state": "open"}
)
titles = [i["title"] for i in issues["result"]["issues"]]
check(
payload["title"] in titles and issues["result"]["total_count"] == 2,
"the issue the workflow filed is on the server",
)
summary["approved_run"] = done.workflow_run_id
say("== 11. a blocked tool inside a workflow")
blocked_text = workflow_yaml(sid, "create_release", "external_action", False)
blocked = admin.workflows.import_workflow(
manifest_yaml=blocked_text, name=f"mcp-release{suffix}"
)
blocked_version = admin.workflows.versions.list(blocked.workflow_id)[0]
refused = expect_status(
400,
lambda: admin.workflows.runs.submit(
workflow_version_id=blocked_version.version_id,
input=json.dumps({"repo": WRITE_REPO, "tag": "v2.4.0"}),
),
"a run is refused before it starts",
)
check(
"MCP runtime preflight failed" in str(refused) and "blocked by policy" in str(refused),
"the preflight names the tool: blocked by policy",
)
check(
executed(ledger, "create_release") == 0, "create_release still never reached the server"
)
say("== 12. servers CALIBER will not run")
rogue = admin.mcp_servers.create(
f"rogue-shell{suffix}", transport="stdio", command="/bin/sh", args=["-c", "echo pwned"]
)
check(
rogue.extra["execution"]["ready"] is False
and rogue.extra["execution"]["command_allowed"] is False,
"a /bin/sh command is registered but not ready: not on the command allowlist",
)
tried = admin.mcp_servers.test_connection(rogue.server_id)
check(
tried["success"] is False and "CALIBER_MCP_STDIO_COMMAND_ALLOWLIST" in tried["error"],
f"test-connection refuses it: {tried['error']}",
)
inline = admin.mcp_servers.create(
f"rogue-python{suffix}", transport="stdio", command="${PYTHON}", args=["-c", "print(1)"]
)
tried = admin.mcp_servers.test_connection(inline.server_id)
check(
tried["success"] is False and "allowlisted '-m' module" in tried["error"],
"python -c is refused: only an allowlisted -m module or script may run",
)
loopback = admin.mcp_servers.create(
f"loopback-http{suffix}",
transport="streamable-http",
uri="http://127.0.0.1:9/mcp",
)
tried = admin.mcp_servers.test_connection(loopback.server_id)
check(
tried["success"] is False and "blocked loopback range" in tried["error"],
"a loopback HTTP endpoint is refused by the egress policy, even though the host "
"allowlist names it",
)
summary["refused_servers"] = [rogue.server_id, inline.server_id, loopback.server_id]
history = admin.mcp_servers.history(rogue.server_id)
check(
[h["action"] for h in history] == ["create_mcp_server"],
"a refused test leaves only the registration in that server's history",
)
say("== 13. history and audit")
actions = [entry["action"] for entry in admin.mcp_servers.history(sid)]
for action in (
"create_mcp_server",
"update_mcp_tool_policy",
"update_mcp_tool_test_cases",
"calibrate_mcp_tool",
):
check(action in actions, f"history has {action}")
check(
actions.count("update_mcp_tool_policy") == len(classification),
f"one policy change per tool ({len(classification)})",
)
audited = {(e.actor, e.action) for e in admin.audit.list(limit=200) if e.entity_id == sid}
check(
("lab05-operator", "calibrate_mcp_tool") in audited,
"the audit log names lab05-operator for the calibrations",
)
say("== 14. the traces")
counts = trace_names(admin, prefix)
check(
counts.get(f"{prefix}issue_write") == 1,
"one standalone issue_write trace: the Playground write",
)
spans: list[str] = []
for _ in range(20): # MLflow writes the run's trace a moment after the run settles
spans = [
s["name"] for s in admin.workflows.runs.trace(summary["approved_run"])["spans"]
]
if len(spans) >= 5:
break
time.sleep(1.5)
check(
sorted(spans)
== sorted(
[
"workflow.run",
"node.call_tool",
"tool.issue_write",
f"{prefix}issue_write",
"node.done",
]
),
"the workflow's write is the same span, nested in the run's own trace: "
f"{sorted(spans)}",
)
for tool in ("create_release", "drop_database"):
check(f"{prefix}{tool}" not in counts, f"no trace for {tool}: a refusal leaves none")
check(
counts.get(f"{prefix}scan_dependencies") == 3,
"scan_dependencies: three traces (one of them the timeout), none for the refused call",
)
traces = [t for t in mcp_traces(admin, prefix) if t.extra["name"] == f"{prefix}issue_write"]
detail = admin.observability.trace(traces[0].trace_id)
span = detail["spans"][0]
attrs = span["attributes"]
check(
span["span_type"] == "TOOL"
and attrs["caliber.mcp.transport"] == "stdio"
and attrs["caliber.mcp.server_id"] == sid
and "caliber.tool.input" in attrs
and "caliber.tool.output" in attrs,
"the trace is one TOOL span with the server, transport, input, output and latency",
)
failed_trace = [
t
for t in mcp_traces(admin, prefix)
if t.extra["name"] == f"{prefix}search_repositories"
]
check(
any(str(t.status).upper().endswith("ERROR") for t in failed_trace),
"a tool's own error is traced as ERROR",
)
summary["traces"] = counts
say("== 15. the gallery starter")
recipe = {item.id: item for item in admin.cookbooks.list()}["05"]
check(len(recipe.steps) == 11, "the gallery lists 11 steps for this lab")
installed = admin.cookbooks.install(
"05",
name=f"Cookbook 05 starter{suffix}",
acknowledge_prerequisites=bool(recipe.prerequisites),
)
manifest = installed["version"]["manifest"]
node_types = sorted(n["type"] for n in manifest["nodes"].values())
check(
node_types == ["agent", "note", "output", "start"] and not manifest["tools"],
"the starter is a generic single-agent draft with no tools: it does not use the "
"MCP server",
)
summary["starter_workflow_id"] = installed["workflow"]["workflow_id"]
return summary
def _invoke(row: dict[str, Any]) -> dict[str, Any]:
return {"tool_name": row["tool_name"], "arguments": row["arguments"]}
def cleanup(admin: CaliberClient, suffix: str) -> None:
wanted = {
f"repo-tracker{suffix}",
f"rogue-shell{suffix}",
f"rogue-python{suffix}",
f"loopback-http{suffix}",
}
workflows = {
f"mcp-file-issue{suffix}",
f"mcp-release{suffix}",
f"Cookbook 05 starter{suffix}",
}
for workflow in admin.workflows.list():
if workflow.name in workflows:
admin.workflows.delete(workflow.workflow_id)
say(f"deleted workflow {workflow.name}")
for project in admin.projects.list():
if project.name == f"mcp-ops{suffix}":
with admin.workspace_scope(project.project_id):
for server in admin.mcp_servers.list():
if server.name in wanted:
admin.mcp_servers.delete(server.server_id)
say(f"deleted MCP server {server.name}")
admin.projects.archive(project.project_id)
say(f"archived workspace {project.name}")
def main() -> None:
base_url = os.environ["CALIBER_BASE_URL"]
suffix = os.environ.get("LAB05_SUFFIX", "")
admin = CaliberClient(base_url, token=os.environ["CALIBER_TOKEN"], timeout=180)
if "--cleanup" in sys.argv:
cleanup(admin, suffix)
return
ensure_accounts(admin)
result = run(
admin,
operator=login_client(base_url, *OPERATOR),
approver=login_client(base_url, *APPROVER),
viewer=login_client(base_url, *VIEWER),
ledger=ledger_path(),
suffix=suffix,
)
say("== done")
print(json.dumps(result, indent=2, sort_keys=True))
if __name__ == "__main__":
main()sdk/caliber-sdk/examples/cookbooks/cookbook_05_governed_tool_connectivity.py — executed by the SDK example test suite.Cookbook 06 — Grounded Knowledge Assistant
Upload 11 policy documents to an object-store bucket, build knowledge base version 1 and check that the answer cites the chunk holding the clause, compare dense, hybrid and graph_hybrid retrieval over 41 answerable questions, calibrate Recall@k and nDCG@k against a pinned baseline, build a tuned version 2, test activation, rollback and failing builds, then install the answer workflow and route its low-confidence run to a review queue. It needs an admin token, the cookbooks flag, an S3-compatible object store and the local all-MiniLM-L6-v2 embedding model; retrieval and its metrics are real, while the answer text, model-judged metrics (Faithfulness, Answer-correctness) and prompt scoring (refused with 400) are simulated on the default stack. It uses client.raw once, for /readiness.
SDK surfaces: cookbooks, knowledge_bases, object_store, datasets, workflows, review_queues, prompts, judges, evaluations
- Read readiness, the object store status and the knowledge-base options (chunking strategies and embedding models), then upload the 11 documents to
policy-corpus/policies/. - Create the knowledge base and build version 1 through the queue and worker (11 sources, 27 chunks of 384-dimension vectors), and query it to check the answer cites the
data-retention-policy.mdchunk containing365 days. - Compare dense, hybrid and graph_hybrid hit rates at top 3, check what a 0.42 score gate refuses (every out-of-corpus question, not the two trap questions), then calibrate and pin the baseline run.
- Build the tuned version 2 (69 chunks), and verify activation, rollback, a build that skips an unreadable file (it completes with
failed_sources: 1), and a build with nothing readable (it fails and cannot be activated). - Install the answer workflow, run three questions through it, and enqueue only the low-confidence run in a review queue, where the reviewer's answer is written back to the trace.
- Store the answer prompt and the faithfulness judge, and check scoring the prompt is refused with 400 on the simulated model.
"""Cookbook 06 (Grounded Knowledge Assistant), run end to end against a real server.
The lab's whole API path, from the policy documents to a verified outcome:
upload the corpus -> build knowledge-base version 1 (queue + worker) -> read the chunks back
-> query with citations and check the cited chunk holds the clause -> compare dense, hybrid
and graph_hybrid over the 41 answerable questions -> check what a score gate can and cannot
refuse -> calibrate (Recall@k, nDCG@k) -> build the tuned version 2, pin a baseline -> activate
and roll back -> a build that skips an unreadable file, a build that fails outright -> install
the answer workflow, run it and route the low-confidence runs to a review queue -> store the
answer prompt and the faithfulness judge, and see the model-scored step refused on the
simulated stack.
It exits 0 only when every documented outcome is verified. The assets it reads are the lab's own
files under ``docs-site/cookbooks/06-knowledge-retrieval-policy-qa-lab/assets/``.
Run it from the repository root, against a server started with the Cookbooks flag and an
S3-compatible object store (``scripts/cookbook-env.sh up lab06 --flags cookbooks --s3``)::
source .tmp/cookbook-env/lab06/env.sh # CALIBER_BASE_URL, CALIBER_S3_ENDPOINT, ...
export CALIBER_TOKEN=calpat_... # Settings > API tokens, or POST /auth/tokens
PYTHONPATH=sdk/caliber-sdk caliber/.venv/bin/python \\
-m examples.cookbooks.cookbook_06_grounded_knowledge_assistant
``--cleanup SUFFIX`` removes what a run created (the suffix is in the first line it prints).
What is real and what is simulated on the default stack (``CALIBER_LLM_PROVIDER=fake``,
``CALIBER_EVAL_PROVIDER=fake``, ``CALIBER_ASSISTANT_ENGINE=fake``):
* Real: the object store (an S3 endpoint), the build worker, the chunking, the embeddings (the
``all-MiniLM-L6-v2`` model, run locally) and every retrieval ranking, so Recall@k, nDCG@k, the hit
rates and the score gate are arithmetic on real retrieval.
* Simulated: the answer text (an extractive "most relevant evidence" digest, not a generated
answer), the model-judged calibration metrics (Faithfulness and Answer-correctness come back
``null``) and scoring a prompt on the Evaluations page (refused with ``400``). A real provider
changes those three and nothing else; the script prints what it saw.
"""
from __future__ import annotations
import json
import os
import re
import secrets
import sys
import time
from collections.abc import Callable
from pathlib import Path
from typing import Any
from caliber_sdk import CaliberClient
from caliber_sdk.errors import CaliberAPIError
from examples.cookbooks._helpers import configuration_blockers, env_client, get_recipe
BUCKET = "policy-corpus"
PREFIX = "policies/"
UNREADABLE_KEY = "unreadable/scanned-handbook.pdf"
EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
#: The two chunkings the lab compares: the markdown strategy's own defaults, then smaller chunks.
BASELINE_CHUNKING = {"chunk_size": 1400, "chunk_overlap": 120}
TUNED_CHUNKING = {"chunk_size": 500, "chunk_overlap": 60}
TOP_K = 3
#: ``verification.yaml``: the hybrid mode must put the clause's chunk in the top 3 for this share.
HYBRID_HIT_AT_3_MIN = 0.95
#: The top-1 dense similarity below which a question is treated as not covered by the corpus.
#: Chosen between the weakest answerable question (0.444 / 0.498 on the two versions) and the
#: strongest question that really is outside the corpus (0.384 / 0.377).
SCORE_GATE = 0.42
#: Questions that are unanswerable but share their vocabulary with a policy that exists: a score
#: gate cannot refuse them (``verification.yaml`` records why, and what does).
TRAP_TAG = "trap"
CONFIDENCE_REVIEW_THRESHOLD = 0.65
def assets_dir() -> Path:
override = os.environ.get("COOKBOOK_06_ASSETS")
if override:
return Path(override)
repo_root = Path(__file__).resolve().parents[4]
return repo_root / "docs-site/cookbooks/06-knowledge-retrieval-policy-qa-lab/assets"
def load_jsonl(path: Path) -> list[dict[str, Any]]:
lines = path.read_text(encoding="utf-8").splitlines()
return [json.loads(line) for line in lines if line.strip()]
def load_corpus(assets: Path) -> dict[str, bytes]:
sources = assets / "dataset/sources"
return {
path.name: path.read_bytes()
for path in sorted(sources.glob("*.md"))
if path.name != "README.md"
}
def norm(text: str) -> str:
"""The comparison the dataset and the checks share: no stars, one space, lowercase."""
return re.sub(r"\s+", " ", text.replace("*", "")).strip().lower()
def split_frontmatter(text: str) -> tuple[dict[str, str], str]:
"""A prompt asset: ``key: value`` frontmatter, then the literal template."""
_, front, body = text.split("---\n", 2)
meta: dict[str, str] = {}
for line in front.splitlines():
key, _, value = line.partition(":")
if key.strip():
meta[key.strip()] = value.strip().strip('"')
return meta, body.strip()
class Report:
"""Collects ``ok`` lines the README quotes, and fails loudly on the first broken claim."""
def __init__(self) -> None:
self.checks: list[dict[str, Any]] = []
def check(self, label: str, ok: bool, detail: str = "") -> None:
self.checks.append({"label": label, "ok": bool(ok), "detail": detail})
print(
f"{'ok ' if ok else 'FAIL'} {label}" + (f" [{detail}]" if detail else ""), flush=True
)
if not ok:
raise AssertionError(f"{label}: {detail}")
def reason_of(exc: CaliberAPIError) -> str:
return exc.detail or str(exc)
def expect_status(label: str, status: int, call: Callable[[], Any]) -> str:
"""Run ``call`` and require it to fail with HTTP ``status``; return the server's reason."""
try:
call()
except CaliberAPIError as exc:
assert exc.status_code == status, f"{label}: expected {status}, got {exc.status_code}"
return f"{status} {reason_of(exc)}"
raise AssertionError(f"{label}: expected HTTP {status}, but the call succeeded")
def wait_for_build(
caliber: CaliberClient, version_id: str, *, timeout: float = 300.0, poll: float = 1.0
) -> dict[str, Any]:
"""Poll until the queued build has been claimed by the worker and has stopped."""
deadline = time.monotonic() + timeout
while True:
version: dict[str, Any] = caliber.knowledge_bases.version(version_id)
if version["status"] in ("completed", "failed"):
return version
if time.monotonic() > deadline:
raise TimeoutError(
f"version {version_id} is still {version['status']} after {timeout}s"
)
time.sleep(poll)
def ask(
caliber: CaliberClient,
version_id: str,
question: str,
*,
mode: str = "dense",
top_k: int = TOP_K,
retries: int = 0,
) -> dict[str, Any]:
hits: dict[str, Any] = {}
for attempt in range(retries + 1):
result = caliber.knowledge_bases.query(
version_ids=[version_id], question=question, top_k=top_k, retrieval_modes=[mode]
)
hits = result["versions"][0]
# On a real stack a provider hiccup (a 429, a timeout) does not fail the query: the answer
# silently becomes the extractive digest and ``answer_error`` says why. Retry those.
provider_failed = bool(hits.get("answer_error")) and bool(hits.get("retrieved_chunks"))
if not (retries and provider_failed) or attempt == retries:
break
time.sleep(5.0 * (attempt + 1))
return hits
def evidence_rank(retrieved: dict[str, Any], evidence: str) -> int | None:
"""1-based rank of the first retrieved chunk whose text holds the supporting clause."""
for rank, chunk in enumerate(retrieved["retrieved_chunks"], start=1):
if norm(evidence) in norm(chunk["content"]):
return rank
return None
def sweep(
caliber: CaliberClient,
version_id: str,
rows: list[dict[str, Any]],
mode: str,
*,
retries: int = 0,
keep: dict[str, dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""Where the supporting clause ranks, for every answerable question, in one retrieval mode.
``keep`` (optional) collects each question's full query result by id, so a caller that also
wants the answers (the real-provider tier) does not query twice.
"""
ranks: dict[str, int | None] = {}
for row in rows:
retrieved = ask(caliber, version_id, row["input"]["question"], mode=mode, retries=retries)
if keep is not None:
keep[row["id"]] = retrieved
ranks[row["id"]] = evidence_rank(retrieved, row["expected"]["evidence"])
total = len(ranks)
return {
"mode": mode,
"questions": total,
"hit_at_1": sum(1 for r in ranks.values() if r == 1),
"hit_at_3": sum(1 for r in ranks.values() if r is not None),
"misses": sorted(qid for qid, r in ranks.items() if r is None),
}
def calibrate(
caliber: CaliberClient, kb_id: str, version_id: str, dataset_id: str, mode: str, top_k: int
) -> dict[str, Any]:
run = caliber.knowledge_bases.calibrate(
kb_id, version_id=version_id, eval_dataset_id=dataset_id, retrieval_mode=mode, top_k=top_k
)
metrics = run["metrics"]
return {
"test_run_id": run["test_run_id"],
"mode": mode,
"top_k": top_k,
"recall_at_k": round(metrics["recall_at_k"], 4),
"ndcg_at_k": round(metrics["ndcg_at_k"], 4),
"faithfulness": metrics.get("faithfulness"),
"answer_correctness": metrics.get("answer_correctness"),
"passed": metrics.get("passed_count"),
"failed": metrics.get("failed_count"),
"question_count": metrics["question_count"],
}
# --------------------------------------------------------------------------- #
# The real-provider tier: what a model changes (README, "Run it with a real provider")
# --------------------------------------------------------------------------- #
#: Invariants for a model that can do the job; the README records the values one run produced.
ASSISTANT_CONTAINS_MIN = 0.50 # share of answerable questions whose answer holds the expected fact
DECISION_PARSE_MIN = 0.90 # share of kb-answer replies that are valid JSON with a decision
ANSWER_DECISION_MIN = 0.60 # share of answerable questions the model decides to `answer`
ABSTAIN_OUTSIDE_MIN = 0.60 # share of the 5 out-of-corpus questions the model abstains on
DECISIONS = ("answer", "abstain", "clarify")
def format_chunks(retrieved: dict[str, Any]) -> str:
"""The chunks as ``kb-answer`` expects ``{{ retrieved_chunks }}``: id, source, text."""
return "\n\n".join(
f"[{c['chunk_id']}] source_id={c['source_name']}\n{c['content']}"
for c in retrieved["retrieved_chunks"]
)
def parse_decision(prediction: Any) -> str | None:
"""The ``decision`` of a ``kb-answer`` reply, or None if it is not the JSON contract."""
text = str(prediction or "").strip()
text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text)
try:
decision = json.loads(text).get("decision")
except (ValueError, AttributeError):
return None
return decision if decision in DECISIONS else None
def _real_answers(
caliber: CaliberClient,
version_id: str,
qa_rows: list[dict[str, Any]],
hybrid_results: dict[str, dict[str, Any]],
retries: int,
check: Callable[..., Any],
) -> dict[str, Any]:
"""The assistant's own answers (hybrid, top 3) for all 48 questions, scored by rules only."""
for row in qa_rows:
if row["id"] not in hybrid_results: # the 41 answerable ones were answered by the sweep
hybrid_results[row["id"]] = ask(
caliber, version_id, row["input"]["question"], mode="hybrid", retries=retries
)
failed = [qid for qid, r in hybrid_results.items() if r["answer_error"] or not r["answer"]]
check(
"a model answered all 48 questions, with no provider error",
not failed and len(hybrid_results) == len(qa_rows),
f"{len(hybrid_results)} answers" if not failed else f"no answer for {failed}",
)
digest = [q for q, r in hybrid_results.items() if str(r["answer"]).startswith("Question:")]
check("none of them is the simulated extractive digest", not digest, f"digests: {digest}")
answerable = [r for r in qa_rows if r["expected"]["sources"] and r["expected"]["expected"]]
holds = {
r["id"]: norm(r["expected"]["expected"]) in norm(hybrid_results[r["id"]]["answer"])
for r in answerable
}
share = sum(holds.values()) / len(holds)
check(
f"answers state the expected fact (>= {ASSISTANT_CONTAINS_MIN:.0%} of answerable)",
share >= ASSISTANT_CONTAINS_MIN,
f"{sum(holds.values())}/{len(holds)} = {share:.0%}",
)
return {
"answered": len(hybrid_results),
"answerable_stating_the_expected_fact": f"{sum(holds.values())}/{len(holds)}",
"missing_the_fact": sorted(q for q, ok in holds.items() if not ok),
"sample": " ".join(str(hybrid_results["Q15"]["answer"]).split())[:240],
}
def _grounded_evaluation(
caliber: CaliberClient,
*,
suffix: str,
owner: str,
qa_rows: list[dict[str, Any]],
hybrid_results: dict[str, dict[str, Any]],
prompt_name: str,
judge_id: str,
check: Callable[..., Any],
) -> dict[str, Any]:
"""Score the ``kb-answer`` prompt on all 48 questions with the real CitationFaithfulness judge.
Evaluations has no retrieval step, so the test set carries what retrieval returned (the hybrid
top 3 for each question) in ``input.retrieved_chunks``, which the prompt's variable receives.
The prompt replies with a ``decision``; the table printed is that decision against the label.
"""
grounded = caliber.eval_datasets.create(
f"policy-qa-grounded-{suffix}",
owner=owner,
description="The 48 questions with the chunks retrieval returned for each (hybrid, top 3)",
)
for row in qa_rows:
caliber.eval_datasets.add_example(
grounded.dataset_id,
input={**row["input"], "retrieved_chunks": format_chunks(hybrid_results[row["id"]])},
expected=row["expected"],
tags=row["tags"],
)
judge_scorer = f"Judge.{judge_id}"
run = caliber.evaluations.create(
grounded.dataset_id,
predict_target="prompt",
subject_ref=f"{prompt_name}@1",
scorers=["contains_expected", "non_empty", judge_scorer],
label=f"kb-answer v1 {suffix}",
)
stored = caliber.evaluations.get(run.run_id)
rows = stored.results or []
check(
"the answer prompt was scored on all 48 questions, every row without an error",
stored.status == "completed"
and stored.n_examples == len(qa_rows)
and len(rows) == len(qa_rows)
and all(r["error"] is None for r in rows),
f"{run.run_id} {stored.status}"
+ (f": {stored.error_message}" if stored.error_message else ""),
)
by_question = {r["input"]["question"]: r for r in qa_rows}
table: dict[str, dict[str, int]] = {
label: {**{d: 0 for d in DECISIONS}, "unparsed": 0} for label in DECISIONS
}
judged: dict[str, list[float]] = {label: [] for label in DECISIONS}
trap_decisions: dict[str, str] = {}
for result in rows:
qa = by_question[result["input"]["question"]]
label = qa["expected"]["decision"]
decision = parse_decision(result["prediction"])
table[label][decision or "unparsed"] += 1
judged[label].append(float(result["scores"][judge_scorer]))
if TRAP_TAG in qa["tags"] and label == "abstain":
trap_decisions[qa["id"]] = decision or "unparsed"
print(
" expected \\ produced answer abstain clarify unparsed judge pass rate",
flush=True,
)
for label in DECISIONS:
counts = table[label]
mean = sum(judged[label]) / len(judged[label])
print(
f" {label:<18} {counts['answer']:>6} {counts['abstain']:>7} "
f"{counts['clarify']:>7} {counts['unparsed']:>8} {mean:.2f}",
flush=True,
)
unparsed = sum(c["unparsed"] for c in table.values())
check(
f"the replies follow the JSON contract (>= {DECISION_PARSE_MIN:.0%} carry a decision)",
1 - unparsed / len(rows) >= DECISION_PARSE_MIN,
f"{len(rows) - unparsed}/{len(rows)} parsed",
)
answer_share = table["answer"]["answer"] / sum(table["answer"].values())
check(
f"it decides to answer answerable questions (>= {ANSWER_DECISION_MIN:.0%})",
answer_share >= ANSWER_DECISION_MIN,
f"{table['answer']['answer']}/{sum(table['answer'].values())}",
)
outside = [r for r in qa_rows if not r["expected"]["sources"] and TRAP_TAG not in r["tags"]]
abstained = sum(
parse_decision(
next(x for x in rows if x["input"]["question"] == r["input"]["question"])["prediction"]
)
== "abstain"
for r in outside
)
check(
f"it abstains on questions the corpus does not cover (>= {ABSTAIN_OUTSIDE_MIN:.0%})",
abstained / len(outside) >= ABSTAIN_OUTSIDE_MIN,
f"{abstained}/{len(outside)}",
)
aggregate = stored.aggregate
return {
"run_id": run.run_id,
"decisions": table,
"trap_decisions": trap_decisions,
"aggregate": {k: round(v, 3) for k, v in aggregate.items()},
"judge_pass_rate_by_label": {k: round(sum(v) / len(v), 3) for k, v in judged.items()},
}
def bind_knowledge_node(
caliber: CaliberClient, version_id: str, kb_id: str
) -> tuple[Any, dict[str, Any]]:
"""Bind the installed template's knowledge node to the KB and gate confidence on the score.
The template ships a ``confidence`` node whose signals read the citations of the query result.
One more signal is added: the best chunk's similarity must reach :data:`SCORE_GATE`, the same
gate the script just checked against the question set.
"""
version = caliber.workflows.versions.get(version_id)
manifest = version.manifest
manifest["nodes"]["knowledge"].update(
knowledge_base_id=kb_id, version_ids=[], retrieval_modes=["dense"], top_k=TOP_K
)
manifest["nodes"]["confidence"]["config"] = {
"bias": 0.1,
"review_threshold": CONFIDENCE_REVIEW_THRESHOLD,
"signals": [
{
"name": "has-citations",
"path": "versions.0.citations.0",
"operator": "exists",
"value": True,
"weight": 0.15,
},
{
"name": "top-chunk-score",
"path": "versions.0.retrieved_chunks.0.score",
"operator": "greater_or_equal",
"value": SCORE_GATE,
"weight": 0.55,
},
],
}
manifest_hash = version.manifest_hash
if manifest_hash is None:
raise AssertionError("the workflow version reported no manifest_hash to edit against")
updated = caliber.workflows.versions.update(
version_id, manifest=manifest, manifest_hash=manifest_hash
)
return updated, manifest
def step_output(run: Any, node_id: str) -> dict[str, Any]:
summary = (run.extra or {}).get("summary") or {}
for step in summary.get("steps", []):
if step.get("node_id") == node_id:
return step.get("output_by_port") or {}
return {}
def run(caliber: CaliberClient, *, suffix: str | None = None, poll: float = 1.0) -> dict[str, Any]:
assets = assets_dir()
suffix = suffix or secrets.token_hex(3)
report = Report()
check = report.check
out: dict[str, Any] = {"suffix": suffix}
print(f"cookbook 06 run {suffix}", flush=True)
corpus = load_corpus(assets)
qa_rows = load_jsonl(assets / "dataset/qa-eval.jsonl")
calibration_rows = load_jsonl(assets / "dataset/calibration-questions.jsonl")
answerable = [r for r in qa_rows if r["expected"]["sources"]]
unanswerable = [r for r in qa_rows if not r["expected"]["sources"]]
check(
"the dataset is the one the README describes",
len(corpus) == 11
and len(qa_rows) == 48
and len(answerable) == 41
and len(unanswerable) == 7
and len(calibration_rows) == 41,
f"{len(corpus)} policy documents, {len(qa_rows)} questions "
f"({len(answerable)} answerable, {len(unanswerable)} not), "
f"{len(calibration_rows)} calibration pairs",
)
# every gold clause is a literal passage of its document, so the dataset cannot drift
docs = {name: norm(body.decode("utf-8")) for name, body in corpus.items()}
drifted = [
r["id"]
for r in answerable
if not any(norm(r["expected"]["evidence"]) in docs[s] for s in r["expected"]["sources"])
]
check(
"every supporting clause is a literal passage of its document",
not drifted,
f"drifted: {drifted}",
)
# ---- 0. what the server has ------------------------------------------------------------
recipe = get_recipe(caliber, "06")
readiness = caliber.raw.get("/readiness")
simulated = readiness.get("simulated") or []
out["simulated"] = simulated
#: A model behind the server: answers are generated, and calibration's Faithfulness and
#: Answer-correctness judges run. (The README's "Run it with a real provider".)
real = "llm" not in simulated and "eval" not in simulated
out["mode"] = "real provider" if real else "simulated"
retries = 3 if real else 0
status = caliber.object_store.status()
check(
"the object store is reachable",
bool(status.get("connected")),
f"{status.get('bucket_count')} buckets",
)
options = caliber.knowledge_bases.options()
model = next(m for m in options["embedding_models"] if m["id"] == EMBEDDING_MODEL)
check(
"the embedding model is available",
bool(model["available"]),
model.get("unavailable_reason") or EMBEDDING_MODEL,
)
out["unmet_checks"] = configuration_blockers(recipe)
# ---- 1. the corpus in the object store -------------------------------------------------
caliber.object_store.create_bucket(BUCKET)
for name, body in corpus.items():
caliber.object_store.upload(
BUCKET, filename=name, content=body, prefix=PREFIX, media_type="text/markdown"
)
caliber.object_store.upload(
BUCKET,
filename=Path(UNREADABLE_KEY).name,
content=(assets / "dataset/unreadable/scanned-handbook.pdf").read_bytes(),
prefix="unreadable/",
media_type="application/pdf",
)
listed = sorted(
o.key for o in caliber.object_store.objects(BUCKET, prefix=PREFIX, recursive=True)
)
check(
"the corpus is in the bucket",
listed == [PREFIX + name for name in sorted(corpus)],
f"{len(listed)} objects under {BUCKET}/{PREFIX}",
)
# ---- 2. version 1: queue + worker ------------------------------------------------------
kb_name = f"policy-qa-kb-{suffix}"
created = caliber.knowledge_bases.create(
kb_name,
description="Policy QA lab: 11 HR, IT, finance, billing and security policies",
source_bucket=BUCKET,
sources=[{"kind": "folder", "path": PREFIX}],
chunking_strategy="markdown",
chunking_config=BASELINE_CHUNKING,
embedding_model=EMBEDDING_MODEL,
)
kb_id = created.knowledge_base_id
v1_id = created.extra["version"]["knowledge_base_version_id"]
out.update(knowledge_base_id=kb_id, v1=v1_id)
check(
"the build was queued for the worker",
created.extra["version"]["status"] == "queued"
and created.extra["run"]["status"] == "queued",
f"{v1_id} {created.extra['run']['status']}",
)
v1 = wait_for_build(caliber, v1_id, poll=poll)
summary = v1["summary"]
check(
"version 1 completed",
v1["status"] == "completed",
f"{v1['status']} in {summary['duration_seconds']}s"
+ (f": {v1['error_summary']}" if v1.get("error_summary") else ""),
)
check(
"every document was read and chunked",
summary["processed_sources"] == 11 and summary["failed_sources"] == 0,
f"{summary['processed_sources']} sources, {summary['chunk_count']} chunks, "
f"{summary['total_chars']} chars",
)
check(
"the embeddings are the model's real 384-dimension vectors",
v1["embedding_dimension"] == 384 and v1["embedding_provider"] == "huggingface",
f"{v1['embedding_provider']} {v1['embedding_model']} dim {v1['embedding_dimension']}",
)
kb = caliber.knowledge_bases.get(kb_id)
check("the finished build is the active version", kb.active_version_id == v1_id, v1_id)
out["v1_summary"] = {k: summary[k] for k in ("processed_sources", "chunk_count", "total_chars")}
chunks = caliber.knowledge_bases.chunks(v1_id, limit=500)
by_source: dict[str, int] = {}
for chunk in chunks:
by_source[chunk["source_name"]] = by_source.get(chunk["source_name"], 0) + 1
check(
"chunks carry their source documents",
sorted(by_source) == sorted(corpus)
and all(c["source_key"].startswith(PREFIX) for c in chunks),
f"{len(chunks)} chunks over {len(by_source)} documents",
)
# ---- 3. query with citations -----------------------------------------------------------
probe = next(r for r in answerable if r["id"] == "Q15")
retrieved = ask(caliber, v1_id, probe["input"]["question"], mode="hybrid", retries=retries)
rank = evidence_rank(retrieved, probe["expected"]["evidence"])
holder = retrieved["retrieved_chunks"][rank - 1] if rank else {}
cited = {c["chunk_id"] for c in retrieved["citations"]}
check(
"the answer cites the chunk that holds the clause",
rank is not None
and holder["chunk_id"] in cited
and holder["source_name"] == "data-retention-policy.md",
f"{probe['input']['question']!r} -> [{rank}] {holder.get('source_name')} "
f"{holder.get('chunk_id')}",
)
check(
"the chunk states the retention period",
"365 days" in holder.get("content", ""),
"365 days",
)
if real:
answer = retrieved["answer"] or ""
check(
"a model wrote the answer from the retrieved chunks, with no provider error",
retrieved["answer_error"] is None
and not answer.startswith("Question:")
and "365" in answer,
" ".join(answer.split())[:110],
)
else:
check(
"the answer is the extractive digest, with a numbered label per citation",
retrieved["answer"].startswith("Question:")
and retrieved["citations"][0]["label"].startswith("[1] "),
retrieved["citations"][0]["label"],
)
# ---- 4. retrieval modes over the whole answerable set ----------------------------------
hybrid_results: dict[str, dict[str, Any]] = {}
sweeps = {
mode: sweep(
caliber,
v1_id,
answerable,
mode,
retries=retries,
keep=hybrid_results if mode == "hybrid" else None,
)
for mode in ("dense", "hybrid", "graph_hybrid")
}
out["sweeps"] = sweeps
for mode, row in sweeps.items():
print(
f" {mode:<13} hit@1 {row['hit_at_1']}/{row['questions']} "
f"hit@3 {row['hit_at_3']}/{row['questions']} missed {row['misses']}",
flush=True,
)
check(
"hybrid puts the clause's chunk in the top 3 for nearly every question",
sweeps["hybrid"]["hit_at_3"] / sweeps["hybrid"]["questions"] >= HYBRID_HIT_AT_3_MIN,
f"{sweeps['hybrid']['hit_at_3']}/{sweeps['hybrid']['questions']}",
)
check(
"hybrid ranks the clause first more often than dense",
sweeps["hybrid"]["hit_at_1"] > sweeps["dense"]["hit_at_1"],
f"hybrid {sweeps['hybrid']['hit_at_1']} vs dense {sweeps['dense']['hit_at_1']}",
)
# the two refund documents a conflict-aware answerer must see together
for qid in ("Q40", "Q41"):
row = next(r for r in qa_rows if r["id"] == qid)
found = {
c["source_name"]
for c in ask(caliber, v1_id, row["input"]["question"], mode="dense")["retrieved_chunks"]
}
check(
f"{qid}: both conflicting refund documents are retrieved together",
{"refund-policy.md", "refund-faq.md"} <= found,
", ".join(sorted(found)),
)
# ---- 5. what a score gate can refuse ---------------------------------------------------
gate: dict[str, list[float]] = {"answerable": [], "outside": [], "trap": []}
for row in qa_rows:
top = ask(caliber, v1_id, row["input"]["question"], mode="dense", top_k=1)[
"retrieved_chunks"
][0]["score"]
if row["expected"]["sources"]:
gate["answerable"].append(top)
elif TRAP_TAG in row["tags"]:
gate["trap"].append(top)
else:
gate["outside"].append(top)
out["gate"] = {k: [min(v), max(v)] for k, v in gate.items()}
check(
f"a top-1 similarity gate of {SCORE_GATE} refuses every question outside the corpus",
max(gate["outside"]) < SCORE_GATE <= min(gate["answerable"]),
f"outside <= {max(gate['outside']):.3f}, answerable >= {min(gate['answerable']):.3f}",
)
check(
"it cannot refuse the trap questions: their policy exists, only the clause is missing",
min(gate["trap"]) >= SCORE_GATE,
f"traps {min(gate['trap']):.3f}..{max(gate['trap']):.3f}",
)
# ---- 6. calibration: the test set, the baseline, and a tuned version 2 -----------------
owner = caliber.me.get().user_id
dataset = caliber.eval_datasets.create(
f"policy-qa-calibration-{suffix}",
owner=owner,
description="41 policy questions with their gold sources",
)
for row in calibration_rows:
caliber.eval_datasets.add_example(
dataset.dataset_id, input=row["input"], expected=row["expected"], tags=row["tags"]
)
out["eval_dataset_id"] = dataset.dataset_id
check(
"the calibration test set holds every question",
len(caliber.eval_datasets.examples(dataset.dataset_id)) == len(calibration_rows),
f"{len(calibration_rows)} examples",
)
baseline = calibrate(caliber, kb_id, v1_id, dataset.dataset_id, "dense", 1)
caliber.knowledge_bases.set_baseline(kb_id, test_run_id=baseline["test_run_id"])
check(
"the baseline run is pinned",
caliber.knowledge_bases.get(kb_id).extra.get("baseline_run_id") == baseline["test_run_id"],
f"{baseline['test_run_id']} recall@1 {baseline['recall_at_k']} "
f"nDCG@1 {baseline['ndcg_at_k']}",
)
tuned = caliber.knowledge_bases.create_version(
kb_id,
chunking_strategy="markdown",
chunking_config=TUNED_CHUNKING,
embedding_model=EMBEDDING_MODEL,
)
v2_id = tuned["version"]["knowledge_base_version_id"]
out["v2"] = v2_id
v2 = wait_for_build(caliber, v2_id, poll=poll)
check(
"version 2 (500-character chunks) completed with more, smaller chunks",
v2["status"] == "completed" and v2["summary"]["chunk_count"] > summary["chunk_count"],
f"{summary['chunk_count']} -> {v2['summary']['chunk_count']} chunks",
)
check(
"a finished build becomes the active version by itself",
caliber.knowledge_bases.get(kb_id).active_version_id == v2_id,
v2_id,
)
grid: list[dict[str, Any]] = []
# A calibration run answers every question and judges the answer twice (3 model calls per
# question), so on a real provider only version 1 is compared: dense against hybrid, at 1 and 3
# chunks. Version 2's retrieval numbers are the same arithmetic on either tier.
versions = (("v1", v1_id),) if real else (("v1", v1_id), ("v2", v2_id))
for label, version_id in versions:
for mode in ("dense", "hybrid"):
for k in (1, 3):
if (label, mode, k) == ("v1", "dense", 1):
row = dict(baseline)
else:
row = calibrate(caliber, kb_id, version_id, dataset.dataset_id, mode, k)
grid.append({"version": label, **row})
out["calibration"] = grid
print(" version mode k recall@k nDCG@k faithfulness correctness", flush=True)
for row in grid:
faith = "n/a" if row["faithfulness"] is None else f"{row['faithfulness']:.2f}"
correct = "n/a" if row["answer_correctness"] is None else f"{row['answer_correctness']:.2f}"
print(
f" {row['version']:<7} {row['mode']:<7} {row['top_k']} {row['recall_at_k']:<8} "
f"{row['ndcg_at_k']:<6} {faith:<12} {correct}",
flush=True,
)
check(
"every calibration run scored all 41 questions",
all(r["question_count"] == 41 for r in grid),
f"{len(grid)} runs",
)
top_of_k1 = [r for r in grid if r["top_k"] == 1]
best = max(top_of_k1, key=lambda r: (r["recall_at_k"], r["ndcg_at_k"]))
check(
"tuning raises Recall@1 above the baseline",
best["recall_at_k"] > baseline["recall_at_k"],
f"{baseline['recall_at_k']} -> {best['recall_at_k']} ({best['version']}, {best['mode']})",
)
check(
"with three chunks every configuration finds the right policy for nearly every question",
all(r["recall_at_k"] >= 0.95 for r in grid if r["top_k"] == 3),
"recall@3 " + ", ".join(str(r["recall_at_k"]) for r in grid if r["top_k"] == 3),
)
judged = [r for r in grid if r["faithfulness"] is not None]
check(
"the model-judged metrics are n/a on a simulated judge, and real numbers otherwise",
bool(judged) == ("eval" not in simulated),
"faithfulness n/a (simulated judge)"
if not judged
else f"faithfulness {judged[0]['faithfulness']}",
)
if real:
scored = [
r for r in grid if r["faithfulness"] is not None and r["answer_correctness"] is not None
]
check(
"every calibration run has a real Faithfulness and Answer-correctness score in 0..1",
len(scored) == len(grid)
and all(
0.0 <= r[m] <= 1.0 for r in scored for m in ("faithfulness", "answer_correctness")
),
", ".join(
f"{r['mode']}@{r['top_k']} {r['faithfulness']:.2f}/{r['answer_correctness']:.2f}"
for r in scored
),
)
out["answer_quality"] = {
f"{r['mode']}@{r['top_k']}": {
"faithfulness": round(r["faithfulness"], 3),
"answer_correctness": round(r["answer_correctness"], 3),
"passed": r["passed"],
"failed": r["failed"],
}
for r in scored
}
# ---- 7. activate, roll back ------------------------------------------------------------
caliber.knowledge_bases.activate_version(kb_id, v1_id)
check(
"activating version 1 makes it live",
caliber.knowledge_bases.get(kb_id).active_version_id == v1_id,
v1_id,
)
caliber.knowledge_bases.rollback(kb_id)
check(
"rollback restores the version that was live before",
caliber.knowledge_bases.get(kb_id).active_version_id == v2_id,
f"back to {v2_id}",
)
# ---- 8. builds that meet an unreadable file --------------------------------------------
partial = caliber.knowledge_bases.create_version(
kb_id,
sources=[{"kind": "folder", "path": PREFIX}, {"kind": "file", "path": UNREADABLE_KEY}],
chunking_strategy="markdown",
chunking_config=TUNED_CHUNKING,
embedding_model=EMBEDDING_MODEL,
)
v3_id = partial["version"]["knowledge_base_version_id"]
v3 = wait_for_build(caliber, v3_id, poll=poll)
sources = caliber.knowledge_bases.sources(v3_id)
failed = [s for s in sources if s["status"] == "failed"]
check(
"an unreadable file is recorded as a failed source, and the build still completes",
v3["status"] == "completed" and v3["summary"]["failed_sources"] == 1 and len(failed) == 1,
f"{failed[0]['object_name']}: {failed[0]['error_summary']}" if failed else "",
)
check(
"that incomplete version went live on its own: read failed_sources before trusting a build",
caliber.knowledge_bases.get(kb_id).active_version_id == v3_id,
f"active {v3_id}, processed {v3['summary']['processed_sources']}, "
f"failed {v3['summary']['failed_sources']}",
)
caliber.knowledge_bases.activate_version(kb_id, v2_id)
check(
"activating the good version undoes it",
caliber.knowledge_bases.get(kb_id).active_version_id == v2_id,
v2_id,
)
broken = caliber.knowledge_bases.create_version(
kb_id,
sources=[{"kind": "file", "path": UNREADABLE_KEY}],
chunking_strategy="markdown",
chunking_config=TUNED_CHUNKING,
embedding_model=EMBEDDING_MODEL,
)
v4_id = broken["version"]["knowledge_base_version_id"]
v4 = wait_for_build(caliber, v4_id, poll=poll)
check(
"a build with nothing readable fails with the reason",
v4["status"] == "failed" and "did not produce any chunks" in (v4["error_summary"] or ""),
v4["error_summary"] or "",
)
check(
"a failed build leaves the live version alone",
caliber.knowledge_bases.get(kb_id).active_version_id == v2_id,
f"still {v2_id}",
)
not_ready = ask(caliber, v4_id, "How long are audit logs retained?")
check(
"querying a version that is not ready returns no chunks and says why",
not not_ready["retrieved_chunks"]
and not_ready["answer_error"] == "Version is not ready for retrieval.",
not_ready["answer_error"],
)
out["activate_failed"] = expect_status(
"activating a failed version",
409,
lambda: caliber.knowledge_bases.activate_version(kb_id, v4_id),
)
check(
"a failed version cannot be activated",
out["activate_failed"].startswith("409 "),
out["activate_failed"],
)
# a completed version that is not active is still queryable: "active" decides what consumers use
other = ask(caliber, v1_id, "How long are audit logs retained?")
check(
"a completed version that is not active can still be queried by id",
bool(other["retrieved_chunks"]) and other["answer_error"] is None,
f"{v1_id} is not active, {len(other['retrieved_chunks'])} chunks",
)
# ---- 9. the answer workflow ------------------------------------------------------------
installed = caliber.cookbooks.install(
"06",
name=f"cookbook-06-kb-assistant-{suffix}",
acknowledge_prerequisites=bool(recipe.prerequisites),
)
workflow_id = installed["workflow"]["workflow_id"]
draft_id = installed["version"]["version_id"]
out.update(workflow_id=workflow_id, workflow_version_id=draft_id)
check(
"the recipe installs as a paused workflow with a draft version",
installed["workflow"]["status"] == "paused" and installed["version"]["status"] == "draft",
f"{workflow_id} {draft_id}",
)
bind_knowledge_node(caliber, draft_id, kb_id)
check(
"the bound draft validates",
caliber.workflows.versions.validate(draft_id)["valid"] is True,
draft_id,
)
paused = expect_status(
"running a paused workflow",
409,
lambda: caliber.workflows.versions.run(draft_id, input="How long are audit logs retained?"),
)
check("a paused workflow refuses to run", paused.startswith("409 "), paused)
caliber.workflows.update(workflow_id, status="active")
def run_workflow(question: str) -> dict[str, Any]:
started = caliber.workflows.versions.run(draft_id, input=question)
finished = caliber.workflows.runs.wait(started["workflow_run_id"], timeout=180)
result = step_output(finished, "knowledge").get("result") or {}
verdict = (step_output(finished, "confidence").get("result")) or {}
version = (result.get("versions") or [{}])[0]
return {
"run_id": finished.workflow_run_id,
"trace_id": finished.trace_id,
"status": finished.status,
"resolved_version_ids": result.get("resolved_version_ids"),
"top_source": (version.get("retrieved_chunks") or [{}])[0].get("source_name"),
"top_score": (version.get("retrieved_chunks") or [{}])[0].get("score"),
"confidence": verdict.get("confidence"),
"needs_review": verdict.get("needs_review"),
"matched_signals": verdict.get("matched_signals"),
}
runs = {
"answerable": run_workflow("How long are security audit logs retained?"),
"outside_the_corpus": run_workflow("What is the dress code for client meetings?"),
"trap": run_workflow(
"What is the first-response time for an Enterprise customer's P1 case?"
),
}
out["workflow_runs"] = runs
for name, item in runs.items():
print(
f" {name:<19} {item['status']} top {item['top_source']} {item['top_score']} "
f"confidence {item['confidence']} needs_review {item['needs_review']}",
flush=True,
)
check(
"all three runs completed through the real knowledge_query node",
all(i["status"] == "completed" and i["top_source"] for i in runs.values()),
", ".join(i["run_id"] for i in runs.values()),
)
check(
"the workflow resolved the knowledge base's active version",
runs["answerable"]["resolved_version_ids"] == [v2_id],
f"resolved {runs['answerable']['resolved_version_ids']}",
)
check(
"a covered question is confident and a question outside the corpus is sent to review",
runs["answerable"]["needs_review"] is False
and runs["answerable"]["top_source"] == "data-retention-policy.md"
and runs["outside_the_corpus"]["needs_review"] is True,
f"{runs['answerable']['confidence']} vs {runs['outside_the_corpus']['confidence']}",
)
check(
"the trap question passes the gate: only a model can tell the clause is missing",
runs["trap"]["needs_review"] is False,
f"confidence {runs['trap']['confidence']} from {runs['trap']['top_source']}",
)
caliber.knowledge_bases.activate_version(kb_id, v1_id)
rerun = run_workflow("How long are security audit logs retained?")
caliber.knowledge_bases.rollback(kb_id)
check(
"activating another version changes what the workflow uses; rollback changes it back",
rerun["resolved_version_ids"] == [v1_id]
and caliber.knowledge_bases.get(kb_id).active_version_id == v2_id,
f"{v2_id} -> {rerun['resolved_version_ids'][0]} -> {v2_id}",
)
# ---- 10. route the low-confidence run to a review queue --------------------------------
queue = caliber.review_queues.create(
f"policy-qa-review-{suffix}",
description="Runs the confidence gate sent to a person",
questions=[
{
"key": "decision_justified",
"title": "Is abstaining or clarifying justified by the retrieved evidence?",
"type": "pass_fail",
"required": True,
},
{
"key": "right_source_cited",
"title": "Did the answer cite the right policy?",
"type": "pass_fail",
"required": False,
},
],
)
flagged = [i for i in runs.values() if i["needs_review"]]
items = caliber.review_queues.enqueue(
queue.queue_id, trace_ids=[i["trace_id"] for i in flagged]
)
out["review_queue_id"] = queue.queue_id
check(
"only the low-confidence run was enqueued, as a trace-linked item",
len(items) == 1
and items[0]["trace_id"] == runs["outside_the_corpus"]["trace_id"]
and items[0]["status"] == "pending",
f"{queue.queue_id} {items[0]['item_id']}",
)
done = caliber.review_queues.submit(
queue.queue_id, items[0]["item_id"], decision_justified=True
)
check(
"the reviewer's answer is saved and written back to the trace as an assessment",
done["status"] == "completed"
and done["answers"] == {"decision_justified": True}
and bool(done["assessment_ids"]),
f"assessment {done['assessment_ids'][0]}",
)
# ---- 11. the answer prompt and the faithfulness judge ----------------------------------
meta, template = split_frontmatter(
(assets / "prompts/kb-answer.md").read_text(encoding="utf-8")
)
prompt_name = f"kb-answer-{suffix}"
caliber.prompts.create(prompt_name, template, commit_message=meta["commit_message"])
stored = caliber.prompts.versions(prompt_name)
check(
"the answer prompt is stored with its three variables",
all(
f"{{{{ {var} }}}}" in template
for var in ("question", "policy_domain", "retrieved_chunks")
),
f"{prompt_name}, {len(stored) if isinstance(stored, list) else 'versioned'}",
)
judge_file = json.loads(
(assets / "judges/citation-faithfulness.judge.json").read_text(encoding="utf-8")
)
judge = caliber.judges.create(
f"CitationFaithfulness-{suffix}",
instructions=judge_file["instructions"],
feedback_value_type=judge_file["feedback_value_type"],
)
out["judge_id"] = judge.judge_id
check("the faithfulness judge is registered", bool(judge.judge_id), judge.judge_id)
qa_set = caliber.eval_datasets.create(
f"policy-qa-eval-{suffix}",
owner=owner,
description="48 policy questions: answer, clarify, abstain",
)
for row in qa_rows:
caliber.eval_datasets.add_example(
qa_set.dataset_id, input=row["input"], expected=row["expected"], tags=row["tags"]
)
out["qa_dataset_id"] = qa_set.dataset_id
if "llm" in simulated:
refused = expect_status(
"scoring a prompt on a simulated model",
400,
lambda: caliber.evaluations.create(
qa_set.dataset_id,
predict_target="prompt",
subject_ref=f"{prompt_name}@1",
scorers=["contains_expected"],
label="kb-answer v1",
),
)
out["evaluation"] = f"refused: {refused}"
check(
"scoring the answer prompt is refused on the simulated model",
"real LLM provider" in refused,
refused,
)
else:
out["real_answers"] = _real_answers(caliber, v1_id, qa_rows, hybrid_results, retries, check)
out["evaluation"] = _grounded_evaluation(
caliber,
suffix=suffix,
owner=owner,
qa_rows=qa_rows,
hybrid_results=hybrid_results,
prompt_name=prompt_name,
judge_id=judge.judge_id,
check=check,
)
out["recipe_unmet_checks"] = configuration_blockers(recipe)
out["verified"] = all(c["ok"] for c in report.checks)
out["checks"] = len(report.checks)
return out
def cleanup(caliber: CaliberClient, suffix: str) -> None:
"""Remove what a run with ``suffix`` created. Idempotent; the bucket is left in place."""
removed = []
for kb in caliber.knowledge_bases.list():
if kb.name == f"policy-qa-kb-{suffix}":
caliber.knowledge_bases.delete(kb.knowledge_base_id)
removed.append(f"knowledge base {kb.name}")
for workflow in caliber.workflows.list():
if workflow.name == f"cookbook-06-kb-assistant-{suffix}":
caliber.workflows.update(workflow.workflow_id, status="archived")
removed.append(f"workflow {workflow.name} (archived)")
for prompt in caliber.prompts.list():
if prompt.prompt_name == f"kb-answer-{suffix}":
caliber.prompts.delete(prompt.prompt_name)
removed.append(f"prompt {prompt.prompt_name}")
for judge in caliber.judges.list():
if judge.name == f"CitationFaithfulness-{suffix}":
caliber.judges.update(judge.judge_id, status="archived")
removed.append(f"judge {judge.name} (archived)")
for queue in caliber.review_queues.list():
if queue.name == f"policy-qa-review-{suffix}":
caliber.review_queues.update(queue.queue_id, status="archived")
removed.append(f"review queue {queue.name} (archived)")
for name in (
f"policy-qa-calibration-{suffix}",
f"policy-qa-eval-{suffix}",
f"policy-qa-grounded-{suffix}",
):
for dataset in caliber.eval_datasets.list():
if dataset.name == name:
caliber.eval_datasets.update(dataset.dataset_id, status="archived")
removed.append(f"test set {name} (archived)")
print("removed: " + ("; ".join(removed) if removed else "nothing"))
def main() -> None:
# Calibration and Evaluations are single requests that make a model call per question.
with env_client(timeout=3600.0) as caliber:
if "--cleanup" in sys.argv:
cleanup(caliber, sys.argv[sys.argv.index("--cleanup") + 1])
return
report = run(caliber)
print(json.dumps(report, indent=2, sort_keys=True, default=str))
if __name__ == "__main__":
main()sdk/caliber-sdk/examples/cookbooks/cookbook_06_grounded_knowledge_assistant.py — executed by the SDK example test suite.Cookbook 07 — Support Triage Copilot
Create a project with two reviewers, install the model-free Cookbooks starter and prove the approval rules on it, import the lab's support-triage workflow, promote it to a staging alias, and run all 44 tickets of ticket-cases.jsonl through the run queue, asserting decision, severity, SLA, approval flag, flags and node path (44/44) and that exactly the 15 approval-required tickets pause at the gate. It then answers the gate (one approved, one rejected, the rest cancelled), ships a deliberately bad version that the dataset catches, rolls back, and reads the run audit trail. It needs an admin-scoped SDK token, a server started with CALIBER_FEATURE_COOKBOOKS=true, CALIBER_OPERATOR_USERS=admin,lena,sam, CALIBER_APPROVER_USERS=admin,lena and a staging approval policy, and no model: the classifier is deterministic rules in one Python Code node and the draft_reply agent runs on the simulated provider. The script creates the lena and sam accounts, signs them in with plain httpx calls to /auth/login, and does not use client.raw.
SDK surfaces: cookbooks, projects, auth, workflows, datasets, audit
- Create a project, add
lena(approver) andsam(operator withoutcaliber.approver) as reviewers, and check their scopes. - Install the starter recipe (it arrives paused), activate and publish it, and prove the approval rules: the person who started the run cannot approve it (403), an operator without the scope cannot (403), a second person with the scope approves and the run completes, and a rejection ends it
failedwithapproval_rejected. - Import the triage workflow, validate it, confirm Preview refuses its
python_codenode, publish it, and promote thestagingalias (approved by the second person when the server asks). - Load the 44 tickets as a test set, read them back, run every ticket through the queue against the alias, and check each run's decision, severity, SLA, approval flag, flags and path; answer the gate on live runs (approve one and release the action, reject one and release nothing, cancel the rest).
- Publish a version with a bad rule, move the alias onto it, watch the dataset catch the regression (3 of 11 bug tickets wrong), then roll back and see the same tickets pass again.
- Read the audit log to find who enqueued, approved and resumed the approved run;
--cleanuparchives what earlier runs created.
"""Cookbook 07: a support triage workflow, run through the queue with human approval, for real.
This is the executable form of ``docs-site/cookbooks/07-support-triage-resolution-loop/README.md``.
It drives a real CALIBER server and exits 0 only when every documented outcome was verified:
1. install the Cookbooks starter (``07``): a model-free skeleton that always pauses for approval,
and prove the approval rules on it: the person who started the run cannot approve it (403), an
approver with no ``caliber.approver`` scope cannot (403), a second person with the scope can,
and a rejection ends the run without releasing the action;
2. import the lab's triage workflow (``assets/workflows/support-triage.workflow.json``), validate
it, and confirm Preview refuses it (a ``python_code`` node cannot be isolated in Preview);
3. publish it and move the ``staging`` alias onto it (when the server requires approval for
``staging`` the promotion waits, and the script approves it as the second person);
4. import ``assets/dataset/ticket-cases.jsonl`` (44 tickets) as a test set, read it back, and run
every ticket through the queue against the alias; check decision, severity, SLA, approval flag
and flags against the expected values, and the path each run took through the graph;
5. answer the approval gate on live runs: approve one, reject one (nothing is released) and
cancel the rest;
6. publish a deliberately bad version, move the alias onto it, and watch the same dataset catch the
regression; then roll the alias back and see the dataset pass again;
7. read the run-level audit trail for the approved run.
Two modes, detected from ``GET /readiness`` (``simulated`` empty means a real provider):
* Simulated stack (the default): the agent node answers with canned text, and the script asserts
routing and approvals only.
* Real provider (``scripts/cookbook-env.sh up NAME --flags cookbooks --real-llm``): the same checks
hold (the router, gate and rules are deterministic), the reply agent writes real text, and
Evaluations is shown refusing the deterministic workflow row by row (Preview cannot run Python
code). ``--model-variant`` also imports the optional model-based variant
(``support-triage-model.workflow.json``): an agent classifies, a deterministic guard decides,
and it is evaluated (a deterministic scorer and a model-graded judge), run through the queue
and calibrated. How often the model agrees with the rules is reported, never asserted exactly;
what is asserted is that no escalation the model proposes is released without a person.
Environment (see the lab README): ``CALIBER_BASE_URL`` (the server root, for example
``http://127.0.0.1:5001``, without the API path) and ``CALIBER_TOKEN`` (an ADMIN personal access
token). The script creates two more accounts (``lena``, an approver, and ``sam``, an operator
without the approver scope), which the server must know: start it with
``CALIBER_OPERATOR_USERS`` and ``CALIBER_APPROVER_USERS`` as the README shows. Optional:
``COOKBOOK_07_ASSETS`` (another assets directory), ``COOKBOOK_07_PASSWORD`` (the password).
PYTHONPATH=sdk/caliber-sdk caliber/.venv/bin/python \
-m examples.cookbooks.cookbook_07_support_triage_copilot
... --cleanup # archive what earlier runs created
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import time
from collections import Counter
from collections.abc import Callable
from pathlib import Path
from typing import Any
import httpx
from caliber_sdk import CaliberClient, wait_for
from caliber_sdk.errors import CaliberAPIError, CaliberPermissionError
from caliber_sdk.transport import API_PREFIX
from examples.cookbooks._helpers import PAUSED_OR_TERMINAL_RUN_STATES, env_client
NAME_PREFIX = "cookbook-07-"
APPROVER_USER = "lena"
MEMBER_USER = "sam"
DEFAULT_PASSWORD = "cookbook07-lab-passphrase"
#: Steps that decide what a ticket is; the rest of the graph only acts on the decision.
CLASSIFY_NODE = "classify"
#: The node each decision must end at when no approval is needed.
TERMINAL_NODE = {
"reply": "draft_reply",
"clarify": "clarify_question",
"escalate_support": "support_note",
}
APPROVAL_NODE = "review"
RELEASED_NODE = "action_request"
#: The optional model-based variant (real provider only) and its judge.
VARIANT_FILE = "workflows/support-triage-model.workflow.json"
JUDGE_FILE = "judges/support-triage-routing-and-reply.judge.json"
VARIANT_GATE_DATASET_REF = "ticket-eval"
#: Twelve tickets, three per decision, scored by Evaluations and replayed through the variant. They
#: include the hard negative (TK07), a prompt injection (TK16), PII, a duplicate and a cosmetic
#: bug, where a model is most likely to disagree with the rules.
EVAL_TICKETS = (
"TK01",
"TK07",
"TK26",
"TK10",
"TK16",
"TK44",
"TK18",
"TK20",
"TK40",
"TK29",
"TK33",
"TK37",
)
#: Node ids that release an action after an approval, in the variant.
VARIANT_RELEASE_NODES = ("release_bug", "release_support")
#: The regression the dataset must catch: a "tidy-up" that stops flagging production impact.
BAD_RULE = ("urgent_markers = has([", "urgent_markers = False and has([")
#: Seconds a single request may take. A real provider answers a gate replay or an evaluation inside
#: one request, which takes minutes (the SDK default is 30 s).
REQUEST_TIMEOUT = 900.0
Report = Callable[[str], None]
class LabVerificationError(AssertionError):
"""At least one documented outcome of the lab did not hold."""
class SetupError(RuntimeError):
"""The deployment is not set up the way the lab needs (a fix, not a defect)."""
# ---------------------------------------------------------------------------
# The asset files
# ---------------------------------------------------------------------------
def default_assets_dir() -> Path:
override = os.environ.get("COOKBOOK_07_ASSETS")
if override:
return Path(override)
return (
Path(__file__).resolve().parents[4]
/ "docs-site/cookbooks/07-support-triage-resolution-loop/assets"
)
def load_cases(path: Path) -> list[dict[str, Any]]:
rows = [
json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()
]
for row in rows:
if not {"id", "input", "expected"} <= set(row):
raise LabVerificationError(f"{path.name}: row {row.get('id')} lacks id/input/expected")
return rows
def load_json(path: Path) -> dict[str, Any]:
return dict(json.loads(path.read_text(encoding="utf-8")))
def load_manifest(assets: Path) -> dict[str, Any]:
manifest: dict[str, Any] = json.loads(
(assets / "workflows/support-triage.workflow.json").read_text(encoding="utf-8")
)
shipped = (assets / "workflows/classify-ticket.py").read_text(encoding="utf-8")
if manifest["nodes"][CLASSIFY_NODE]["code"] != shipped:
raise LabVerificationError(
"the classify node in support-triage.workflow.json no longer matches "
"workflows/classify-ticket.py; rebuild the manifest from the file"
)
return manifest
# ---------------------------------------------------------------------------
# Reading runs
# ---------------------------------------------------------------------------
def summary_of(run: Any) -> dict[str, Any]:
return dict((run.extra or {}).get("summary") or {})
def node_path(run: Any) -> list[str]:
return list(summary_of(run).get("node_path") or [])
def triage_of(run: Any) -> dict[str, Any] | None:
"""The record the ``classify`` node produced, read from the run's own step trace."""
for step in summary_of(run).get("steps") or []:
if step.get("node_id") == CLASSIFY_NODE:
# A Python Code node's ``result`` port holds everything the code returned; the triage
# record is its own ``result`` key.
returned = (step.get("output_by_port") or {}).get("result")
if isinstance(returned, dict) and isinstance(returned.get("result"), dict):
return dict(returned["result"])
return None
return None
def run_output(run: Any) -> str:
"""The final text of a settled run (the server keeps it on the run summary)."""
return str(summary_of(run).get("output") or "")
def problems_for(case: dict[str, Any], run: Any) -> list[str]:
"""What differs between what the dataset expects and what the run did."""
expected = case["expected"]
triage = triage_of(run)
if triage is None:
return [f"no classify step (status {run.status}, error {run.error})"]
found: list[str] = []
for key in ("decision", "severity", "sla_minutes", "requires_approval", "flags"):
if triage.get(key) != expected[key]:
found.append(f"{key}: expected {expected[key]!r}, got {triage.get(key)!r}")
path = node_path(run)
if expected["requires_approval"]:
if run.status != "waiting_approval" or not path or path[-1] != APPROVAL_NODE:
found.append(f"expected a pause at {APPROVAL_NODE!r}, got {run.status} via {path}")
else:
terminal = TERMINAL_NODE[expected["decision"]]
if run.status != "completed" or terminal not in path or APPROVAL_NODE in path:
found.append(f"expected completion via {terminal!r}, got {run.status} via {path}")
return found
def wait_settled(caliber: CaliberClient, run_id: str, *, timeout: float = 240.0) -> Any:
return wait_for(
lambda: caliber.workflows.runs.get(run_id),
is_done=lambda item: item.status in PAUSED_OR_TERMINAL_RUN_STATES,
interval=0.5,
max_interval=2.0,
timeout=timeout,
)
#: A run that ends ``failed`` with one of these is the provider's (a dropped connection, a rate
#: limit), not the workflow's: it is resubmitted, a bounded number of times.
TRANSIENT_RUN_ERRORS = (
"connection error",
"429",
"rate limit",
"timed out",
"timeout",
"overloaded",
"temporarily",
)
RUN_RETRIES = 2
def failure_of(run: Any) -> str:
return str((run.extra or {}).get("error_summary") or run.error or "")
def resubmit_transient(
caliber: CaliberClient,
runs: dict[str, Any],
inputs: dict[str, str],
*,
workflow_id: str,
alias: str,
key: str,
retried: list[str] | None = None,
) -> dict[str, Any]:
"""Resubmit the runs that failed for a transient provider reason, up to ``RUN_RETRIES`` times.
Only a failure whose own error says the connection dropped or the provider pushed back is
retried; a run that failed for any other reason keeps failing, so a real defect still shows.
``inputs`` maps each case id to the run input text.
"""
for attempt in range(1, RUN_RETRIES + 1):
transient = [
case_id
for case_id, run in runs.items()
if run.status == "failed"
and any(marker in failure_of(run).lower() for marker in TRANSIENT_RUN_ERRORS)
]
if not transient:
break
queued = {
case_id: caliber.workflows.runs.submit(
workflow_id=workflow_id,
alias=alias,
input=inputs[case_id],
idempotency_key=f"{key}-retry{attempt}-{case_id}",
)
for case_id in transient
}
for case_id, run in queued.items():
runs[case_id] = wait_settled(caliber, run.workflow_run_id)
if retried is not None:
retried.extend(transient)
return runs
def submit_cases(
caliber: CaliberClient,
cases: list[dict[str, Any]],
*,
workflow_id: str,
alias: str,
key: str,
retried: list[str] | None = None,
) -> dict[str, Any]:
"""Queue every case against the alias (asynchronously), then wait for all of them."""
inputs = {case["id"]: json.dumps(case["input"]) for case in cases}
queued = {
case["id"]: caliber.workflows.runs.submit(
workflow_id=workflow_id,
alias=alias,
input=inputs[case["id"]],
idempotency_key=f"{key}-{case['id']}",
)
for case in cases
}
runs = {case_id: wait_settled(caliber, run.workflow_run_id) for case_id, run in queued.items()}
return resubmit_transient(
caliber, runs, inputs, workflow_id=workflow_id, alias=alias, key=key, retried=retried
)
def grade(cases: list[dict[str, Any]], runs: dict[str, Any]) -> dict[str, list[str]]:
return {case["id"]: found for case in cases if (found := problems_for(case, runs[case["id"]]))}
def is_real_stack(caliber: CaliberClient) -> bool:
"""True when the server runs real providers (``/readiness`` lists nothing as simulated)."""
return not (caliber.readiness() or {}).get("simulated")
def refused(call: Callable[[], Any]) -> CaliberAPIError | None:
"""The API error a call raises, or ``None`` when it succeeded."""
try:
call()
except CaliberAPIError as exc:
return exc
return None
# ---------------------------------------------------------------------------
# Accounts
# ---------------------------------------------------------------------------
def sign_in(base_url: str, user_id: str, password: str) -> str:
"""``POST /auth/login``; the session token doubles as a bearer token for scripts."""
url = f"{base_url.rstrip('/')}{API_PREFIX}/auth/login"
csrf = httpx.get(f"{base_url.rstrip('/')}{API_PREFIX}/csrf", timeout=30)
headers: dict[str, str] = {}
if csrf.status_code == 200:
body = csrf.json().get("data") or {}
if body.get("enabled") and body.get("token"):
headers["X-CALIBER-CSRF"] = str(body["token"])
response = httpx.post(
url, json={"user_id": user_id, "password": password}, headers=headers, timeout=30
)
if response.status_code != 200:
raise SetupError(
f"could not sign in as {user_id!r}: {response.status_code} {response.text[:200]}. "
"An account left by an earlier run may have another password: reset it under "
"Administration, or set COOKBOOK_07_PASSWORD"
)
return str(response.cookies["caliber_session"])
def ensure_accounts(caliber: CaliberClient, password: str) -> None:
existing = {account.user_id: account for account in caliber.auth.accounts.list()}
for user in (APPROVER_USER, MEMBER_USER):
if user not in existing:
caliber.auth.accounts.create(user, password)
elif getattr(existing[user], "disabled", False):
caliber.auth.accounts.update(user, disabled=False)
# ---------------------------------------------------------------------------
# The lab
# ---------------------------------------------------------------------------
def run(
caliber: CaliberClient,
*,
project_client: Callable[[str, str], CaliberClient],
suffix: str | None = None,
assets: Path | None = None,
report: Report = print,
sleep: Callable[[float], None] = time.sleep,
model_variant: bool = False,
) -> dict[str, Any]:
"""Run the whole lab. ``project_client(user_id, project_id)`` returns that person's client,
bound to the project; ``caliber`` is the admin client (it creates the project).
``model_variant`` adds the optional model-based variant at the end (real provider only)."""
assets = assets or default_assets_dir()
suffix = suffix or time.strftime("%Y%m%d-%H%M%S")
cases = load_cases(assets / "dataset/ticket-cases.jsonl")
manifest = load_manifest(assets)
failures: list[str] = []
retried: list[str] = []
result: dict[str, Any] = {"suffix": suffix}
def check(label: str, ok: bool, detail: Any = "") -> None:
report(f"{'ok ' if ok else 'FAIL'} {label}" + (f" [{detail}]" if detail != "" else ""))
if not ok:
failures.append(label)
me = caliber.me.get()
if not me.is_admin:
raise SetupError("CALIBER_TOKEN must be an admin personal access token")
if "07" not in {recipe.id for recipe in caliber.cookbooks.list()}:
raise SetupError("Cookbooks are off: start the server with CALIBER_FEATURE_COOKBOOKS=true")
real = is_real_stack(caliber)
result["mode"] = "real" if real else "simulated"
if model_variant and not real:
raise SetupError("--model-variant needs a real provider (start with --real-llm)")
# -- 0. The project and the three people ------------------------------------------------
project = caliber.projects.create(
f"{NAME_PREFIX}support-ops-{suffix}", description="Cookbook 07 support triage"
)
for user in (APPROVER_USER, MEMBER_USER):
caliber.projects.add_member(project.project_id, user, role="reviewer")
admin = project_client(me.user_id, project.project_id)
approver = project_client(APPROVER_USER, project.project_id)
member = project_client(MEMBER_USER, project.project_id)
scopes = {
user: set(client.me.get().scopes) for user, client in (("lena", approver), ("sam", member))
}
if "caliber.approver" not in scopes["lena"] or "caliber.approver" in scopes["sam"]:
raise SetupError(
"start CALIBER with CALIBER_OPERATOR_USERS=admin,lena,sam and "
"CALIBER_APPROVER_USERS=admin,lena (lena approves, sam must not)"
)
check("lena holds caliber.approver; sam does not", True, f"project {project.project_id}")
result["project_id"] = project.project_id
# -- 1. The starter: the approval rules -------------------------------------------------
installed = admin.cookbooks.install(
"07", name=f"{NAME_PREFIX}starter-{suffix}", acknowledge_prerequisites=True
)
starter_workflow = installed["workflow"]["workflow_id"]
check(
"the installed starter arrives paused (activation needs review)",
installed["workflow"]["status"] == "paused" and installed["activation_requires_review"],
)
admin.workflows.update(starter_workflow, status="active")
starter = admin.workflows.versions.publish(installed["version"]["version_id"])
def starter_run(label: str) -> Any:
queued = admin.workflows.runs.submit(
workflow_version_id=starter.version_id,
input="How do I enable SSO for my workspace?",
idempotency_key=f"{suffix}-starter-{label}",
)
return wait_settled(admin, queued.workflow_run_id)
paused = starter_run("approve")
check(
"the starter pauses at its approval node",
paused.status == "waiting_approval" and node_path(paused)[-1] == APPROVAL_NODE,
paused.workflow_run_id,
)
own = refused(lambda: admin.workflows.runs.approve(paused.workflow_run_id, reason="self"))
check(
"the person who started the run cannot approve it (403)",
isinstance(own, CaliberPermissionError) and "second person" in str(own),
)
no_scope = refused(lambda: member.workflows.runs.approve(paused.workflow_run_id, reason="x"))
check(
"an operator without caliber.approver cannot approve (403)",
isinstance(no_scope, CaliberPermissionError) and "caliber.approver" in str(no_scope),
)
approver.workflows.runs.approve(paused.workflow_run_id, reason="Looks right to me.")
approver.workflows.runs.resume(paused.workflow_run_id)
done = wait_settled(admin, paused.workflow_run_id)
check(
"a second person with the scope approves and the run completes", done.status == "completed"
)
rejected = starter_run("reject")
approver.workflows.runs.reject(rejected.workflow_run_id, reason="Not this one.")
rejected = wait_settled(admin, rejected.workflow_run_id)
check(
"a rejection ends the run as failed with approval_rejected",
rejected.status == "failed" and rejected.extra.get("error_code") == "approval_rejected",
rejected.extra.get("error_code"),
)
result["starter"] = {
"approved_run": done.workflow_run_id,
"rejected_run": rejected.workflow_run_id,
}
# -- 2. The lab workflow: import, validate, Preview refuses -----------------------------
imported = admin.workflows.import_workflow(
manifest=manifest, name=f"{NAME_PREFIX}support-triage-{suffix}"
)
workflow_id = imported.workflow_id
v1 = admin.workflows.versions.list(workflow_id)[0]
report_ = admin.workflows.versions.validate(v1.version_id)
check("the imported manifest validates", report_["valid"] and not report_["errors"])
preview = admin.workflows.versions.preview_run(v1.version_id, input="How do I enable SSO?")
check(
"Preview refuses a workflow with a python_code node",
preview["status"] == "error" and "classify (python_code)" in preview["error"],
preview["error"][:90],
)
v1 = admin.workflows.versions.publish(v1.version_id)
result["workflow_id"] = workflow_id
synchronous = refused(lambda: admin.workflows.versions.run(v1.version_id, input="x"))
check(
"a synchronous run of a workflow with an approval gate is refused (400): use the queue",
synchronous is not None
and synchronous.status_code == 400
and "queued /workflow-runs" in str(synchronous),
)
# -- 3. Staging: a gated promotion waits for a second person ----------------------------
def promote(version_id: str) -> str:
moved = admin.workflows.promote_deployment(workflow_id, "staging", version_id=version_id)
if moved["rotated"]:
return "rotated"
pending = moved["promotion"]
check(
"the staging promotion waits for approval",
pending["status"] == "pending" and moved["deployment"] is None,
pending["promotion_id"],
)
approver.workflows.promotions.approve(pending["promotion_id"], reason="Dataset passed.")
return "approved"
def staging_version() -> str | None:
rows = {row["alias"]: row["version_id"] for row in admin.workflows.deployments(workflow_id)}
return rows.get("staging")
result["promotion"] = promote(v1.version_id)
check("staging now serves version 1", staging_version() == v1.version_id)
# -- 4. The dataset: import it, read it back, run every ticket --------------------------
dataset = admin.eval_datasets.create(
f"{NAME_PREFIX}ticket-cases-{suffix}", owner=me.user_id, description="Cookbook 07 tickets"
)
for row in cases:
admin.eval_datasets.add_example(
dataset.dataset_id,
input=row["input"],
expected=row["expected"],
tags=row.get("tags", []),
)
stored = admin.eval_datasets.examples(dataset.dataset_id)
check("the test set holds every ticket", len(stored) == len(cases), f"{len(stored)} rows")
# The runs below use the rows read back from the server, matched to the file by content, so
# a row that did not survive the import would fail here rather than go unnoticed.
canonical = Counter(json.dumps(row["input"], sort_keys=True) for row in cases)
returned = Counter(json.dumps(row.input, sort_keys=True) for row in stored)
check("the stored rows are the file's rows", canonical == returned)
served = cases
started = time.monotonic()
runs = submit_cases(
admin, served, workflow_id=workflow_id, alias="staging", key=f"{suffix}-v1", retried=retried
)
mismatches = grade(served, runs)
seconds = round(time.monotonic() - started, 1)
check(
"every ticket routed as expected (decision, severity, SLA, approval, flags, path)",
not mismatches,
f"{len(served) - len(mismatches)}/{len(served)} in {seconds}s"
+ (f", {mismatches}" if mismatches else ""),
)
decisions = Counter(triage["decision"] for run in runs.values() if (triage := triage_of(run)))
waiting = [case_id for case_id, run in runs.items() if run.status == "waiting_approval"]
result["batch"] = {
"cases": len(served),
"decisions": dict(sorted(decisions.items())),
"waiting_approval": len(waiting),
}
check(
"exactly the approval-required tickets are paused at the gate",
sorted(waiting)
== sorted(case["id"] for case in cases if case["expected"]["requires_approval"]),
f"{len(waiting)} paused",
)
if real:
replies = {
case["id"]: run_output(runs[case["id"]])
for case in cases
if case["expected"]["decision"] == "reply"
}
check(
"the reply agent wrote real text, not the simulated echo",
all(
text.strip() and not text.startswith("[support-reply]") for text in replies.values()
),
f"{len(replies)} replies",
)
# -- 5. Answer the gate on live runs ----------------------------------------------------
approve_id = next(
case["id"]
for case in cases
if case["expected"]["requires_approval"] and case["expected"]["decision"] == "escalate_bug"
)
reject_id = next(
case["id"]
for case in cases
if case["expected"]["requires_approval"]
and case["expected"]["decision"] == "escalate_support"
)
approver.workflows.runs.approve(runs[approve_id].workflow_run_id, reason="Confirmed defect.")
approver.workflows.runs.resume(runs[approve_id].workflow_run_id)
approved = wait_settled(admin, runs[approve_id].workflow_run_id)
check(
f"{approve_id}: approved, resumed, and the action was released",
approved.status == "completed" and run_output(approved).startswith("APPROVED_ACTION"),
)
approver.workflows.runs.reject(runs[reject_id].workflow_run_id, reason="Over the refund limit.")
refused_run = wait_settled(admin, runs[reject_id].workflow_run_id)
check(
f"{reject_id}: rejected, and no action was released",
refused_run.status == "failed"
and RELEASED_NODE not in node_path(refused_run)
and "APPROVED_ACTION" not in run_output(refused_run),
)
leftovers = [case_id for case_id in waiting if case_id not in {approve_id, reject_id}]
for case_id in leftovers:
admin.workflows.runs.cancel(runs[case_id].workflow_run_id)
cancelled = {
admin.workflows.runs.get(runs[case_id].workflow_run_id).status for case_id in leftovers
}
check(
"the remaining paused runs cancel cleanly",
cancelled == {"cancelled"},
f"{len(leftovers)} runs",
)
# -- 6. A bad version: the dataset catches it, rollback restores it ---------------------
bad_manifest = json.loads(json.dumps(manifest))
code = bad_manifest["nodes"][CLASSIFY_NODE]["code"]
if BAD_RULE[0] not in code:
raise LabVerificationError("the classify code no longer contains the rule the lab breaks")
bad_manifest["nodes"][CLASSIFY_NODE]["code"] = code.replace(*BAD_RULE, 1)
v2 = admin.workflows.versions.create(workflow_id, bad_manifest)
v2 = admin.workflows.versions.publish(v2.version_id)
promote(v2.version_id)
check("staging now serves version 2 (the bad one)", staging_version() == v2.version_id)
bug_cases = [case for case in cases if case["expected"]["decision"] == "escalate_bug"]
bad_runs = submit_cases(
admin,
bug_cases,
workflow_id=workflow_id,
alias="staging",
key=f"{suffix}-v2",
retried=retried,
)
caught = grade(bug_cases, bad_runs)
# The bad rule drops "high" and "urgent" for a bug unless the ticket reports data loss.
expected_caught = sorted(
case["id"]
for case in bug_cases
if case["expected"]["severity"] in {"high", "urgent"}
and "bug-data-loss" not in case["tags"]
)
check(
"the dataset catches the regression (the bug tickets that lost their severity)",
sorted(caught) == expected_caught and bool(caught),
f"{len(caught)} of {len(bug_cases)} bug tickets wrong: {sorted(caught)}",
)
for run_ in bad_runs.values():
if run_.status == "waiting_approval":
admin.workflows.runs.cancel(run_.workflow_run_id)
admin.workflows.rollback_deployment(workflow_id, "staging")
check("rollback puts staging back on version 1", staging_version() == v1.version_id)
again = submit_cases(
admin,
bug_cases,
workflow_id=workflow_id,
alias="staging",
key=f"{suffix}-v1b",
retried=retried,
)
still = grade(bug_cases, again)
check(
"after the rollback the same tickets pass again", not still, f"{len(bug_cases)} bug tickets"
)
for run_ in again.values():
if run_.status == "waiting_approval":
admin.workflows.runs.cancel(run_.workflow_run_id)
result["regression"] = {"caught": sorted(caught), "after_rollback": len(still)}
# -- 7. Run-level audit for the approved run --------------------------------------------
run_id = approved.workflow_run_id
trail = {(e.action, e.actor) for e in admin.audit.list(entity_id=run_id, limit=50)}
approvals = admin.audit.list(action="approve_workflow_run_runtime_approval", limit=200)
trail |= {(e.action, e.actor) for e in approvals if e.details.get("workflow_run_id") == run_id}
check(
"the audit log names who enqueued, who approved and who resumed the approved run",
{
("enqueue_workflow_run", me.user_id),
("approve_workflow_run_runtime_approval", APPROVER_USER),
("resume_workflow_run", APPROVER_USER),
}
<= trail,
f"{len(trail)} entries",
)
result["audited_run"] = run_id
if retried:
result["resubmitted_after_provider_errors"] = sorted(set(retried))
if real:
eval_rows = [case for case in cases if case["id"] in EVAL_TICKETS]
eval_set = admin.eval_datasets.create(
f"{NAME_PREFIX}ticket-eval-{suffix}",
owner=me.user_id,
description="Cookbook 07: twelve labelled tickets (answer = the printed label)",
)
for row in eval_rows:
admin.eval_datasets.add_example(
eval_set.dataset_id,
input=row["input"],
expected={**row["expected"], "answer": row["expected"]["decision"].upper()},
tags=row.get("tags", []),
)
# Evaluations runs the workflow in Preview, which cannot run a Python Code node: the
# deterministic workflow cannot be scored, and the rows say so (they are not silent zeros).
refusal_run = admin.evaluations.create(
eval_set.dataset_id,
predict_target="workflow",
subject_ref=v1.version_id,
scorers=["contains_expected"],
max_examples=2,
)
errors = [str(row.get("error") or "") for row in refusal_run.results]
check(
"Evaluations cannot score the deterministic workflow, and each row says why",
refusal_run.passed_count == 0
and len(errors) == 2
and all("python_code" in e for e in errors),
errors[0][:70] if errors else "",
)
if model_variant:
result["variant"] = run_model_variant(
admin,
approver,
assets=assets,
eval_rows=eval_rows,
eval_set_id=eval_set.dataset_id,
eval_set_name=eval_set.name,
suffix=suffix,
check=check,
)
if failures:
raise LabVerificationError(f"{len(failures)} check(s) failed: {failures}")
report("\nAll documented outcomes verified.")
return result
def label_of(text: str) -> str:
"""The label a variant run starts with: REPLY, CLARIFY, ESCALATE_SUPPORT or ESCALATE_BUG."""
head = text.strip().split(".", 1)[0].strip()
return head if head in {"REPLY", "CLARIFY", "ESCALATE_SUPPORT", "ESCALATE_BUG"} else ""
def run_model_variant(
admin: CaliberClient,
approver: CaliberClient,
*,
assets: Path,
eval_rows: list[dict[str, Any]],
eval_set_id: str,
eval_set_name: str,
suffix: str,
check: Callable[..., None],
) -> dict[str, Any]:
"""The optional variant: a model classifies, a deterministic guard decides.
Asserted (invariants): the variant validates and is evaluated over every labelled ticket with
a deterministic scorer and a judge; through the queue no escalation is released without a
person; the calibration evidence says what measured it. Reported (model-dependent): how many
tickets the model routed as the rules do, and which it did not.
"""
manifest = load_json(assets / VARIANT_FILE)
manifest["name"] = f"{NAME_PREFIX}support-triage-model-{suffix}"
manifest["artifacts"]["eval_datasets"][VARIANT_GATE_DATASET_REF]["dataset_name"] = eval_set_name
imported = admin.workflows.import_workflow(manifest=manifest)
workflow_id = imported.workflow_id
version = admin.workflows.versions.list(workflow_id)[0]
validation = admin.workflows.versions.validate(version.version_id)
check("the model variant validates", validation["valid"] and not validation["errors"])
judge_spec = load_json(assets / JUDGE_FILE)
judge = admin.judges.create(
f"{judge_spec['name']}-{suffix}",
instructions=judge_spec["instructions"],
feedback_value_type=judge_spec["feedback_value_type"],
)
judge_key = f"Judge.{judge.judge_id}"
scorecard = admin.evaluations.create(
eval_set_id,
predict_target="workflow",
subject_ref=version.version_id,
scorers=["contains_expected", judge_key],
max_examples=len(eval_rows),
)
errored = [row for row in scorecard.results if row.get("error")]
label_score = scorecard.aggregate.get("contains_expected")
judge_score = scorecard.aggregate.get(judge_key)
check(
"Evaluations scores the model variant over every labelled ticket",
scorecard.status == "completed"
and scorecard.n_examples == len(eval_rows)
and not errored
and label_score is not None
and 0.5 <= label_score <= 1.0,
f"label agreement {label_score}, judge {judge_score}, {len(errored)} rows errored",
)
check(
"the model-graded judge ran next to the deterministic scorer",
judge_score is not None and 0.0 <= judge_score <= 1.0,
judge_score,
)
disagreements = sorted(
str(row["example_id"])
for row in scorecard.results
if (row.get("scores") or {}).get("contains_expected", 0.0) < 1.0
)
# Through the queue: whatever the model proposes, an escalation waits for a person.
admin.workflows.update(workflow_id, status="active")
published = admin.workflows.versions.publish(version.version_id)
queued = {
row["id"]: admin.workflows.runs.submit(
workflow_version_id=published.version_id,
input=json.dumps(row["input"]),
idempotency_key=f"{suffix}-variant-{row['id']}",
)
for row in eval_rows
}
runs = {row_id: wait_settled(admin, run.workflow_run_id) for row_id, run in queued.items()}
# Nobody has approved anything yet, so a run that reached a release node, or that completed
# with an escalation label, got there without a person.
released_without_approval = [
row_id
for row_id, run_ in runs.items()
if any(node in node_path(run_) for node in VARIANT_RELEASE_NODES)
or (run_.status == "completed" and label_of(run_output(run_)).startswith("ESCALATE"))
]
paused = sorted(row_id for row_id, run_ in runs.items() if run_.status == "waiting_approval")
check(
"through the queue, no escalation is released without a person",
not released_without_approval and all(r.status != "failed" for r in runs.values()),
f"{len(paused)} of {len(runs)} runs paused at an approval gate",
)
if paused:
approver.workflows.runs.approve(runs[paused[0]].workflow_run_id, reason="Looks right.")
approver.workflows.runs.resume(runs[paused[0]].workflow_run_id)
released = wait_settled(admin, runs[paused[0]].workflow_run_id)
check(
"a second person's approval releases the escalation",
released.status == "completed" and run_output(released).startswith("ESCALATE"),
run_output(released)[:30],
)
for row_id in paused[1:]:
admin.workflows.runs.cancel(runs[row_id].workflow_run_id)
agent_id = f"{NAME_PREFIX}agent-{suffix}"
admin.agents.create(agent_id, experiment_id=f"exp-{suffix}", name="support triage model")
calibration = admin.workflows.create_calibration_run(workflow_id, agent_id=agent_id)
job = admin.jobs.wait(calibration["job"]["job_id"], timeout=900)
evidence = job.eval_results or {}
check(
"the calibration evidence says what measured its baseline",
evidence.get("simulated") is False
and evidence.get("provider") not in (None, "fake")
and evidence.get("scorer") == "structural"
and evidence.get("n_examples", 0) >= 2,
{k: evidence.get(k) for k in ("provider", "simulated", "scorer", "n_examples")},
)
return {
"tickets": len(eval_rows),
"label_agreement": label_score,
"judge": judge_score,
"disagreements": disagreements,
"paused_at_gate": len(paused),
"calibration": {
"status": job.status,
"n_examples": evidence.get("n_examples"),
"baseline_quality": (evidence.get("baseline") or {}).get("overall"),
"candidates": len(evidence.get("calibration_candidates") or []),
"provider": evidence.get("provider"),
"simulated": evidence.get("simulated"),
"scorer": evidence.get("scorer"),
},
"evaluation_run": scorecard.run_id,
}
def cleanup(caliber: CaliberClient) -> None:
"""Archive the projects, workflows, test sets and judges this lab created."""
for project in caliber.projects.list():
if project.name.startswith(NAME_PREFIX):
caliber.projects.archive(project.project_id)
for workflow in caliber.workflows.list():
if workflow.name.startswith(NAME_PREFIX) and workflow.status != "archived":
caliber.workflows.update(workflow.workflow_id, status="archived")
for dataset in caliber.eval_datasets.list():
if dataset.name.startswith(NAME_PREFIX) and dataset.status != "archived":
caliber.eval_datasets.update(dataset.dataset_id, status="archived")
# The judges the real-provider tier created ("<judge name>-<suffix>").
for judge in caliber.judges.list():
if (
judge.name.startswith("SupportTriageRoutingAndReply-")
and getattr(judge, "status", "active") != "archived"
):
caliber.judges.update(judge.judge_id, status="archived")
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
parser.add_argument("--cleanup", action="store_true", help="archive what earlier runs created")
parser.add_argument("--suffix", help="name suffix (default: a timestamp)")
parser.add_argument(
"--model-variant",
action="store_true",
help="also run the optional model-based variant (real provider only)",
)
args = parser.parse_args(argv)
base_url = os.environ["CALIBER_BASE_URL"]
password = os.environ.get("COOKBOOK_07_PASSWORD", DEFAULT_PASSWORD)
opened: list[CaliberClient] = []
def project_client(user_id: str, project_id: str) -> CaliberClient:
if user_id in (APPROVER_USER, MEMBER_USER):
token = sign_in(base_url, user_id, password)
else:
token = os.environ["CALIBER_TOKEN"]
client = CaliberClient(base_url, token=token, project=project_id, timeout=REQUEST_TIMEOUT)
opened.append(client)
return client
with env_client(timeout=REQUEST_TIMEOUT) as caliber:
try:
if args.cleanup:
cleanup(caliber)
return 0
ensure_accounts(caliber, password)
result = run(
caliber,
project_client=project_client,
suffix=args.suffix,
model_variant=args.model_variant,
)
except (LabVerificationError, SetupError) as exc:
print(f"\nVERIFICATION FAILED: {exc}", file=sys.stderr)
return 1
finally:
for client in opened:
client.close()
print(json.dumps(result, indent=2, sort_keys=True, default=str))
return 0
if __name__ == "__main__":
sys.exit(main())sdk/caliber-sdk/examples/cookbooks/cookbook_07_support_triage_copilot.py — executed by the SDK example test suite.Cookbook 08 — Incident Response Copilot
Install the incident-commander starter, import the lab workflow (refused until its 41-incident test set exists), Preview it, promote it through a gated prod alias whose deploy gate replays the dataset, then run all 41 incidents through the queue and assert severity, action and path (41/41) with exactly the 5 rollback incidents paused at the approval gate. It also checks that the gate refuses a bad version, exercises four failure drills (Error Boundary, unregistered tool, blocked API Request host, Wait For Event), rolls back, and asks for a workflow calibration. It needs an admin-scoped SDK token and a server started with CALIBER_FEATURE_COOKBOOKS=true, CALIBER_OPERATOR_USERS=admin,lena,sam, CALIBER_APPROVER_USERS=admin,lena, a production human-approval policy and the graded-executor requirement emptied; no model is needed. The deploy gate replays with the simulated executor and says so, draft_update runs on the simulated provider, and evidence is supplied inside each incident record. It does not use client.raw (it signs in as lena with plain httpx calls).
SDK surfaces: cookbooks, projects, auth, workflows, datasets, evaluations, jobs
- Install the starter recipe and run it through the queue; Preview refuses it because its API Request nodes cannot be isolated.
- Import the 41-incident test set (the workflow import is refused until it exists), then import and validate the commander workflow and Preview it, where every node is declarative and the dataset's verdicts hold.
- Publish it and move the aliases:
stagingrotates at once, andprodreplays all 41 incidents through the deploy gate (pass rate 1.0, executor reported as simulated) and waits for a second person to approve; a bad rollback rule is refused by the gate andprodstays on version 1. - Run every incident through the queue against
prod, check severity, action and path (41/41), and answer the rollback gate: self-approval 403, approve releasesROLLBACK_APPROVED, reject releases nothing, cancel the rest. - Run the failure drills: an Error Boundary degrades a failing lookup to a fallback, an unregistered tool is refused at import, a blocked API Request host fails the run with the egress reason, and a Wait For Event run pauses with a readable checkpoint and completes when its event arrives.
- Promote a good version and roll
prodback to version 1, create a workflow calibration run (it reports no candidate), and confirm the Evaluations route refuses workflow scoring without a real model (400).
"""Cookbook 08: an incident commander workflow, gated, queued and approved, for real.
This is the executable form of ``docs-site/cookbooks/08-incident-response-commander/README.md``.
It drives a real CALIBER server and exits 0 only when every documented outcome was verified:
1. install the Cookbooks starter (``08``) and run it through the queue; Preview refuses it because
it holds API Request nodes (they cannot be isolated);
2. import ``assets/dataset/incident-cases.jsonl`` (41 incidents) as a test set, then import the lab
workflow (``assets/workflows/incident-commander.workflow.json``). The workflow names that test
set in its deploy gate, so the import is refused until the test set exists;
3. validate it and Preview it: every node is declarative, so Preview runs it, and the dataset's
verdicts hold in Preview as well (severity and action for every incident);
4. publish it and move the aliases: ``staging`` rotates at once; ``prod`` replays the dataset
through the deploy gate (the executor is the simulated one, and the gate says so), then waits
for a second person to approve the promotion;
5. publish a version with a bad rule and watch the gate refuse it (``prod`` does not move);
6. run every incident through the queue against ``prod``: check severity, action and path, and
answer the rollback approval gate (self-approval 403, approve, reject, cancel the rest);
7. the failure drills: an Error Boundary turns a failing lookup into a fallback, a workflow
naming an unregistered tool is refused at import, an API Request that reaches a blocked host
fails the run, and a Wait For Event run pauses until its event arrives (its checkpoint is
readable);
8. publish a good version, promote it, and roll ``prod`` back; ask for a workflow calibration and
read its outcome; and confirm the Evaluations route refuses workflow scoring without a model.
Two modes, detected from ``GET /readiness`` (``simulated`` empty means a real provider):
* Simulated stack (the default): the deploy gate names the fake executor, the workflow calibration
reports a ``simulated`` baseline, and Evaluations refuses workflow scoring (400).
* Real provider (``scripts/cookbook-env.sh up NAME --flags cookbooks --real-llm``): the gate replays
the incidents through a real model (and says so), the calibration baseline is measured and not
marked simulated, and Evaluations scores the workflow for real with a deterministic scorer and a
model-graded judge. ``--model-variant`` also imports the optional model-based variant
(``incident-commander-model.workflow.json``), where an agent proposes a severity and action and
the decision tables still decide. The script asserts invariants (markers, counts, "the model
cannot authorise a rollback"), never generated text or an exact model score.
Environment (see the lab README): ``CALIBER_BASE_URL`` (the server root without the API path) and
``CALIBER_TOKEN`` (an ADMIN personal access token). The server must have been started as the README
shows (``CALIBER_OPERATOR_USERS``/``CALIBER_APPROVER_USERS`` naming ``lena``, release policy for
``production``). Optional: ``COOKBOOK_08_ASSETS``, ``COOKBOOK_08_PASSWORD``.
PYTHONPATH=sdk/caliber-sdk caliber/.venv/bin/python \
-m examples.cookbooks.cookbook_08_incident_response_copilot
... --cleanup # archive what earlier runs created
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import time
from collections import Counter
from collections.abc import Callable
from pathlib import Path
from typing import Any
from caliber_sdk import CaliberClient, wait_for
from caliber_sdk.errors import CaliberAPIError, CaliberPermissionError
from examples.cookbooks._helpers import PAUSED_OR_TERMINAL_RUN_STATES, env_client
from examples.cookbooks.cookbook_07_support_triage_copilot import (
APPROVER_USER,
MEMBER_USER,
ensure_accounts,
is_real_stack,
refused,
resubmit_transient,
sign_in,
)
from examples.cookbooks.cookbook_07_support_triage_copilot import (
LabVerificationError as LabVerificationError, # re-exported: the lab's test imports it here
)
from examples.cookbooks.cookbook_07_support_triage_copilot import (
SetupError as SetupError, # re-exported: the lab's test imports it here
)
NAME_PREFIX = "cookbook-08-"
DEFAULT_PASSWORD = "cookbook08-lab-passphrase"
GATE_DATASET_REF = "incident-cases"
APPROVAL_NODE = "review"
RELEASED_TEXT = "ROLLBACK_APPROVED"
#: The node each action ends at when no approval is needed.
TERMINAL_NODE = {
"escalate_human": "handoff_note",
"gather_more_evidence": "handoff_note",
"disable_feature_flag": "recommendation",
"scale_out": "recommendation",
"monitor": "recommendation",
}
#: The regression the gate must catch: rollbacks that need the error rate to reach 50%.
BAD_RULE = ('"value": 0.05}]', '"value": 0.5}]')
#: The optional model-based variant of the workflow (real provider only).
VARIANT_FILE = "workflows/incident-commander-model.workflow.json"
JUDGE_FILE = "judges/stakeholder-update-honesty.judge.json"
#: Incidents the variant is run over (Preview): one or two per action, plus the vague and the
#: conflicting-evidence cases where a model is most likely to disagree with the tables.
VARIANT_INCIDENTS = ("IN01", "IN02", "IN03", "IN04", "IN05", "IN07", "IN09", "IN12", "IN36", "IN38")
#: How many incidents a real Evaluations run scores (the route caps a workflow run at 20).
EVAL_MAX_EXAMPLES = 8
#: Seconds a single request may take. A real provider answers a gate replay or an evaluation inside
#: one request, which takes minutes (the SDK default is 30 s).
REQUEST_TIMEOUT = 900.0
Report = Callable[[str], None]
def default_assets_dir() -> Path:
override = os.environ.get("COOKBOOK_08_ASSETS")
if override:
return Path(override)
return (
Path(__file__).resolve().parents[4]
/ "docs-site/cookbooks/08-incident-response-commander/assets"
)
def load_cases(path: Path) -> list[dict[str, Any]]:
rows = [
json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()
]
for row in rows:
if not {"id", "input", "expected"} <= set(row):
raise LabVerificationError(f"{path.name}: row {row.get('id')} lacks id/input/expected")
return rows
def load_json(path: Path) -> dict[str, Any]:
return dict(json.loads(path.read_text(encoding="utf-8")))
def summary_of(run: Any) -> dict[str, Any]:
return dict((run.extra or {}).get("summary") or {})
def node_path(run: Any) -> list[str]:
return list(summary_of(run).get("node_path") or [])
def verdict_of(run: Any) -> dict[str, Any] | None:
"""The verdict the ``summarize`` node produced, from the run's own step trace."""
for step in summary_of(run).get("steps") or []:
if step.get("node_id") == "summarize":
result = (step.get("output_by_port") or {}).get("result")
return dict(result) if isinstance(result, dict) else None
return None
def run_output(run: Any) -> str:
return str(summary_of(run).get("output") or "")
def terminal_node(action: str) -> str:
return APPROVAL_NODE if action == "rollback" else TERMINAL_NODE[action]
def problems_for(case: dict[str, Any], run: Any) -> list[str]:
expected = case["expected"]
verdict = verdict_of(run)
if verdict is None:
return [f"no verdict (status {run.status}, error {run.error})"]
found = [
f"{key}: expected {expected[key]!r}, got {verdict.get(key)!r}"
for key in ("severity", "action")
if verdict.get(key) != expected[key]
]
path = node_path(run)
if expected["requires_approval"]:
if run.status != "waiting_approval" or not path or path[-1] != APPROVAL_NODE:
found.append(f"expected a pause at {APPROVAL_NODE!r}, got {run.status} via {path}")
else:
terminal = terminal_node(expected["action"])
if run.status != "completed" or terminal not in path or APPROVAL_NODE in path:
found.append(f"expected completion via {terminal!r}, got {run.status} via {path}")
return found
def wait_settled(caliber: CaliberClient, run_id: str, *, timeout: float = 240.0) -> Any:
return wait_for(
lambda: caliber.workflows.runs.get(run_id),
is_done=lambda item: item.status in PAUSED_OR_TERMINAL_RUN_STATES,
interval=0.5,
max_interval=2.0,
timeout=timeout,
)
def submit_cases(
caliber: CaliberClient,
cases: list[dict[str, Any]],
*,
workflow_id: str,
alias: str,
key: str,
retried: list[str] | None = None,
) -> dict[str, Any]:
inputs = {case["id"]: json.dumps(case["input"]) for case in cases}
queued = {
case["id"]: caliber.workflows.runs.submit(
workflow_id=workflow_id,
alias=alias,
input=inputs[case["id"]],
idempotency_key=f"{key}-{case['id']}",
)
for case in cases
}
runs = {case_id: wait_settled(caliber, run.workflow_run_id) for case_id, run in queued.items()}
# A real provider can drop a connection or push back: resubmit those runs, only those.
return resubmit_transient(
caliber, runs, inputs, workflow_id=workflow_id, alias=alias, key=key, retried=retried
)
def grade(cases: list[dict[str, Any]], runs: dict[str, Any]) -> dict[str, list[str]]:
return {case["id"]: found for case in cases if (found := problems_for(case, runs[case["id"]]))}
def run(
caliber: CaliberClient,
*,
project_client: Callable[[str, str], CaliberClient],
suffix: str | None = None,
assets: Path | None = None,
report: Report = print,
model_variant: bool = False,
) -> dict[str, Any]:
"""Run the whole lab. ``project_client(user_id, project_id)`` returns that person's client.
``model_variant`` adds the optional model-based variant after the main lab (real provider only).
"""
assets = assets or default_assets_dir()
suffix = suffix or time.strftime("%Y%m%d-%H%M%S")
cases = load_cases(assets / "dataset/incident-cases.jsonl")
manifest = load_json(assets / "workflows/incident-commander.workflow.json")
failures: list[str] = []
retried: list[str] = []
result: dict[str, Any] = {"suffix": suffix}
def check(label: str, ok: bool, detail: Any = "") -> None:
report(f"{'ok ' if ok else 'FAIL'} {label}" + (f" [{detail}]" if detail != "" else ""))
if not ok:
failures.append(label)
me = caliber.me.get()
if not me.is_admin:
raise SetupError("CALIBER_TOKEN must be an admin personal access token")
if "08" not in {recipe.id for recipe in caliber.cookbooks.list()}:
raise SetupError("Cookbooks are off: start the server with CALIBER_FEATURE_COOKBOOKS=true")
real = is_real_stack(caliber)
result["mode"] = "real" if real else "simulated"
if model_variant and not real:
raise SetupError("--model-variant needs a real provider (start with --real-llm)")
# -- 0. The project and the people ------------------------------------------------------
project = caliber.projects.create(
f"{NAME_PREFIX}incident-ops-{suffix}", description="Cookbook 08 incident response"
)
for user in (APPROVER_USER, MEMBER_USER):
caliber.projects.add_member(project.project_id, user, role="reviewer")
admin = project_client(me.user_id, project.project_id)
approver = project_client(APPROVER_USER, project.project_id)
scopes = set(approver.me.get().scopes)
if "caliber.approver" not in scopes:
raise SetupError(
"start CALIBER with CALIBER_OPERATOR_USERS=admin,lena,sam and "
"CALIBER_APPROVER_USERS=admin,lena (lena approves)"
)
result["project_id"] = project.project_id
# -- 1. The starter: it runs, Preview refuses it ----------------------------------------
installed = admin.cookbooks.install(
"08", name=f"{NAME_PREFIX}starter-{suffix}", acknowledge_prerequisites=True
)
admin.workflows.update(installed["workflow"]["workflow_id"], status="active")
starter = admin.workflows.versions.publish(installed["version"]["version_id"])
queued = admin.workflows.runs.submit(
workflow_version_id=starter.version_id,
input="gateway 5xx after deploy a1b9f3c",
idempotency_key=f"{suffix}-starter",
)
starter_run = wait_settled(admin, queued.workflow_run_id)
check(
"the installed starter runs through the queue",
starter_run.status == "completed",
starter_run.workflow_run_id,
)
refusal = admin.workflows.versions.preview_run(starter.version_id, input="x")
check(
"Preview refuses the starter (its API Request nodes cannot be isolated)",
refusal["status"] == "error" and "(api_request)" in refusal["error"],
refusal["error"][-70:],
)
# -- 2. The test set first, then the workflow that names it ------------------------------
dataset_name = f"{NAME_PREFIX}incident-cases-{suffix}"
manifest["name"] = f"{NAME_PREFIX}incident-commander-{suffix}"
manifest["artifacts"]["eval_datasets"][GATE_DATASET_REF]["dataset_name"] = dataset_name
early = admin.workflows.preview_import(manifest=manifest)
codes = {error["code"] for error in early["validation"]["errors"]}
check(
"the workflow cannot be imported before its test set exists",
not early["ready_to_import"] and "unresolved_import_dependency" in codes,
sorted(codes),
)
dataset = admin.eval_datasets.create(
dataset_name, owner=me.user_id, description="Cookbook 08 incidents"
)
for row in cases:
admin.eval_datasets.add_example(
dataset.dataset_id, input=row["input"], expected=row["expected"], tags=row["tags"]
)
stored = admin.eval_datasets.examples(dataset.dataset_id)
canonical = Counter(json.dumps(row["input"], sort_keys=True) for row in cases)
returned = Counter(json.dumps(row.input, sort_keys=True) for row in stored)
check(
"the test set holds every incident, unchanged",
len(stored) == len(cases) and canonical == returned,
f"{len(stored)} rows",
)
imported = admin.workflows.import_workflow(manifest=manifest)
workflow_id = imported.workflow_id
v1 = admin.workflows.versions.list(workflow_id)[0]
validation = admin.workflows.versions.validate(v1.version_id)
check("the imported manifest validates", validation["valid"] and not validation["errors"])
result["workflow_id"] = workflow_id
# -- 3. Preview works: every node is declarative ----------------------------------------
previews = {
case["id"]: admin.workflows.versions.preview_run(
v1.version_id, input=json.dumps(case["input"])
)
for case in cases[:6]
}
ok_previews = [
case_id
for case_id, preview in previews.items()
if preview["status"] == "completed" and "Verdict: " in preview["output"]
]
check("Preview runs the workflow (no node needs isolating)", len(ok_previews) == len(previews))
# -- 4. Publish; staging rotates, prod is gated and approved ----------------------------
v1 = admin.workflows.versions.publish(v1.version_id)
def deployed(alias: str) -> str | None:
rows = {row["alias"]: row["version_id"] for row in admin.workflows.deployments(workflow_id)}
return rows.get(alias)
def promote(version_id: str, alias: str = "prod") -> dict[str, Any]:
try:
moved = admin.workflows.promote_deployment(workflow_id, alias, version_id=version_id)
except CaliberAPIError as exc:
if "graded" in str(exc):
raise SetupError(
"the server wants a real model for production gates: start it with "
"CALIBER_RELEASE_REQUIRE_GRADED_EXECUTOR_FOR_ENVIRONMENT_CLASSES= (empty), "
"as the README shows"
) from exc
raise
if not moved["rotated"]:
pending = moved["promotion"]
approver.workflows.promotions.approve(pending["promotion_id"], reason="Gate passed.")
return dict(moved)
admin.workflows.promote_deployment(workflow_id, "staging", version_id=v1.version_id)
check("staging rotates at once (it is not gated)", deployed("staging") == v1.version_id)
moved = promote(v1.version_id)
gate = moved["gate"]
gate_run = gate["runs"][0]
check(
"the prod gate replayed every incident and passed",
gate["has_gate"]
and gate["passed"]
and gate_run["n_examples"] == len(cases)
and gate_run["pass_rate"] == 1.0,
f"{gate_run['n_examples']} replays, pass rate {gate_run['pass_rate']}",
)
executor = gate["executor"]
if real:
check(
"the gate says its executor is a real model, not the simulated one",
executor["provider"] != "fake" and executor["deterministic"] is False,
executor,
)
else:
check(
"the gate says its executor is the simulated one",
executor["provider"] == "fake" and executor["deterministic"] is True,
executor,
)
check(
"prod waits for a second person, then serves version 1",
moved["rotated"] is False and deployed("prod") == v1.version_id,
"promotion approved by " + APPROVER_USER,
)
# -- 5. A bad version: the gate refuses it ----------------------------------------------
# Derive new versions from the stored manifest: it carries the workflow's real id.
stored_manifest = admin.workflows.versions.get(v1.version_id).manifest
bad = json.loads(json.dumps(stored_manifest))
bad_text = json.dumps(bad["nodes"]["action_table"])
if BAD_RULE[0] not in bad_text:
raise LabVerificationError("the action table no longer holds the rule the lab breaks")
bad["nodes"]["action_table"] = json.loads(bad_text.replace(*BAD_RULE, 1))
v2 = admin.workflows.versions.create(workflow_id, bad)
v2 = admin.workflows.versions.publish(v2.version_id)
blocked = refused(
lambda: admin.workflows.promote_deployment(workflow_id, "prod", version_id=v2.version_id)
)
body = (blocked.payload or {}) if blocked else {}
failing = (body.get("gate") or {}).get("runs") or [{}]
check(
"the gate refuses the bad version (400) and says why",
blocked is not None
and blocked.status_code == 400
and failing[0].get("passed") is False
and failing[0].get("n_examples") == len(cases)
and failing[0].get("pass_rate", 1.0) < 1.0,
f"pass rate {failing[0].get('pass_rate')} over {failing[0].get('n_examples')} replays",
)
check("prod still serves version 1", deployed("prod") == v1.version_id)
result["gate"] = {"good": gate_run["pass_rate"], "bad": failing[0].get("pass_rate")}
# -- 6. Every incident through the queue, against prod -----------------------------------
started = time.monotonic()
runs = submit_cases(
admin, cases, workflow_id=workflow_id, alias="prod", key=f"{suffix}-prod", retried=retried
)
mismatches = grade(cases, runs)
seconds = round(time.monotonic() - started, 1)
check(
"every incident got the expected severity, action and path",
not mismatches,
f"{len(cases) - len(mismatches)}/{len(cases)} in {seconds}s"
+ (f", {mismatches}" if mismatches else ""),
)
waiting = sorted(case_id for case_id, item in runs.items() if item.status == "waiting_approval")
rollbacks = sorted(c["id"] for c in cases if c["expected"]["action"] == "rollback")
check("exactly the rollback incidents are paused at the gate", waiting == rollbacks, waiting)
result["batch"] = {
"cases": len(cases),
"severities": dict(sorted(Counter(c["expected"]["severity"] for c in cases).items())),
"actions": dict(sorted(Counter(c["expected"]["action"] for c in cases).items())),
"waiting_approval": waiting,
}
approve_id, reject_id = waiting[0], waiting[1]
own = refused(lambda: admin.workflows.runs.approve(runs[approve_id].workflow_run_id))
check(
"the person who started the run cannot approve the rollback (403)",
isinstance(own, CaliberPermissionError),
)
approver.workflows.runs.approve(runs[approve_id].workflow_run_id, reason="Deploy is the cause.")
approver.workflows.runs.resume(runs[approve_id].workflow_run_id)
approved = wait_settled(admin, runs[approve_id].workflow_run_id)
check(
f"{approve_id}: approved, resumed, rollback released",
approved.status == "completed" and run_output(approved).startswith(RELEASED_TEXT),
run_output(approved)[:40],
)
approver.workflows.runs.reject(runs[reject_id].workflow_run_id, reason="Not the deploy.")
rejected = wait_settled(admin, runs[reject_id].workflow_run_id)
check(
f"{reject_id}: rejected, nothing released",
rejected.status == "failed" and RELEASED_TEXT not in run_output(rejected),
)
for case_id in waiting[2:]:
admin.workflows.runs.cancel(runs[case_id].workflow_run_id)
left = {admin.workflows.runs.get(runs[i].workflow_run_id).status for i in waiting[2:]}
check("the remaining paused runs cancel cleanly", left == {"cancelled"}, f"{len(waiting) - 2}")
# -- 7. Failure drills -------------------------------------------------------------------
def drill(file: str) -> dict[str, Any]:
spec = load_json(assets / "workflows" / file)
spec["name"] = f"{NAME_PREFIX}{spec['name']}-{suffix}"
return spec
def published_drill(file: str) -> Any:
created = admin.workflows.import_workflow(manifest=drill(file))
version = admin.workflows.versions.list(created.workflow_id)[0]
return admin.workflows.versions.publish(version.version_id)
def run_once(version: Any, text: str, key: str) -> Any:
queued_run = admin.workflows.runs.submit(
workflow_version_id=version.version_id,
input=text,
idempotency_key=f"{suffix}-{key}",
)
return wait_settled(admin, queued_run.workflow_run_id)
lookup = published_drill("evidence-lookup-drill.workflow.json")
good = run_once(lookup, '{"service": "gateway", "environment": "prod"}', "lookup-ok")
bad_lookup = run_once(lookup, "not json at all", "lookup-bad")
check(
"Error Boundary: a good request returns the deployments",
good.status == "completed" and "a1b9f3c" in run_output(good),
)
check(
"Error Boundary: a failing lookup degrades to the fallback and the run completes",
bad_lookup.status == "completed" and run_output(bad_lookup).startswith("NO_EVIDENCE"),
run_output(bad_lookup)[:30],
)
preview = admin.workflows.versions.preview_run(lookup.version_id, input="{}")
check(
"Preview refuses a Python Code node",
preview["status"] == "error" and "(python_code)" in preview["error"],
)
missing = refused(
lambda: admin.workflows.import_workflow(manifest=drill("missing-tool-drill.workflow.json"))
)
check(
"a workflow naming an unregistered tool is refused at import (400)",
missing is not None and missing.status_code == 400,
"preflight failed",
)
status_page = run_once(published_drill("status-page-drill.workflow.json"), "INC-9", "status")
check(
"an API Request to a blocked host fails the run with the egress reason",
status_page.status == "failed" and "blocked" in str(status_page.extra.get("error_summary")),
str(status_page.extra.get("error_summary"))[:70],
)
wait_version = published_drill("mitigation-wait-drill.workflow.json")
waiting_run = run_once(
wait_version,
json.dumps({"incident_id": "INC-9"}),
"wait",
)
checkpoints = admin.workflows.runs.checkpoints(waiting_run.workflow_run_id)
check(
"Wait For Event: the run pauses with a readable checkpoint",
waiting_run.status == "waiting_event"
and checkpoints
and checkpoints[0]["state_blob"]["expected_event_name"] == "incident.mitigation_confirmed",
waiting_run.status,
)
admin.workflows.runs.resume_by_event(
event_name="incident.mitigation_confirmed",
event_payload={"incident_id": "INC-9", "confirmed": True},
workflow_id=wait_version.workflow_id,
)
resumed = wait_for(
lambda: admin.workflows.runs.get(waiting_run.workflow_run_id),
is_done=lambda item: item.status not in {"waiting_event", "queued", "running"},
interval=0.5,
timeout=60,
)
check("Wait For Event: the event resumes the run to completion", resumed.status == "completed")
# -- 8. A good version, rollback, calibration, Evaluations -------------------------------
better = json.loads(json.dumps(stored_manifest))
better["description"] += " (v3: same rules, new description)"
v3 = admin.workflows.versions.create(workflow_id, better)
v3 = admin.workflows.versions.publish(v3.version_id)
promote(v3.version_id)
check("a good version passes the gate and prod moves to it", deployed("prod") == v3.version_id)
admin.workflows.rollback_deployment(workflow_id, "prod")
check("rollback puts prod back on version 1", deployed("prod") == v1.version_id)
agent_id = f"{NAME_PREFIX}agent-{suffix}"
admin.agents.create(agent_id, experiment_id=f"exp-{suffix}", name="incident commander")
calibration = admin.workflows.create_calibration_run(workflow_id, agent_id=agent_id)
job = admin.jobs.wait(calibration["job"]["job_id"], timeout=900 if real else 300)
eval_results = job.eval_results or {}
check(
"a workflow calibration runs against the test set and reports its baseline",
bool(eval_results.get("workflow"))
and eval_results.get("n_examples", 0) >= 20
and "baseline" in eval_results,
f"{job.status}: {(eval_results.get('gate') or {}).get('reasons')}",
)
# Whatever the outcome, the evidence says what measured it (the UI's "Simulated evaluation" and
# "Structural score" markers read these fields, also when no candidate was found).
check(
"the calibration evidence says what measured its baseline",
eval_results.get("simulated") is (not real)
and eval_results.get("scorer") == "structural"
and (eval_results.get("provider") == "fake") is (not real),
{k: eval_results.get(k) for k in ("provider", "simulated", "scorer")},
)
result["calibration"] = {
"status": job.status,
"n_examples": eval_results.get("n_examples"),
"baseline_quality": (eval_results.get("baseline") or {}).get("overall"),
"candidates": len(eval_results.get("calibration_candidates") or []),
"provider": eval_results.get("provider"),
"simulated": eval_results.get("simulated"),
"scorer": eval_results.get("scorer"),
}
if real:
judge_spec = load_json(assets / JUDGE_FILE)
judge = admin.judges.create(
f"{judge_spec['name']}-{suffix}",
instructions=judge_spec["instructions"],
feedback_value_type=judge_spec["feedback_value_type"],
)
scorecard = admin.evaluations.create(
dataset.dataset_id,
predict_target="workflow",
subject_ref=v1.version_id,
scorers=["contains_expected", f"Judge.{judge.judge_id}"],
max_examples=EVAL_MAX_EXAMPLES,
)
sampling = (scorecard.evidence or {}).get("sampling") or {}
verdict_score = scorecard.aggregate.get("contains_expected")
check(
"Evaluations scores the workflow version for real over the test set",
scorecard.status == "completed"
and scorecard.n_examples == EVAL_MAX_EXAMPLES
and sampling.get("available_examples") == len(cases)
and sampling.get("truncated") is True
and verdict_score is not None
and verdict_score >= 0.9,
f"{scorecard.passed_count}/{scorecard.n_examples} passed, contains_expected "
f"{verdict_score}, judge {scorecard.aggregate.get(f'Judge.{judge.judge_id}')}",
)
judge_score = scorecard.aggregate.get(f"Judge.{judge.judge_id}")
check(
"the model-graded judge ran next to the deterministic scorer",
judge_score is not None and 0.0 <= judge_score <= 1.0,
judge_score,
)
result["evaluation"] = {
"run_id": scorecard.run_id,
"n_examples": scorecard.n_examples,
"available_examples": sampling.get("available_examples"),
"pass_rate": scorecard.pass_rate,
"contains_expected": verdict_score,
"judge": judge_score,
"model": scorecard.model,
}
else:
evaluation = refused(
lambda: admin.evaluations.create(
dataset.dataset_id,
predict_target="workflow",
subject_ref=v1.version_id,
scorers=["contains_expected"],
)
)
check(
"Evaluations refuses workflow scoring without a real model (400)",
evaluation is not None
and evaluation.status_code == 400
and "real LLM provider" in str(evaluation),
)
if model_variant:
result["variant"] = run_model_variant(
admin, assets=assets, cases=cases, suffix=suffix, check=check
)
if retried:
result["resubmitted_after_provider_errors"] = sorted(set(retried))
if failures:
raise LabVerificationError(f"{len(failures)} check(s) failed: {failures}")
report("\nAll documented outcomes verified.")
return result
def parse_proposal(text: str) -> dict[str, Any] | None:
"""The JSON object a model replied with, however it fenced or padded it; ``None`` if none."""
start, end = text.find("{"), text.rfind("}")
if start < 0 or end <= start:
return None
try:
value = json.loads(text[start : end + 1])
except ValueError:
return None
return value if isinstance(value, dict) else None
def run_model_variant(
admin: CaliberClient,
*,
assets: Path,
cases: list[dict[str, Any]],
suffix: str,
check: Callable[..., None],
) -> dict[str, Any]:
"""The optional variant: a model agent proposes a triage, the decision tables still decide.
What a real model changes is the proposal and the stakeholder update, and nothing else:
the verdict (severity and action), the path and the approval gate come from the tables, so
they are asserted exactly. How often the model agrees with the tables is reported, not asserted
(it varies from run to run).
"""
manifest = load_json(assets / VARIANT_FILE)
manifest["name"] = f"{NAME_PREFIX}incident-commander-model-{suffix}"
imported = admin.workflows.import_workflow(manifest=manifest)
version = admin.workflows.versions.list(imported.workflow_id)[0]
validation = admin.workflows.versions.validate(version.version_id)
check("the model variant validates", validation["valid"] and not validation["errors"])
wanted = {case["id"]: case for case in cases if case["id"] in VARIANT_INCIDENTS}
verdict_ok: list[str] = []
gate_ok: list[str] = []
parsed: dict[str, dict[str, Any]] = {}
for case_id, case in wanted.items():
preview = admin.workflows.versions.preview_run(
version.version_id, input=json.dumps(case["input"])
)
output = str(preview.get("output") or "")
verdict = parse_proposal(
output[output.find("Verdict: ") :] if "Verdict: " in output else ""
)
expected = case["expected"]
if (
preview["status"] == "completed"
and verdict
and verdict.get("severity") == expected["severity"]
and verdict.get("action") == expected["action"]
):
verdict_ok.append(case_id)
# Preview passes the approval node as if approved, so the release text appears exactly
# when the *tables* say rollback, whatever the model proposed.
if output.startswith("ROLLBACK_APPROVED") is (expected["action"] == "rollback"):
gate_ok.append(case_id)
proposal = parse_proposal(str((verdict or {}).get("model_proposal") or ""))
if proposal:
parsed[case_id] = proposal
check(
"the model variant's verdicts equal the tables' (the model cannot change a decision)",
sorted(verdict_ok) == sorted(wanted),
f"{len(verdict_ok)}/{len(wanted)}",
)
check(
"a rollback is released exactly when the tables say rollback, not when the model does",
sorted(gate_ok) == sorted(wanted),
f"{len(gate_ok)}/{len(wanted)}",
)
agree_severity = sum(
1 for i, p in parsed.items() if p.get("severity") == wanted[i]["expected"]["severity"]
)
agree_action = sum(
1 for i, p in parsed.items() if p.get("action") == wanted[i]["expected"]["action"]
)
check(
"the model produced a readable proposal for most incidents",
len(parsed) >= len(wanted) - 2,
f"{len(parsed)}/{len(wanted)} parsed",
)
# A live run: a rollback incident still stops at the human gate with the model node present.
admin.workflows.update(imported.workflow_id, status="active")
published = admin.workflows.versions.publish(version.version_id)
rollback_case = wanted["IN01"]
queued = admin.workflows.runs.submit(
workflow_version_id=published.version_id,
input=json.dumps(rollback_case["input"]),
idempotency_key=f"{suffix}-variant-IN01",
)
paused = wait_settled(admin, queued.workflow_run_id)
check(
"through the queue the rollback still pauses at the approval gate",
paused.status == "waiting_approval" and node_path(paused)[-1] == APPROVAL_NODE,
paused.status,
)
admin.workflows.runs.cancel(paused.workflow_run_id)
return {
"incidents": len(wanted),
"verdicts_equal_tables": len(verdict_ok),
"proposals_parsed": len(parsed),
"model_agrees_severity": agree_severity,
"model_agrees_action": agree_action,
"model_disagreements": sorted(
i
for i, p in parsed.items()
if p.get("action") != wanted[i]["expected"]["action"]
or p.get("severity") != wanted[i]["expected"]["severity"]
),
}
def cleanup(caliber: CaliberClient) -> None:
"""Archive the projects, workflows and test sets this lab created."""
for project in caliber.projects.list():
if project.name.startswith(NAME_PREFIX):
caliber.projects.archive(project.project_id)
for workflow in caliber.workflows.list():
if workflow.name.startswith(NAME_PREFIX) and workflow.status != "archived":
caliber.workflows.update(workflow.workflow_id, status="archived")
for dataset in caliber.eval_datasets.list():
if dataset.name.startswith(NAME_PREFIX) and dataset.status != "archived":
caliber.eval_datasets.update(dataset.dataset_id, status="archived")
# The judges the real-provider tier created ("<judge name>-<suffix>").
for judge in caliber.judges.list():
if (
judge.name.startswith("StakeholderUpdateHonesty-")
and getattr(judge, "status", "active") != "archived"
):
caliber.judges.update(judge.judge_id, status="archived")
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
parser.add_argument("--cleanup", action="store_true", help="archive what earlier runs created")
parser.add_argument("--suffix", help="name suffix (default: a timestamp)")
parser.add_argument(
"--model-variant",
action="store_true",
help="also run the optional model-based variant (real provider only)",
)
args = parser.parse_args(argv)
base_url = os.environ["CALIBER_BASE_URL"]
password = os.environ.get("COOKBOOK_08_PASSWORD", DEFAULT_PASSWORD)
opened: list[CaliberClient] = []
def project_client(user_id: str, project_id: str) -> CaliberClient:
if user_id in (APPROVER_USER, MEMBER_USER):
token = sign_in(base_url, user_id, password)
else:
token = os.environ["CALIBER_TOKEN"]
client = CaliberClient(base_url, token=token, project=project_id, timeout=REQUEST_TIMEOUT)
opened.append(client)
return client
with env_client(timeout=REQUEST_TIMEOUT) as caliber:
try:
if args.cleanup:
cleanup(caliber)
return 0
ensure_accounts(caliber, password)
result = run(
caliber,
project_client=project_client,
suffix=args.suffix,
model_variant=args.model_variant,
)
except (LabVerificationError, SetupError) as exc:
print(f"\nVERIFICATION FAILED: {exc}", file=sys.stderr)
return 1
finally:
for client in opened:
client.close()
print(json.dumps(result, indent=2, sort_keys=True, default=str))
return 0
if __name__ == "__main__":
sys.exit(main())sdk/caliber-sdk/examples/cookbooks/cookbook_08_incident_response_copilot.py — executed by the SDK example test suite.Cookbook 09 — Self-Healing Workflows
Import the lab's own refund-intake workflow (it does not install the Cookbooks starter), run 35 tickets through version 1 and assert that exactly the documented 24 fail (17 at validate, 3 at check_reference, 4 at decide), read the debugger evidence and a same-way-failing retry, show what propose-patch can and cannot do for a code node, then write the patch as version 2, rerun all 35 (none fails, the 11 that worked are byte-identical), and exercise the staging alias, a rollback, and the prod refusal. It needs an admin-scoped SDK token, the lab's stand-in account service (assets/upstream/account_service.py, port 8780, not a real system) and a server started with CALIBER_EGRESS_ALLOWED_HOSTS=127.0.0.1; it needs no model and no feature flag. It uses only typed client.workflows calls (no client.raw); --cleanup deletes the workflow it created.
SDK surfaces: workflows
- Import
ticket-intake.v1.workflow.yamlasrefund-intakeand publish version 1. - Run the 35 tickets of
failing-inputs.jsonlthrough version 1 and check that exactly the documented tickets fail, at the documented node, with the documented error. - Read the debugger evidence for one failing run of each kind (the
ERRORspan in the trace, theworkflow.run.failedevent, no checkpoint), then retry one and confirm it fails at the same node as attempt 2 of 2 with a two-attempt lineage. - Ask
propose-patchfor a fix: it returns a generic prompt suggestion with no graph change for the timed-out node, and a guardrail patch aimed at a code node is refused with a 400. - Write the patch (three node bodies) as version 2 of the same workflow, validate and publish it, and rerun all 35 tickets: none fails and the 11 that already worked produce identical output.
- Promote version 1 then version 2 to
staging, run through the alias, roll the alias back and see the same ticket fail again, and confirmprodrefuses a version with no deploy gate (400).
"""Cookbook 09: find why a workflow fails in production, patch it, prove the patch, roll it back.
Runs the whole lab through the SDK against a live server and exits 0 only when every check below
holds. It is the API half of the lab README (docs-site/cookbooks/09-workflow-debugger-self-healing-
lab/README.md) and prints the same values the README tells you to expect.
export CALIBER_BASE_URL=http://127.0.0.1:5001 CALIBER_TOKEN=calpat_...
PYTHONPATH=sdk/caliber-sdk python \
sdk/caliber-sdk/examples/cookbooks/cookbook_09_self_healing_workflows.py
The server must be able to call the lab's stand-in account service (``assets/upstream/
account_service.py``, port 8780): start it, and start CALIBER with ``CALIBER_EGRESS_ALLOWED_HOSTS=
127.0.0.1``. The workflow runs on the shipped alpha runtime; nothing here needs a model.
What it does, in order:
1. Imports ``assets/workflow/ticket-intake.v1.workflow.yaml`` (``refund-intake``) and publishes it.
2. Runs the 35 tickets in ``assets/dataset/failing-inputs.jsonl`` through version 1 and checks that
exactly the documented ones fail, at the documented node, with the documented error.
3. Reads the debugger evidence for one failing run of each kind: the error span in the trace, the
run's events and checkpoints, and the retry lineage after a retry that fails the same way.
4. Asks ``propose-patch`` for a fix, and shows what it can and cannot do for a code node.
5. Writes the patch (three node bodies) as version 2 of the same workflow, validates and
publishes it.
6. Reruns all 35 tickets on version 2: none fails, and the 11 that already worked produce
byte-identical output (the regression slice).
7. Promotes version 1, then version 2, to the ``staging`` alias, runs through the alias, rolls the
alias back, and shows that ``prod`` refuses a version with no deploy gate.
``--cleanup`` deletes the workflow the run created when it succeeds.
"""
from __future__ import annotations
import json
import os
import re
import sys
import time
from collections import Counter
from pathlib import Path
from typing import Any
from caliber_sdk import CaliberClient
from caliber_sdk.errors import CaliberAPIError
from examples.cookbooks._helpers import env_client
ASSETS = Path(
os.environ.get(
"COOKBOOK_09_ASSETS",
Path(__file__).resolve().parents[4]
/ "docs-site/cookbooks/09-workflow-debugger-self-healing-lab/assets",
)
)
#: Nodes whose code the patch replaces; ``assets/workflow/patch/<node>.py`` is each node's new body.
PATCHED_NODES = ("validate", "check_reference", "decide")
#: What the dataset must contain, and what version 1 must do with it (quoted in the README).
EXPECTED_V1_FAILURES = {"validate": 17, "check_reference": 3, "decide": 4}
RUN_TIMEOUT_SECONDS = 180.0
class VerificationError(AssertionError):
"""A documented outcome did not hold; the message says which."""
def check(condition: bool, message: str) -> None:
if not condition:
raise VerificationError(message)
def load_rows(assets: Path = ASSETS) -> list[dict[str, Any]]:
path = assets / "dataset/failing-inputs.jsonl"
return [
json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()
]
def failing_node(error: str | None) -> str | None:
"""The node named in a run's error summary (``python_code node 'validate' failed: ...``)."""
match = re.search(r"node '([a-z_]+)'", error or "")
return match.group(1) if match else None
def run_all(caliber: CaliberClient, rows: list[dict[str, Any]], **target: str) -> dict[str, Any]:
"""Submit every row to ``target`` (a version id, or workflow id and alias); wait for each."""
submitted = {
row["id"]: caliber.workflows.runs.submit(input=row["input"]["payload"], **target)
for row in rows
}
return {
row_id: caliber.workflows.runs.wait(
run.workflow_run_id, timeout=RUN_TIMEOUT_SECONDS, raise_on_failure=False
)
for row_id, run in submitted.items()
}
def output_of(run: Any) -> dict[str, Any]:
summary = run.extra.get("summary") or {}
output: dict[str, Any] = json.loads(summary.get("output") or "{}")
return output
def verify_version_1(rows: list[dict[str, Any]], runs: dict[str, Any]) -> Counter[str]:
failed_at: Counter[str] = Counter()
for row in rows:
expected, run = row["expected"], runs[row["id"]]
if expected["v1_status"] == "completed":
check(run.status == "completed", f"{row['id']}: v1 should complete, got {run.status}")
out = output_of(run)
check(
(out["decision"], out["reason_code"])
== (expected["decision"], expected["reason_code"]),
f"{row['id']}: v1 decided {out}, expected {expected['decision']}",
)
continue
error = run.extra.get("error_summary") or ""
check(run.status == "failed", f"{row['id']}: v1 should fail, got {run.status}")
check(
failing_node(error) == expected["v1_failing_node"],
f"{row['id']}: failed at {failing_node(error)}, expected {expected['v1_failing_node']}",
)
check(expected["v1_error_contains"] in error, f"{row['id']}: unexpected error {error!r}")
failed_at[expected["v1_failing_node"]] += 1
check(dict(failed_at) == EXPECTED_V1_FAILURES, f"v1 failures by node: {dict(failed_at)}")
return failed_at
def verify_version_2(rows: list[dict[str, Any]], runs: dict[str, Any]) -> Counter[str]:
decisions: Counter[str] = Counter()
for row in rows:
expected, run = row["expected"], runs[row["id"]]
check(
run.status == "completed",
f"{row['id']}: v2 should complete, got {run.status}: {run.extra.get('error_summary')}",
)
out = output_of(run)
check(
(out["decision"], out["reason_code"])
== (expected["decision"], expected["reason_code"]),
f"{row['id']}: v2 decided {out}, expected "
f"{expected['decision']}/{expected['reason_code']}",
)
if "upstream_status" in expected:
check(out.get("upstream_status") == expected["upstream_status"], f"{row['id']}: {out}")
if "v2_errors_contain" in expected:
check(
any(expected["v2_errors_contain"] in e for e in out.get("errors", [])),
f"{row['id']}: rejection reasons {out.get('errors')}",
)
decisions[out["decision"]] += 1
return decisions
def debugger_evidence(caliber: CaliberClient, run: Any, node: str) -> dict[str, Any]:
"""What the run debugger shows for a failed run: where it stopped, and what it recorded."""
trace = caliber.workflows.runs.trace(run.workflow_run_id)
error_spans = [s["name"] for s in trace["spans"] if s.get("status") == "ERROR"]
events = caliber.workflows.runs.events(run.workflow_run_id)
failed = [e for e in events if e["event_type"] == "workflow.run.failed"]
steps = [(s["node_id"], s["status"]) for s in (run.extra["summary"].get("steps") or [])]
checkpoints = caliber.workflows.runs.checkpoints(run.workflow_run_id)
check(f"node.{node}" in error_spans, f"{run.workflow_run_id}: error spans {error_spans}")
check(bool(failed), "no workflow.run.failed event recorded")
check(checkpoints == [], f"a node failure should leave no checkpoint, got {checkpoints}")
return {
"run_id": run.workflow_run_id,
"error_spans": error_spans,
"completed_steps": [name for name, status in steps if status == "ok"],
"checkpoints": len(checkpoints),
}
def retry_fails_the_same_way(caliber: CaliberClient, run: Any, node: str) -> dict[str, Any]:
retried = caliber.workflows.runs.retry(run.workflow_run_id, reason="retry the same input")
again = caliber.workflows.runs.wait(
retried["workflow_run_id"], timeout=RUN_TIMEOUT_SECONDS, raise_on_failure=False
)
lineage = caliber.workflows.runs.lineage(again.workflow_run_id)
check(again.status == "failed", f"retry of a code fault should fail again, got {again.status}")
check(failing_node(again.extra.get("error_summary")) == node, "retry failed at another node")
check(again.extra.get("attempt_number") == 2, "the retry should be attempt 2")
check(lineage["total_attempts"] == 2, f"lineage: {lineage['total_attempts']} attempts")
return {"retry_run_id": again.workflow_run_id, "status": again.status, "attempts": 2}
def propose_patch_shows_its_limits(caliber: CaliberClient, version_id: str) -> dict[str, Any]:
patch = caliber.workflows.versions.propose_patch(
version_id,
evidence={
"node_id": "check_reference",
"root_cause": "check_reference timed out after 2.0s",
},
)
check(patch["patch_kind"] == "prompt", f"unexpected patch kind {patch['patch_kind']}")
check(patch["semantic_ops"] == [], "propose-patch should have no graph change for a code node")
refused = None
try:
caliber.workflows.versions.propose_patch(
version_id, evidence={"category": "guardrail", "node_id": "check_reference"}
)
except CaliberAPIError as exc:
refused = exc.status_code
check(refused == 400, f"a guardrail patch aimed at a code node should be a 400, got {refused}")
return {"patch_id": patch["patch_id"], "patch_kind": patch["patch_kind"], "refused": refused}
def write_version_2(
caliber: CaliberClient, workflow_id: str, version_1_id: str, assets: Path
) -> Any:
manifest = caliber.workflows.versions.get(version_1_id).manifest
for node in PATCHED_NODES:
manifest["nodes"][node]["code"] = (assets / f"workflow/patch/{node}.py").read_text()
version_2 = caliber.workflows.versions.create(workflow_id, manifest)
report = caliber.workflows.versions.validate(version_2.version_id)
check(report["valid"] is True, f"version 2 does not validate: {report}")
return caliber.workflows.versions.publish(version_2.version_id)
def exercise_the_alias(
caliber: CaliberClient, workflow_id: str, version_1: str, version_2: str, failing_payload: str
) -> dict[str, Any]:
"""Promote, run through the alias, roll back; and show that ``prod`` is refused."""
wf = caliber.workflows
wf.promote_deployment(workflow_id, "staging", version_id=version_1)
wf.promote_deployment(workflow_id, "staging", version_id=version_2)
serving = {d["alias"]: d["version_id"] for d in wf.deployments(workflow_id)}
check(serving == {"staging": version_2}, f"staging should serve version 2, got {serving}")
fixed = caliber.workflows.runs.wait(
wf.runs.submit(
workflow_id=workflow_id, alias="staging", input=failing_payload
).workflow_run_id,
timeout=RUN_TIMEOUT_SECONDS,
raise_on_failure=False,
)
check(
fixed.status == "completed",
f"through staging@v2 the ticket should complete: {fixed.status}",
)
wf.rollback_deployment(workflow_id, "staging")
serving = {d["alias"]: d["version_id"] for d in wf.deployments(workflow_id)}
check(serving == {"staging": version_1}, f"rollback should restore version 1, got {serving}")
broken = caliber.workflows.runs.wait(
wf.runs.submit(
workflow_id=workflow_id, alias="staging", input=failing_payload
).workflow_run_id,
timeout=RUN_TIMEOUT_SECONDS,
raise_on_failure=False,
)
check(
broken.status == "failed",
f"after the rollback the ticket should fail again: {broken.status}",
)
refusal: tuple[int, str] | None = None
try:
wf.promote_deployment(workflow_id, "prod", version_id=version_2)
except CaliberAPIError as exc:
refusal = (exc.status_code, str(exc))
if refusal is None or refusal[0] != 400 or "requires a deploy gate" not in refusal[1]:
raise VerificationError(f"prod should refuse a version with no deploy gate, got {refusal}")
return {"through_alias": [fixed.status, broken.status], "prod_refused": refusal[0]}
def run(
caliber: CaliberClient,
*,
assets: Path = ASSETS,
suffix: str | None = None,
cleanup: bool = False,
) -> dict[str, Any]:
suffix = suffix or str(int(time.time()))
rows = load_rows(assets)
check(len(rows) == 35, f"expected 35 tickets, found {len(rows)}")
# 1. import and publish version 1
manifest_yaml = (assets / "workflow/ticket-intake.v1.workflow.yaml").read_text()
workflow = caliber.workflows.import_workflow(
manifest_yaml=manifest_yaml, name=f"refund-intake-{suffix}"
)
version_1 = caliber.workflows.versions.publish(
caliber.workflows.versions.list(workflow.workflow_id)[0].version_id
)
# 2. version 1 against the dataset
runs_v1 = run_all(caliber, rows, workflow_version_id=version_1.version_id)
failed_at = verify_version_1(rows, runs_v1)
# 3. the debugger's evidence, and a retry
evidence = {}
for node in ("validate", "check_reference", "decide"):
sample = next(r for r in rows if r["expected"]["v1_failing_node"] == node)
evidence[node] = debugger_evidence(caliber, runs_v1[sample["id"]], node)
retry = retry_fails_the_same_way(caliber, runs_v1["F29"], "check_reference")
# 4. propose-patch
patch = propose_patch_shows_its_limits(caliber, version_1.version_id)
# 5. version 2
version_2 = write_version_2(caliber, workflow.workflow_id, version_1.version_id, assets)
# 6. version 2 against the dataset, and the regression slice
runs_v2 = run_all(caliber, rows, workflow_version_id=version_2.version_id)
decisions = verify_version_2(rows, runs_v2)
slice_ids = [r["id"] for r in rows if r["expected"]["v1_status"] == "completed"]
for row_id in slice_ids:
check(
runs_v1[row_id].extra["summary"]["output"]
== runs_v2[row_id].extra["summary"]["output"],
f"{row_id}: the patch changed the output of a ticket that already worked",
)
# 7. the alias
f12 = next(r for r in rows if r["id"] == "F12")["input"]["payload"]
alias = exercise_the_alias(
caliber, workflow.workflow_id, version_1.version_id, version_2.version_id, f12
)
if cleanup:
caliber.workflows.delete(workflow.workflow_id)
return {
"workflow_id": workflow.workflow_id,
"version_1": version_1.version_id,
"version_2": version_2.version_id,
"tickets": len(rows),
"v1": {"completed": len(rows) - sum(failed_at.values()), "failed": sum(failed_at.values())},
"v1_failed_at": dict(sorted(failed_at.items())),
"debugger": evidence,
"retry": retry,
"propose_patch": patch,
"v2": {"completed": len(rows), "failed": 0, "decisions": dict(sorted(decisions.items()))},
"regression_slice": len(slice_ids),
"alias": alias,
}
def main() -> None:
with env_client() as caliber:
result = run(caliber, cleanup="--cleanup" in sys.argv)
print(json.dumps(result, indent=2, sort_keys=True))
if __name__ == "__main__":
main()sdk/caliber-sdk/examples/cookbooks/cookbook_09_self_healing_workflows.py — executed by the SDK example test suite.Cookbook 10 — Trustworthy Evaluation
Load a 50-row test set, create a FaithfulnessJudge and a deliberately weak LenientJudge (a template with an unsupported variable is refused with a 400), seed 50 traces, have them reviewed in a queue with the human labels from the dataset, import those labels, and compute the judge's agreement, Cohen's kappa and confusion counts, recomputing each independently and comparing it with the server's numbers before certifying or rejecting the judge on the lab's thresholds (agreement >= 0.80, kappa >= 0.60, at least 30 rows). It runs in two modes, chosen by asking the server: with a model behind it (a real provider or the lab's stand-in model) every step runs, and on the default simulated stack (CALIBER_LLM_PROVIDER=fake) the Evaluations and the judge are refused (400, 'real LLM provider') and the script verifies those refusals plus the model-free steps and a calibration job whose canned score is marked simulated. It needs an admin-scoped SDK token, CALIBER_FEATURE_COOKBOOKS=true, and mlflow plus MLFLOW_TRACKING_URI, because the lab's seed_traces.py writes the traces with MLflow directly, not through the SDK. It does not use client.raw; --expect-stand-in pins the stand-in model's exact numbers and --cleanup archives what it created.
SDK surfaces: cookbooks, datasets, judges, evaluations, review_queues, prompts, jobs
- Read the recipe through
client.cookbooks, then create the 50-row test set (dataset version 51) and read it back. - Create
FaithfulnessJudgeandLenientJudge, show a template using{{ evidence }}refused with a 400 that names it, and show an evaluation of an empty test set refused. - Score a baseline and a candidate with the deterministic scorers and the judge and read the per-row results (with a model); on the simulated stack, verify the refusal the product gives instead.
- Seed 50 traces, create the review queue, enqueue every trace, submit the human answers, and import the labels (50 imported, none skipped).
- Compute judge/human alignment: recompute agreement, Cohen's kappa and confusion counts independently and compare, certify or reject each judge on the lab's rule, and show that five rows alone are not certifiable (with a model); with no model every row errors and a calibration job reports a simulated score.
- Feed the nine disagreements back into the test set as hard cases (dataset version 60, with a model).
"""Cookbook 10: certify (or reject) an LLM judge by how well it agrees with human reviewers.
Runs the whole lab through the SDK against a live server and exits 0 only when every check below
holds. It is the API half of the lab README (docs-site/cookbooks/10-judge-certification-human-
review-lab/README.md) and prints the same values the README tells you to expect.
export CALIBER_BASE_URL=http://127.0.0.1:5001 CALIBER_TOKEN=calpat_...
export MLFLOW_TRACKING_URI=http://127.0.0.1:5000 # where CALIBER's traces live
PYTHONPATH=sdk/caliber-sdk python \
sdk/caliber-sdk/examples/cookbooks/cookbook_10_trustworthy_evaluation.py
What it does, in order:
1. Loads the 50-row test set from ``assets/dataset/aggregated-outputs.jsonl`` and checks its size.
2. Creates the ``FaithfulnessJudge`` from ``assets/judges/faithfulness-judge.judge.json``, and shows
a judge with an unsupported template variable being refused.
3. Runs baseline and candidate Evaluations with the deterministic scorers and the judge, and reads
the per-row results back. An evaluation of an empty test set is refused.
4. Writes the 50 recorded outputs as traces, has them "reviewed" (the human labels in the dataset
file), then imports those labels and checks the judge against them (Judges > Human alignment).
5. Recomputes agreement, Cohen's kappa and the confusion counts independently from the per-row
verdicts and compares them with what the server reported, then certifies or rejects the judge on
the lab's thresholds (agreement >= 0.80 AND kappa >= 0.60 over >= 30 labelled rows).
6. Feeds every disagreement back into the test set as a hard case.
Two modes, chosen by asking the server. On a stack with a model behind it (a real provider, or the
stand-in model in the lab's ``assets/stand-in-model``) every step runs. On the default simulated
stack (``CALIBER_LLM_PROVIDER=fake``) Evaluations and the judge cannot run. The script then verifies
the refusals the product gives instead, plus everything that needs no model: the test set, the
review queue and label import, and a calibration job whose canned score is marked simulated.
``--expect-stand-in`` additionally pins the exact numbers the stand-in model produces, and
``--cleanup`` archives what the run created when it succeeds.
"""
from __future__ import annotations
import importlib.util
import json
import os
import sys
import uuid
from collections import Counter
from pathlib import Path
from typing import Any, TypeVar
from caliber_sdk import CaliberClient
from caliber_sdk.errors import CaliberAPIError
from examples.cookbooks._helpers import env_client, get_recipe
ASSETS = Path(
os.environ.get(
"COOKBOOK_10_ASSETS",
Path(__file__).resolve().parents[4]
/ "docs-site/cookbooks/10-judge-certification-human-review-lab/assets",
)
)
#: The lab's certification policy. A judge is certified only when it clears all three.
AGREEMENT_MIN = 0.80
KAPPA_MIN = 0.60
MIN_LABELLED_ROWS = 30
#: The numbers the lab's stand-in model produces (``--expect-stand-in``). They are properties of its
#: mechanical rule on this dataset, not of any real judge: see the README.
STAND_IN_STRICT = {
"agreement": 0.82,
"kappa": 0.6365,
"confusion": {"true_pos": 23, "false_pos": 5, "true_neg": 18, "false_neg": 4},
}
STAND_IN_LENIENT = {
"agreement": 0.58,
"kappa": 0.0933,
"confusion": {"true_pos": 27, "false_pos": 21, "true_neg": 2, "false_neg": 0},
}
STAND_IN_LEAK = {"agreement": 0.66, "kappa": 0.2952}
STAND_IN_RUNS = {
"baseline": {"non_empty": 1.0, "contains_expected": 0.0, "judge": 1.0},
"candidate": {"non_empty": 1.0, "contains_expected": 0.66, "judge": 0.56},
}
#: The real-provider tier. Nothing about a real model is pinned; these are the invariants that must
#: hold for any model that can do the job (the README records the values one run produced).
#: A candidate that is *given* the evidence must state the expected fact more often than a baseline
#: that sees only the ticket, by at least this much.
REAL_CANDIDATE_LIFT_MIN = 0.10
#: The prompt the real-model candidate runs: the stored prompt plus a slot for the evidence. The
#: stand-in model replays recorded replies and ignores it.
EVIDENCE_SLOT = "\n\nEvidence you may use:\n{{ evidence }}\n"
#: Fields of a row's ``expected`` that are the grader's, not facts a reply could draw on.
NOT_EVIDENCE = frozenset({"expected", "decision"})
SCORERS = ["non_empty", "contains_expected"]
EXAMPLES_EXPECTED = 50
DISAGREEMENTS_EXPECTED = 9
class VerificationError(AssertionError):
"""A documented outcome did not hold."""
def check(condition: bool, message: str) -> None:
if not condition:
raise VerificationError(message)
_T = TypeVar("_T")
def present(value: _T | None, message: str) -> _T:
"""``value`` itself, so a field the server must return is narrowed from ``None`` for the type
checker; a missing one is a failed verification like any other."""
if value is None:
raise VerificationError(message)
return value
# --------------------------------------------------------------------------- #
# The metrics, recomputed from scratch (the server's numbers are checked against these)
# --------------------------------------------------------------------------- #
def agreement(judge: list[bool], human: list[bool]) -> float:
return sum(a == b for a, b in zip(judge, human, strict=True)) / len(judge)
def cohen_kappa(judge: list[bool], human: list[bool]) -> float:
n = len(judge)
observed = agreement(judge, human)
expected = sum((judge.count(label) / n) * (human.count(label) / n) for label in (True, False))
return 1.0 if expected >= 1.0 else (observed - expected) / (1 - expected)
def confusion(judge: list[bool], human: list[bool]) -> dict[str, int]:
pairs = Counter(zip(judge, human, strict=True))
return {
"true_pos": pairs[(True, True)],
"false_pos": pairs[(True, False)],
"true_neg": pairs[(False, False)],
"false_neg": pairs[(False, True)],
}
def decide(scored: int, n: int, agreement_rate: float, kappa: float) -> str:
"""The lab's certification rule."""
if scored != n or scored < MIN_LABELLED_ROWS:
return "NOT_CERTIFIABLE"
return "CERTIFIED" if agreement_rate >= AGREEMENT_MIN and kappa >= KAPPA_MIN else "REJECTED"
# --------------------------------------------------------------------------- #
# Dataset files
# --------------------------------------------------------------------------- #
def load_rows(assets: Path) -> list[dict[str, Any]]:
path = assets / "dataset" / "aggregated-outputs.jsonl"
return [
json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()
]
def evidence_text(row: dict[str, Any]) -> str:
"""The facts behind a row (what a person would have in front of them), one per line."""
return "\n".join(
f"{key}: {value}"
for key, value in row["expected"].items()
if key not in NOT_EVIDENCE and value is not None
)
def output_text(row: dict[str, Any]) -> str:
return row["outputs"].get("reply") or row["outputs"].get("summary") or ""
def seed_traces(assets: Path) -> dict[str, str]:
"""Write the 50 recorded outputs as traces (needs ``mlflow`` and ``MLFLOW_TRACKING_URI``)."""
spec = importlib.util.spec_from_file_location(
"cookbook10_seed_traces", assets / "seed_traces.py"
)
check(spec is not None and spec.loader is not None, "seed_traces.py not found")
assert spec is not None and spec.loader is not None # narrowed for the type checker
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
seeded: dict[str, str] = module.seed(assets / "dataset" / "aggregated-outputs.jsonl")
return seeded
def refused(call: Any) -> CaliberAPIError:
"""Run ``call`` and return the error the server refused it with."""
try:
call()
except CaliberAPIError as error:
return error
raise VerificationError("the server accepted a request it should have refused")
# --------------------------------------------------------------------------- #
# The lab
# --------------------------------------------------------------------------- #
def run(
caliber: CaliberClient,
*,
assets: Path = ASSETS,
trace_ids: dict[str, str] | None = None,
suffix: str | None = None,
expect_stand_in: bool = False,
cleanup: bool = False,
) -> dict[str, Any]:
suffix = suffix or uuid.uuid4().hex[:6]
rows = load_rows(assets)
check(
len(rows) == EXAMPLES_EXPECTED,
f"expected {EXAMPLES_EXPECTED} dataset rows, got {len(rows)}",
)
result: dict[str, Any] = {"suffix": suffix}
created: dict[str, list[str]] = {"datasets": [], "judges": [], "queues": [], "prompts": []}
recipe = get_recipe(caliber, "10")
result["cookbook"] = {"id": recipe.id, "title": recipe.title, "steps": len(recipe.steps)}
# ---- 1. The test set ------------------------------------------------------------------
owner = caliber.me.get().user_id
dataset = caliber.eval_datasets.create(
f"judge-certification-set-{suffix}",
owner=owner,
description="Support replies (SCN-07) and incident summaries (SCN-08) to certify on.",
)
created["datasets"].append(dataset.dataset_id)
for row in rows:
caliber.eval_datasets.add_example(
dataset.dataset_id, input=row["input"], expected=row["expected"], tags=row["tags"]
)
stored = caliber.eval_datasets.get(dataset.dataset_id)
check(
stored.version == len(rows) + 1,
f"dataset version {stored.version}, expected {len(rows) + 1}",
)
check(
len(caliber.eval_datasets.examples(dataset.dataset_id)) == len(rows),
"the test set does not hold every row",
)
result["dataset"] = {"id": dataset.dataset_id, "examples": len(rows), "version": stored.version}
# ---- 2. The judge, and a template it refuses ------------------------------------------
spec = json.loads((assets / "judges" / "faithfulness-judge.judge.json").read_text("utf-8"))
judge = caliber.judges.create(
f"FaithfulnessJudge-{suffix}",
instructions=spec["instructions"],
feedback_value_type=spec["feedback_value_type"],
)
lenient = caliber.judges.create(
f"LenientJudge-{suffix}",
instructions=(
"Return true when {{ outputs }} is a complete, well-formed answer to {{ inputs }}. "
"Return false only if it is empty or cut off."
),
feedback_value_type="bool",
)
created["judges"] += [judge.judge_id, lenient.judge_id]
bad_template = refused(
lambda: caliber.judges.create(
f"BadTemplateJudge-{suffix}",
instructions="Return true when {{ outputs }} is faithful to {{ evidence }}.",
feedback_value_type="bool",
)
)
check(bad_template.status_code == 400, "an unsupported template variable was not a 400")
check("evidence" in str(bad_template), "the refusal does not name the unsupported variable")
result["judge"] = {"id": judge.judge_id, "lenient_id": lenient.judge_id}
result["invalid_template"] = {"status": bad_template.status_code, "variable": "evidence"}
# ---- 3. Evaluations --------------------------------------------------------------------
empty = caliber.eval_datasets.create(f"empty-set-{suffix}", owner=owner)
created["datasets"].append(empty.dataset_id)
empty_error = refused(
lambda: caliber.evaluations.create(empty.dataset_id, scorers=["non_empty"])
)
check(empty_error.status_code == 400, "an empty test set was not a 400")
check("no examples" in str(empty_error), "the empty-set refusal does not say why")
result["empty_dataset_evaluation"] = {"status": empty_error.status_code}
judge_scorer = f"Judge.{judge.judge_id}"
modelled = True
try:
baseline = caliber.evaluations.create(
dataset.dataset_id, scorers=[*SCORERS, judge_scorer], label=f"baseline {suffix}"
)
except CaliberAPIError as error:
check(
error.status_code == 400 and "real LLM provider" in str(error),
f"the first evaluation failed for an unexpected reason: {error}",
)
modelled = False
result["evaluation_refused"] = {"status": error.status_code, "detail": error.detail}
#: A model other than the lab's stand-in: nothing is pinned, only invariants are asserted.
real_model = modelled and not expect_stand_in
result["mode"] = ("real model" if real_model else "model") if modelled else "simulated"
instructions = (
"You answer support tickets and incident alerts using ONLY the evidence you are given. "
"State what the evidence says and nothing more; if it does not cover the question, "
"say so and escalate to a person."
)
prompt = caliber.prompts.create(
f"grounded-reply-{suffix}", instructions + (EVIDENCE_SLOT if real_model else "")
)
created["prompts"].append(prompt["name"])
if modelled:
candidate_set = dataset
if real_model:
# A live model can only use facts it is shown, and the test set's evidence is the
# grader's (``expected``). So the candidate runs on a copy whose rows also carry the
# evidence for the prompt's ``{{ evidence }}`` slot; the baseline sees the ticket alone.
candidate_set = caliber.eval_datasets.create(
f"judge-certification-grounded-{suffix}",
owner=owner,
description="The same 50 rows with their evidence in the input (real-model tier).",
)
created["datasets"].append(candidate_set.dataset_id)
for row in rows:
caliber.eval_datasets.add_example(
candidate_set.dataset_id,
input={**row["input"], "evidence": evidence_text(row)},
expected=row["expected"],
tags=row["tags"],
)
candidate = caliber.evaluations.create(
candidate_set.dataset_id,
scorers=[*SCORERS, judge_scorer],
label=f"candidate {suffix}",
predict_target="prompt",
subject_ref=f"{prompt['name']}@{prompt['version']}",
)
result["evaluations"] = _read_runs(
caliber, baseline, candidate, judge_scorer, expect_stand_in, real_model
)
# ---- 4. Human review and label import ---------------------------------------------------
trace_ids = trace_ids or seed_traces(assets)
check(set(trace_ids) == {row["id"] for row in rows}, "need one trace per dataset row")
queue = caliber.review_queues.create(
f"faithfulness-certification-{suffix}",
questions=json.loads((assets / "review" / "review-questions.json").read_text("utf-8"))[
"questions"
],
)
created["queues"].append(queue.queue_id)
items = caliber.review_queues.enqueue(
queue.queue_id, trace_ids=[trace_ids[r["id"]] for r in rows]
)
item_for_trace = {item["trace_id"]: item["item_id"] for item in items}
check(len(item_for_trace) == len(rows), "the queue did not take every trace")
for row in rows:
answers: dict[str, Any] = {
"faithful": row["human_label"] == "pass",
"evidence": json.dumps(row["expected"], ensure_ascii=False),
}
caliber.review_queues.submit(
queue.queue_id, item_for_trace[trace_ids[row["id"]]], **answers
)
imported = caliber.review_queues.alignment_examples(queue.queue_id, question_key="faithful")
check(imported["skipped"] == [], f"label import skipped rows: {imported['skipped']}")
examples = imported["examples"]
check(len(examples) == len(rows), f"imported {len(examples)} labels, expected {len(rows)}")
row_for_trace = {trace_ids[row["id"]]: row for row in rows}
for example in examples: # the import carries the trace, the reply, the label and the evidence
row = row_for_trace[example["provenance"]["trace_id"]]
check(example["outputs"] == output_text(row), f"imported output differs for {row['id']}")
check(
example["label"] == (row["human_label"] == "pass"),
f"imported label differs for {row['id']}",
)
sendable = [
{key: example[key] for key in ("inputs", "outputs", "expectations", "label")}
for example in examples
]
result["review"] = {"queue_id": queue.queue_id, "labels_imported": len(examples)}
if modelled:
result["alignment"] = _certify(
caliber,
judge.judge_id,
lenient.judge_id,
sendable,
examples,
row_for_trace,
expect_stand_in,
real_model,
)
result["feedback"] = _feed_back(
caliber, dataset.dataset_id, result["alignment"], examples, row_for_trace, trace_ids
)
else:
result["alignment"] = _alignment_without_a_model(caliber, judge.judge_id, sendable)
result["calibration"] = _calibrate_on_canned_scores(
caliber, prompt["name"], dataset.dataset_id
)
result["result"] = "verified"
if cleanup:
_archive(caliber, created)
result["archived"] = {kind: len(ids) for kind, ids in created.items()}
return result
def _archive(caliber: CaliberClient, created: dict[str, list[str]]) -> None:
"""Archive what the run created (names stay reserved, so a rerun uses a new suffix)."""
for judge_id in created["judges"]:
caliber.judges.update(judge_id, status="archived")
for dataset_id in created["datasets"]:
caliber.eval_datasets.update(dataset_id, status="archived")
for queue_id in created["queues"]:
caliber.review_queues.update(queue_id, status="archived")
for name in created["prompts"]:
caliber.prompts.delete(name)
def _read_runs(
caliber: CaliberClient,
baseline: Any,
candidate: Any,
judge_scorer: str,
expect_stand_in: bool,
real_model: bool = False,
) -> dict[str, Any]:
out: dict[str, Any] = {}
for label, run in (("baseline", baseline), ("candidate", candidate)):
stored = caliber.evaluations.get(run.run_id)
check(
stored.status == "completed",
f"{label} run is {stored.status}"
+ (f": {stored.error_message}" if stored.error_message else ""),
)
check(
stored.n_examples == EXAMPLES_EXPECTED, f"{label} scored {stored.n_examples} examples"
)
rows = stored.results or []
check(len(rows) == EXAMPLES_EXPECTED, f"{label} stored {len(rows)} per-row results")
check(
all(
set(row["scores"]) == {*SCORERS, judge_scorer} and row["error"] is None
for row in rows
),
f"a {label} row is missing a score or carries an error",
)
out[label] = {
"run_id": run.run_id,
"overall": stored.overall_score,
"pass_rate": stored.pass_rate,
"non_empty": stored.aggregate["non_empty"],
"contains_expected": stored.aggregate["contains_expected"],
"judge": stored.aggregate[judge_scorer],
}
out["delta_overall"] = round(out["candidate"]["overall"] - out["baseline"]["overall"], 4)
if real_model:
lift = out["candidate"]["contains_expected"] - out["baseline"]["contains_expected"]
check(
lift >= REAL_CANDIDATE_LIFT_MIN,
f"the candidate, given the evidence, states the expected fact {lift:+.2f} more often "
f"than the baseline (needs at least {REAL_CANDIDATE_LIFT_MIN:+.2f})",
)
check(
all(
0.0 <= out[label][key] <= 1.0
for label in ("baseline", "candidate")
for key in ("non_empty", "contains_expected", "judge")
),
"a real-model score is outside 0..1",
)
if expect_stand_in:
for label, expected in STAND_IN_RUNS.items():
for scorer, value in expected.items():
check(
abs(out[label][scorer] - value) < 1e-9,
f"{label} {scorer} is {out[label][scorer]}, expected {value}",
)
return out
def _certify(
caliber: CaliberClient,
judge_id: str,
lenient_id: str,
sendable: list[dict[str, Any]],
examples: list[dict[str, Any]],
row_for_trace: dict[str, dict[str, Any]],
expect_stand_in: bool,
real_model: bool = False,
) -> dict[str, Any]:
out: dict[str, Any] = {}
for label, jid, pinned in (
("faithfulness", judge_id, STAND_IN_STRICT),
("lenient", lenient_id, STAND_IN_LENIENT),
):
report = caliber.judges.alignment(jid, examples=sendable)
check(
report.n == len(sendable) and report.scored == report.n,
f"{label}: judge errored on a row",
)
per = report.per_example
n = present(report.n, f"{label}: the report has no row count")
scored = present(report.scored, f"{label}: the report has no scored count")
agreement_rate = present(report.agreement_rate, f"{label}: the report has no agreement")
kappa = present(report.cohen_kappa, f"{label}: the report has no kappa")
judge_labels = [bool(r["judge_label"]) for r in per]
human_labels = [bool(r["human_label"]) for r in per]
# The server's numbers are arithmetic over the supplied labels; recompute them here.
check(
abs(agreement(judge_labels, human_labels) - agreement_rate) < 5e-5,
f"{label} agreement",
)
check(
abs(cohen_kappa(judge_labels, human_labels) - kappa) < 5e-5,
f"{label} kappa",
)
check(
confusion(judge_labels, human_labels) == report.confusion, f"{label} confusion counts"
)
disagreements = [
row_for_trace[examples[i]["provenance"]["trace_id"]]["id"]
for i, r in enumerate(per)
if not r["agree"]
]
out[label] = {
"n": report.n,
"scored": report.scored,
"agreement": report.agreement_rate,
"kappa": report.cohen_kappa,
"confusion": report.confusion,
"decision": decide(scored, n, agreement_rate, kappa),
"disagreements": disagreements,
}
if expect_stand_in:
check(
report.agreement_rate == pinned["agreement"],
f"{label} agreement {report.agreement_rate}",
)
check(report.cohen_kappa == pinned["kappa"], f"{label} kappa {report.cohen_kappa}")
check(report.confusion == pinned["confusion"], f"{label} confusion {report.confusion}")
if real_model:
# What must hold for any model that can do the job, whichever way it rules on the strict
# judge: a judge told to check every claim against the evidence agrees with people more than
# one told only to check the reply is well formed, and the weak judge is not certified.
strict, weak = out["faithfulness"], out["lenient"]
check(
strict["agreement"] > weak["agreement"],
f"the strict judge's agreement {strict['agreement']} is not above the lenient "
f"judge's {weak['agreement']}",
)
check(weak["decision"] != "CERTIFIED", "the deliberately weak judge was certified")
check(
strict["decision"] in {"CERTIFIED", "REJECTED"},
f"the strict judge was {strict['decision']}",
)
if expect_stand_in:
check(
out["faithfulness"]["decision"] == "CERTIFIED", "the strict judge should be certified"
)
check(out["lenient"]["decision"] == "REJECTED", "the lenient judge should be rejected")
check(
len(out["faithfulness"]["disagreements"]) == DISAGREEMENTS_EXPECTED,
"expected nine disagreements",
)
# Import labels hands the judge every OTHER answer on a queue item as {{ expectations }}. A
# reviewer's explanation that quotes the unsupported claim therefore becomes "evidence", and the
# judge starts agreeing with the claim it should be catching.
leaky = []
for example, send in zip(examples, sendable, strict=True):
row = row_for_trace[example["provenance"]["trace_id"]]
reason = (
{"unsupported_claims": row["human_label_reason"]}
if row["human_label"] == "fail"
else {}
)
leaky.append({**send, "expectations": {**send["expectations"], **reason}})
polluted = caliber.judges.alignment(judge_id, examples=leaky)
out["rationale_leak"] = {
"agreement": polluted.agreement_rate,
"kappa": polluted.cohen_kappa,
"confusion": polluted.confusion,
}
if expect_stand_in:
check(polluted.agreement_rate == STAND_IN_LEAK["agreement"], "rationale-leak agreement")
check(polluted.cohen_kappa == STAND_IN_LEAK["kappa"], "rationale-leak kappa")
# Too few labelled rows: the product still returns numbers, the lab's policy refuses them.
few = caliber.judges.alignment(judge_id, examples=sendable[:5])
few_scored = present(few.scored, "the five-row report has no scored count")
few_n = present(few.n, "the five-row report has no row count")
out["too_few_rows"] = {
"n": few.n,
"agreement": few.agreement_rate,
"kappa": few.cohen_kappa,
"decision": decide(few_scored, few_n, few.agreement_rate or 0.0, few.cohen_kappa or 0.0),
}
check(out["too_few_rows"]["decision"] == "NOT_CERTIFIABLE", "five rows must not be certifiable")
return out
def _feed_back(
caliber: CaliberClient,
dataset_id: str,
alignment: dict[str, Any],
examples: list[dict[str, Any]],
row_for_trace: dict[str, dict[str, Any]],
trace_ids: dict[str, str],
) -> dict[str, Any]:
"""Every disagreement becomes a permanent hard case in the test set."""
disagreements = alignment["faithfulness"]["disagreements"]
before = present(caliber.eval_datasets.get(dataset_id).version, "the dataset has no version")
for row_id in disagreements:
row = next(r for r in row_for_trace.values() if r["id"] == row_id)
caliber.eval_datasets.add_from_trace(
dataset_id,
trace_ids[row_id],
input=row["input"],
expected=row["expected"],
tags=[*row["tags"], "judge-disagreement"],
)
after = present(
caliber.eval_datasets.get(dataset_id).version, "the dataset has no version afterwards"
)
check(after == before + len(disagreements), f"dataset version {before} -> {after}")
return {"hard_cases_added": len(disagreements), "dataset_version": after}
def _alignment_without_a_model(
caliber: CaliberClient, judge_id: str, sendable: list[dict[str, Any]]
) -> dict[str, Any]:
"""With no model the judge cannot run: every row comes back as an error and is left out."""
report = caliber.judges.alignment(judge_id, examples=sendable)
check(report.n == len(sendable), "alignment did not echo the number of rows")
check(report.scored == 0, f"{report.scored} rows were scored without a model")
check(
all(r["judge_label"] is None and r["error"] for r in report.per_example),
"a row came back without an error",
)
return {
"n": report.n,
"scored": report.scored,
"agreement": report.agreement_rate,
"kappa": report.cohen_kappa,
"decision": decide(
present(report.scored, "the report has no scored count"),
present(report.n, "the report has no row count"),
report.agreement_rate or 0.0,
0.0,
),
"first_row_error": report.per_example[0]["error"],
}
def _calibrate_on_canned_scores(
caliber: CaliberClient, prompt_name: str, dataset_id: str
) -> dict[str, Any]:
"""The test set also feeds calibration; on the simulated stack its score is canned."""
run = caliber.prompts.create_calibration_run(
agent_id=prompt_name,
eval_dataset_id=dataset_id,
optimizer_type="MetaPrompt",
scorers=[{"name": "Correctness"}],
)
job = caliber.jobs.wait(run["job"]["job_id"], timeout=120)
check(job.status == "candidate_ready", f"calibration job ended {job.status}")
evidence = job.eval_results or {}
check(evidence.get("simulated") is True, "a canned score was not marked simulated")
check(
evidence.get("n_examples") == EXAMPLES_EXPECTED,
"calibration did not use the whole test set",
)
return {
"job_id": job.job_id,
"status": job.status,
"n_examples": evidence["n_examples"],
"dataset_version": evidence["eval_dataset_version"],
"provider": evidence.get("provider"),
"simulated": evidence["simulated"],
"gate_passed_on_a_canned_score": evidence["gate"]["passed"],
}
def main() -> None:
expect_stand_in = "--expect-stand-in" in sys.argv
cleanup = "--cleanup" in sys.argv
try:
# An Evaluation or alignment check is one request that makes a model call per row.
with env_client(timeout=1800.0) as caliber:
result = run(caliber, expect_stand_in=expect_stand_in, cleanup=cleanup)
except VerificationError as error:
print(f"FAILED: {error}", file=sys.stderr)
sys.exit(1)
print(json.dumps(result, indent=2, sort_keys=True))
if __name__ == "__main__":
main()sdk/caliber-sdk/examples/cookbooks/cookbook_10_trustworthy_evaluation.py — executed by the SDK example test suite.Cookbook 11 — Release Signoff Factory
Create a real prompt with two versions, create the 20 release candidates of release-candidates.jsonl as an operator and assert the server's weighted score, status and blockers against the dataset's independently worked figures (14 ready, 6 blocked), then exercise refusals, waivers, the Allure-compatible report job, go and no-go signoffs, final-once-signed behaviour, and the audit trail. It asserts that signing off deploys nothing (no alias moves; a separate prompt promote does), and that a candidate for a non-existent artifact is accepted because CALIBER records the reference without looking it up. It needs an admin-scoped SDK token, CALIBER_FEATURE_RELEASE_CANDIDATES=true, and CALIBER_OPERATOR_USERS listing lab11-operator next to admin; no model is involved and nothing is simulated. It creates the lab11-operator and lab11-viewer accounts and signs them in with plain httpx calls to mint their tokens (no client.raw); it does not call the cookbooks resource.
SDK surfaces: releases, prompts, auth, audit
- Create a
payments-assistantprompt with two versions and check that no alias points at either. - Create the 20 candidates as the operator and check each weighted score, status and blocker list against the dataset (14 ready, 6 blocked).
- Show what a candidate is refused for (zero weight, score above 1, a key with a space, no criteria, an unknown field, a viewer creating one) and that a candidate for a missing artifact is accepted.
- Record waivers (admin only; reason, expiry and criterion key validated) and show that a waiver clears a blocker but cannot make a low score ready (GO refused with 409), with a stale report snapshot hash before and after.
- Generate the report job, sign RC20 GO, RC19 NO-GO and RC18 GO as admin (an operator cannot), and show a signed candidate is final: re-evaluate, waiver and a second signoff all return 409.
- Show the signed GO deployed nothing (aliases, live board and timeline unchanged until a separate prompt promote), then read each action and its actor back from the audit log.
"""Cookbook 11: a release signoff record, from twenty candidates to one signed GO.
Runs the whole lab against a real CALIBER server and exits 0 only when every documented outcome was
observed:
* create the 20 candidates in ``release-candidates.jsonl`` and check the server's weighted score,
status and blockers against the expectations written independently in the dataset;
* the ways a candidate is refused (bad weights, scores, keys; no role) and the one thing that is
not checked (that the artifact exists);
* waivers: reason, expiry, who may record one, a waiver that clears a blocker, one that cannot make
a low score ready;
* the Allure-compatible report job, and why a report made before a waiver is a stale snapshot;
* go and no-go signoffs, who may record them, and that a signed candidate cannot change;
* the audit trail, and the honest part: a signed GO deployed nothing.
Environment: ``CALIBER_BASE_URL`` (the server root) and ``CALIBER_TOKEN`` (a token for an admin
account). Optional ``LAB11_SUFFIX`` makes every name unique so the script can be re-run on a stack
that already holds an earlier run. ``--cleanup`` removes what a run created.
The server needs ``CALIBER_OPERATOR_USERS`` to list ``lab11-operator`` next to ``admin`` and
``CALIBER_FEATURE_RELEASE_CANDIDATES=true`` (see the README).
"""
from __future__ import annotations
import json
import os
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
import httpx
from caliber_sdk import CaliberClient
from caliber_sdk.errors import CaliberAPIError, CaliberError
LAB_DIR = Path(__file__).resolve().parents[4] / "docs-site/cookbooks/11-release-readiness-factory"
ASSETS = LAB_DIR / "assets"
API_PREFIX = "/ajax-api/2.0/mlflow/caliber"
OPERATOR = ("lab11-operator", "lab11-operator-password")
VIEWER = ("lab11-viewer", "lab11-viewer-password")
PROMPT = "payments-assistant"
def say(message: str) -> None:
print(message, flush=True)
def check(condition: object, message: str) -> None:
if not condition:
raise AssertionError(message)
say(f" ok {message}")
def expect_status(status: int, action: Any, message: str) -> CaliberAPIError:
try:
action()
except CaliberAPIError as exc:
check(exc.status_code == status, f"{message} -> HTTP {exc.status_code}")
return exc
raise AssertionError(f"{message}: expected HTTP {status}, the call succeeded")
def load_candidates() -> list[dict[str, Any]]:
path = ASSETS / "dataset/release-candidates.jsonl"
return [json.loads(line) for line in path.read_text().splitlines() if line.strip()]
def candidate_body(row: dict[str, Any], suffix: str) -> dict[str, Any]:
"""The ``POST /releases/candidates`` body for one dataset row (the New candidate form's)."""
return {
"name": f"{row['name']}{suffix}",
"artifact_type": row["artifact_type"],
"artifact_ref": row["artifact_ref"],
"version_ref": row["version_ref"],
"required_score": row["required_score"],
"criteria": row["criteria"],
"evidence": row["evidence"],
"planned_action": {"action": f"promote_{row['artifact_type']}", "target": "prod"},
"rollback_target": {"version_ref": row["rollback_version"], "target": "prod"},
}
def login_client(
base_url: str, user: str, password: str, *, timeout: float = 60.0
) -> CaliberClient:
"""Sign in as ``user`` and mint a personal access token (a script cannot reuse a cookie)."""
api = base_url.rstrip("/") + API_PREFIX
login = httpx.post(f"{api}/auth/login", json={"user_id": user, "password": password})
login.raise_for_status()
issued = httpx.post(
f"{api}/auth/tokens", json={"name": f"cookbook-11-{user}"}, cookies=login.cookies
)
issued.raise_for_status()
return CaliberClient(base_url, token=issued.json()["data"]["token"], timeout=timeout)
def ensure_accounts(admin: CaliberClient) -> None:
for user, password in (OPERATOR, VIEWER):
try:
admin.auth.accounts.create(user, password)
say(f" created account {user}")
except CaliberError:
admin.auth.accounts.update(user, password=password)
say(f" account {user} already existed; password reset to the lab value")
def statuses(report: dict[str, Any]) -> list[str]:
return [item["status"] for item in report["results"]]
def run(
admin: CaliberClient,
*,
operator: CaliberClient,
viewer: CaliberClient,
suffix: str = "",
) -> dict[str, Any]:
rows = load_candidates()
by_id = {row["id"]: row for row in rows}
summary: dict[str, Any] = {"candidates": len(rows)}
prompt = f"{PROMPT}{suffix}"
ids: dict[str, str] = {}
say("== 1. a real artifact to release: a prompt with two versions")
admin.prompts.create(prompt, "You are a payments assistant. Question: {{question}}")
admin.prompts.register_version(
prompt,
"You are a careful payments assistant. Quote the refund policy. Question: {{question}}",
commit_message="cite the policy",
)
before = {v["version"]: v["aliases"] for v in admin.prompts.versions(prompt)}
check(before == {1: [], 2: []}, f"{prompt}: version 1 and 2 exist, no alias points at either")
say("== 2. create the 20 candidates as the operator")
for row in rows:
body = candidate_body(row, suffix)
if row["id"] == "RC20": # the walkthrough candidate points at the real prompt
body.update(artifact_ref=prompt, version_ref="2")
body["rollback_target"] = {"version_ref": "1", "target": "prod"}
made = operator.releases.create_candidate(**body)
ids[row["id"]] = made.candidate_id
expected = row["expect"]
blockers = [b["criterion_key"] for b in made.extra["blockers"]]
check(
made.weighted_score == expected["weighted_score"]
and made.status == expected["status"]
and blockers == expected["blockers"],
f"{row['id']} {made.weighted_score:<7} {made.status:<7} blockers={blockers}",
)
ready = sum(1 for r in rows if r["expect"]["status"] == "ready")
check(ready == 14 and len(rows) - ready == 6, "14 ready, 6 blocked, as the dataset predicts")
listed = {c.candidate_id for c in admin.releases.candidates()}
check(set(ids.values()) <= listed, "all 20 are listed")
summary["ids"] = ids
say("== 3. what a candidate is refused for")
ok_body = candidate_body(by_id["RC01"], f"{suffix} refused")
for label, change in (
("a criterion weight of 0", {"criteria": [{**by_id["RC01"]["criteria"][0], "weight": 0}]}),
("a score above 1", {"criteria": [{**by_id["RC01"]["criteria"][0], "score": 1.2}]}),
(
"a key with a space",
{"criteria": [{**by_id["RC01"]["criteria"][0], "key": "eval pass"}]},
),
("no criteria at all", {"criteria": []}),
("a required score above 1", {"required_score": 1.5}),
("an unknown field", {"approved": True}),
):
expect_status(
400,
lambda change=change: operator.releases.create_candidate(**{**ok_body, **change}),
f"{label} is rejected",
)
expect_status(
403,
lambda: viewer.releases.create_candidate(**ok_body),
"a viewer cannot create a candidate",
)
ghost = operator.releases.create_candidate(
**{
**ok_body,
"name": f"ghost{suffix}",
"artifact_ref": "no-such-prompt",
"version_ref": "99",
}
)
check(
ghost.status == "ready",
"a candidate for an artifact that does not exist is accepted: CALIBER records the "
"reference and does not look it up",
)
summary["ghost_candidate"] = ghost.candidate_id
say("== 4. waivers")
rc16, rc17, rc05 = ids["RC16"], ids["RC17"], ids["RC05"]
expect_status(
403,
lambda: operator.releases.add_waiver(
rc16, criterion_key="rollback_rehearsed", reason="Rehearsal scheduled for Monday."
),
"an operator cannot record a waiver (admin only)",
)
for label, payload, status in (
(
"an unknown criterion key",
{"criterion_key": "nope", "reason": "A long enough reason."},
400,
),
(
"a reason under 8 characters",
{"criterion_key": "rollback_rehearsed", "reason": "ok"},
400,
),
(
"an expiry in the past",
{
"criterion_key": "rollback_rehearsed",
"reason": "A long enough reason.",
"expires_at": "2020-01-01T00:00:00Z",
},
400,
),
):
expect_status(
status,
lambda payload=payload: admin.releases.add_waiver(rc16, **payload),
f"{label} is rejected",
)
first_report = admin.releases.generate_report(rc16)
check(
statuses(first_report["report"]) == ["passed", "passed", "failed", "passed"],
"RC16 report before the waiver: rollback_rehearsed failed",
)
expires = (datetime.now(timezone.utc) + timedelta(days=14)).isoformat()
waived = admin.releases.add_waiver(
rc16,
criterion_key="rollback_rehearsed",
reason=(
"Rollback rehearsal booked for the 25th; on-call holds the previous image. "
"Owner: release-eng."
),
expires_at=expires,
)
check(
waived["status"] == "ready"
and waived["blockers"] == []
and waived["weighted_score"] == 0.721,
"RC16: the waiver clears the only blocker; the weighted score is still 0.721",
)
check(
waived["waivers"][0]["approved_by"] == "admin" and waived["waivers"][0]["expires_at"],
"the waiver records who approved it, when, and its expiry",
)
again = operator.releases.evaluate(rc16)
check(
again.status == "ready" and again.weighted_score == 0.721,
"Re-evaluate recomputes from the stored criteria and waivers: unchanged",
)
second_report = admin.releases.generate_report(rc16)
check(
statuses(second_report["report"]) == ["passed", "passed", "skipped", "passed"],
"RC16 report after the waiver: the criterion is skipped (waived)",
)
check(
first_report["report"]["candidate_snapshot_sha256"]
!= second_report["report"]["candidate_snapshot_sha256"],
"the first report's snapshot hash is stale once the candidate changed",
)
for key, left in (("regression_vs_baseline", 1), ("human_review", 0)):
waived = admin.releases.add_waiver(
rc17, criterion_key=key, reason=f"Exception for {key}: tracked in the release ticket."
)
check(
len(waived["blockers"]) == left and waived["status"] == "blocked",
f"RC17 after waiving {key}: {left} blocker left, still blocked "
"(weighted 0.6575 < 0.85)",
)
expect_status(
409,
lambda: admin.releases.sign(rc17, decision="go", rationale="Both blockers are waived."),
"GO on RC17 is refused: no blocker is left, but the score is under the bar",
)
expect_status(
409,
lambda: admin.releases.sign(rc05, decision="go", rationale="Everything else is green."),
"GO on RC05 is refused: a blocking criterion (human_review) is unmet",
)
say("== 5. sign off")
rc20 = ids["RC20"]
expect_status(
403,
lambda: operator.releases.sign(rc20, decision="go", rationale="Looks good to me."),
"an operator cannot sign off (admin only)",
)
expect_status(
400,
lambda: admin.releases.sign(rc20, decision="go", rationale="ok"),
"a rationale under 8 characters is rejected",
)
report = operator.releases.generate_report(rc20)
check(
report["status"] == "completed"
and report["format"] == "allure-json"
and len(report["report"]["candidate_snapshot_sha256"]) == 64
and statuses(report["report"]) == ["passed"] * 4,
f"RC20 report job {report['report_job_id']}: completed, 4 passed, snapshot hash recorded",
)
check(
admin.releases.report_job(report["report_job_id"])["report"]["candidate_snapshot_sha256"]
== report["report"]["candidate_snapshot_sha256"],
"the job can be read back by id",
)
live_before = admin.releases.live()
timeline_before = admin.releases.timeline()
signed = admin.releases.sign(
rc20,
decision="go",
rationale=(
"Quality 0.94 on the sealed set, no regression, expert review complete, "
"rollback v1 ready."
),
)
check(
signed["decision"] == "go"
and signed["decided_by"] == "admin"
and signed["candidate_snapshot"]["status"] == "ready"
and signed["candidate_snapshot"]["weighted_score"] == 0.9375,
f"RC20 signed GO by admin ({signed['signoff_id']}); the snapshot froze score 0.9375",
)
no_go = admin.releases.sign(
ids["RC19"],
decision="no_go",
rationale="Trigger precision 0.70 and recall 0.66 are below the 0.92 / 0.85 gates.",
)
check(no_go["decision"] == "no_go", "RC19 (blocked) signed NO-GO: a refusal is a decision too")
go18 = admin.releases.sign(
ids["RC18"],
decision="go",
rationale="All gates met; macros KB v11 reviewed by support leads.",
)
check(go18["decision"] == "go", "RC18 signed GO")
detail = admin.releases.get_candidate(rc20)
check(
detail.status == "signed_go"
and len(detail.extra["signoffs"]) == 1
and detail.extra["signoffs"][0]["signoff_id"] == signed["signoff_id"]
and len(detail.extra["report_jobs"]) == 1,
"the candidate shows signed_go with its signoff and report job",
)
summary["signoff"] = {
"signoff_id": signed["signoff_id"],
"report_job_id": report["report_job_id"],
}
say("== 6. a signed candidate is final")
expect_status(409, lambda: admin.releases.evaluate(rc20), "Re-evaluate is refused (409)")
expect_status(
409,
lambda: admin.releases.add_waiver(
rc20, criterion_key="latency_p95", reason="A late exception must not be possible."
),
"a waiver is refused (409)",
)
expect_status(
409,
lambda: admin.releases.sign(rc20, decision="no_go", rationale="Changing my mind later."),
"a second signoff is refused (409)",
)
check(admin.releases.get_candidate(rc20).status == "signed_go", "it is still signed_go")
bare = operator.releases.create_candidate(
**{**ok_body, "name": f"no-rollback{suffix}", "rollback_target": {}, "planned_action": {}}
)
expect_status(
409,
lambda: admin.releases.sign(
bare.candidate_id, decision="go", rationale="Ship it without a way back."
),
"GO on a ready candidate with no planned action or rollback target is refused",
)
say("== 7. signing off deployed nothing")
after = {v["version"]: v["aliases"] for v in admin.prompts.versions(prompt)}
check(after == before, f"{prompt}: no alias moved (still {after})")
check(
admin.releases.live() == live_before and admin.releases.timeline() == timeline_before,
"the live board and the release timeline did not change",
)
admin.prompts.promote(prompt, 2)
promoted = {v["version"]: v["aliases"] for v in admin.prompts.versions(prompt)}
check(
promoted == {1: [], 2: ["prod"]},
"the real release is a separate act: Promote on the prompt moves the alias",
)
events = [e["action"] for e in admin.releases.timeline()]
check("promote_prompt" in events, "and that, not the signoff, is what the timeline records")
say("== 8. who did what")
actions: dict[str, set[str]] = {}
for entry in admin.audit.list(limit=200):
if entry.entity_id in ids.values():
actions.setdefault(entry.action, set()).add(entry.actor)
for action, actors in (
("create_release_candidate", {"lab11-operator"}),
("waive_release_blocker", {"admin"}),
("generate_release_allure_report", {"admin", "lab11-operator"}),
("signoff_release_candidate", {"admin"}),
("evaluate_release_candidate", {"lab11-operator"}),
):
check(actions.get(action) == actors, f"audit: {action} by {sorted(actors)}")
return summary
def cleanup(admin: CaliberClient, suffix: str) -> None:
try:
admin.prompts.delete(f"{PROMPT}{suffix}")
say(f"deleted prompt {PROMPT}{suffix}")
except CaliberError:
say(f"no prompt {PROMPT}{suffix} to delete")
say(
"release candidates are an audit record and cannot be deleted; signed ones are immutable. "
"Use a new LAB11_SUFFIX to run again, or reset the stack."
)
def main() -> None:
base_url = os.environ["CALIBER_BASE_URL"]
suffix = os.environ.get("LAB11_SUFFIX", "")
admin = CaliberClient(base_url, token=os.environ["CALIBER_TOKEN"], timeout=120)
if "--cleanup" in sys.argv:
cleanup(admin, suffix)
return
ensure_accounts(admin)
result = run(
admin,
operator=login_client(base_url, *OPERATOR),
viewer=login_client(base_url, *VIEWER),
suffix=suffix,
)
say("== done")
print(json.dumps(result, indent=2, sort_keys=True))
if __name__ == "__main__":
main()sdk/caliber-sdk/examples/cookbooks/cookbook_11_release_signoff_factory.py — executed by the SDK example test suite.Cookbook 12 — Aria: Evaluation Harness from Intent
Check Aria's nine capabilities and draw a plan for each of 28 goals (28/28 match the dataset, every draft cancelled, nothing run), then state the canonical intent, approve the two-step plan (judge.create, eval_dataset.create), answer its four interactions with typed values, and assert the active judge and the empty version-1 test set exist under the typed names. It then loads the 30 rows of faithfulness-cases.jsonl, checks them back (version 31), and provokes the refusals (a goal with no steps, a bad form answer, a denied step, a judge with no evaluation variable, a taken name, no operator scope, a non-owner). It needs an admin-scoped SDK token, CALIBER_FEATURE_ARIA=true and CALIBER_OPERATOR_USERS=admin,olga, and creates the olga and vera accounts (signed in with plain httpx calls, no client.raw). Aria's planner is deterministic rules and no model is needed: running the judge in Evaluations is refused with a 400 on the simulated stack and the script verifies that refusal instead of a score (with a real provider it asserts all 30 rows were scored). It does not call the cookbooks resource.
SDK surfaces: aria, judges, datasets, evaluations, auth
- Check that Aria lists its nine capabilities with their tiers, and draw a plan for each of the 28 goals in
goals.jsonl, comparing it with the dataset (28/28) and cancelling every draft. - Create the plan from the typed intent (it draws
judge.createtheneval_dataset.create), approve it and execute it; it pauses on the judge step waiting for input. - Answer the four interactions (judge fields, approve, test set fields, approve) until the plan reads
completed, then check the judge is active asbooland the test set has its own name, version 1 and no rows. - Add the 30 cases to the test set, read them back (30 rows, version 31, each stored row equal to the file's row), and run the test set in Evaluations, which is refused (400) without a real model.
- Provoke the refusals: a goal with no steps cannot be approved (409), a form rejects an unknown field, a wrong type, an empty name and a missing field, a denied step is skipped while the other runs, a judge with no evaluation variable fails its step, and a taken judge name fails its step.
- Show the role rules: an account without the operator scope is refused (403) and creates nothing, and an operator who does not own the plan cannot answer its question (403) or see it (404).
"""Cookbook 12: give Aria one sentence and get a judge and a test set, then fill the test set.
Runs the whole lab through the SDK against a live server and exits 0 only when every check below
holds. It is the API half of the lab README (docs-site/cookbooks/12-aria-evaluation-harness/
README.md) and prints the same values the README tells you to expect.
export CALIBER_BASE_URL=http://127.0.0.1:5001 # the server root, not the /ajax-api path
export CALIBER_TOKEN=calpat_... # an ADMIN personal access token
PYTHONPATH=sdk/caliber-sdk caliber/.venv/bin/python \
-m examples.cookbooks.cookbook_12_aria_evaluation_harness
The server needs ``CALIBER_FEATURE_ARIA=true`` and ``CALIBER_OPERATOR_USERS=admin,olga`` (olga is
an operator who does not own the plan; the script also creates ``vera``, who is not an operator).
Nothing in the planning needs a model: Aria's planner is deterministic. The step that does, running
the judge in Evaluations, has two modes, told apart by ``GET /readiness``. On a simulated stack (the
default) it is refused with a 400 and the script verifies the refusal. On a stack started with
``scripts/cookbook-env.sh up NAME --flags cookbooks,aria --real-llm`` the script scores the 30 rows
with the judge for real, twice (a grounded answerer prompt and a careless control), asserts
structure, ranges and that the judge tells them apart (never an exact score), and then checks the
Ask Aria chat on both sides of its permission boundary. Runs take a few minutes and cost a few
cents there; ``COOKBOOK_ARIA_HTTP_TIMEOUT`` (seconds, default 900) bounds one request.
What it does, in order:
1. Checks Aria's capability list, and draws a plan for each of the 28 goals in
``assets/dataset/goals.jsonl``, comparing it with the dataset (nothing runs: every draft is
cancelled again).
2. States the canonical intent, approves the plan, and answers its four questions: the judge's
fields, an Approve, the test set's fields, an Approve. Checks the judge and the test set exist
under the names typed, and that the test set is empty at version 1.
3. Adds the 30 rows of ``assets/dataset/faithfulness-cases.jsonl`` to the test set, and reads them
back.
4. Runs the test set in Evaluations (refused on a simulated stack; on a real one, scored by the
judge for a grounded and a careless answerer, checked by invariants).
5. Provokes the refusals: a goal with no steps, a plan that was cancelled, answers the form rejects,
a denied step, a judge with no evaluation variable, a duplicate name, an account without the
operator scope, and an operator who does not own the plan.
6. Real stack only: Ask Aria's chat creates a judge in a ``build`` / ``auto_all`` session and is not
offered the tool in the default session.
``--cleanup`` archives what earlier runs created (and deletes the prompts of a real run).
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import time
from collections.abc import Callable
from functools import partial
from pathlib import Path
from typing import Any
from caliber_sdk import CaliberClient
from caliber_sdk.errors import CaliberAPIError, CaliberPermissionError
from examples.cookbooks._aria_lab import (
CARELESS_PROMPT,
GROUNDED_PROMPT,
Checks,
Report,
SetupError,
VerificationError,
check_chat_boundary,
check_goals_report,
check_judged_evaluation,
create_prompt,
ensure_accounts,
env_password,
form_values,
http_timeout,
is_real,
judge_rate,
load_jsonl,
refused,
require_admin_and_aria,
require_scopes,
run_judged_evaluation,
run_plan,
sign_in,
start,
step_keys,
step_status,
walk,
)
from examples.cookbooks._helpers import env_client
NAME_PREFIX = "cookbook-12-"
DEFAULT_PASSWORD = "cookbook-aria-lab-passphrase"
OPERATOR_USER = "olga"
VIEWER_USER = "vera"
INTENT = "Create a judge for answer faithfulness and an eval dataset to run it on."
#: What the planner is documented to draw for the 28 goals (see assets/dataset/goals.jsonl).
GOALS_EXPECTED = 28
ROWS_EXPECTED = 30
#: A real run: the grounded answerer's share of faithful rows must beat the careless one's by this
#: much. Typical observed gaps are far larger (README); the bar only has to rule out a judge that
#: says the same thing about everything.
MIN_FAITHFUL_GAP = float(os.environ.get("COOKBOOK_12_MIN_GAP", "0.2"))
CAPABILITIES = {
"eval_dataset.create": "mutate",
"judge.create": "mutate",
"judge.list": "read",
"openapi_tool.invoke": "read",
"openapi_tool.list": "read",
"review_queue.add_items": "mutate",
"review_queue.create": "mutate",
"review_queue.list": "read",
"workflow.calibrate": "mutate",
}
def default_assets_dir() -> Path:
return Path(
os.environ.get(
"COOKBOOK_12_ASSETS",
Path(__file__).resolve().parents[4]
/ "docs-site/cookbooks/12-aria-evaluation-harness/assets",
)
)
def run(
caliber: CaliberClient,
*,
operator: CaliberClient,
viewer: CaliberClient,
suffix: str | None = None,
assets: Path | None = None,
report: Report = print,
sleep: Callable[[float], None] = time.sleep,
) -> dict[str, Any]:
"""Run the whole lab. ``caliber`` is the admin's client; ``operator`` and ``viewer`` are the
two other accounts' clients."""
assets = assets or default_assets_dir()
suffix = suffix or time.strftime("%Y%m%d-%H%M%S")
check = Checks(report)
result: dict[str, Any] = {"suffix": suffix}
prompts: list[str] = []
result["prompts"] = prompts
goals = load_jsonl(assets / "dataset/goals.jsonl")
cases = load_jsonl(assets / "dataset/faithfulness-cases.jsonl")
judge_spec = form_values(assets / "judges/answer-faithfulness.judge.json")
dataset_spec = form_values(assets / "datasets/support-faithfulness.dataset.json")
judge_name = f"{NAME_PREFIX}{judge_spec['name']}-{suffix}"
dataset_name = f"{NAME_PREFIX}{dataset_spec['name']}-{suffix}"
judge_form = {**judge_spec, "name": judge_name}
dataset_form = {**dataset_spec, "name": dataset_name}
admin_id = require_admin_and_aria(caliber)
real = is_real(caliber)
result["mode"] = "real" if real else "simulated"
require_scopes(
{"olga": operator, "vera": viewer},
has={"olga": True, "vera": False},
hint=(
"start CALIBER with CALIBER_OPERATOR_USERS=admin,olga (olga is an operator who does "
"not own the plan, vera must not be one)"
),
)
# -- 1. What Aria can do, and what it plans for 28 goals -----------------------------------
listed = {item["key"]: item["tier"] for item in caliber.aria.capabilities()["capabilities"]}
check("Aria lists its nine capabilities with their tiers", listed == CAPABILITIES, len(listed))
check_goals_report(caliber, goals, GOALS_EXPECTED, check)
# -- 2. The canonical intent, through every question ----------------------------------------
drawn = caliber.aria.create_plan(INTENT, autonomy="ask_each")
plan_id = drawn.plan.plan_id
check(
"the intent draws judge.create then eval_dataset.create",
step_keys(drawn) == ["judge.create", "eval_dataset.create"],
plan_id,
)
check(
"neither step has an input wired from the other (each asks for its own name)",
all(not step.extra.get("inputs") and not step.depends_on for step in drawn.steps),
)
caliber.aria.approve_plan(plan_id)
first = caliber.aria.execute_plan(plan_id)
check(
"execute pauses on the judge step, waiting for input",
first.plan.status == "paused" and step_status(first)["judge.create"] == "waiting_input",
)
finished, trail = walk(
caliber,
plan_id,
[
("input", judge_form),
("permission", "approve"),
("input", dataset_form),
("permission", "approve"),
],
)
check(
"the plan asked for the judge's fields, an approval, the test set's fields and an approval",
trail
== [
("input", "judge.create"),
("permission", "judge.create"),
("input", "eval_dataset.create"),
("permission", "eval_dataset.create"),
],
)
check(
"the plan completed with both steps done",
finished.plan.status == "completed" and set(step_status(finished).values()) == {"done"},
finished.plan.status,
)
judge_id = next(s for s in finished.steps if s.capability_key == "judge.create").result[
"judge_id"
]
dataset_id = next(
s for s in finished.steps if s.capability_key == "eval_dataset.create"
).result["dataset_id"]
judge = caliber.judges.get(judge_id)
check(
"the judge is active with the typed name, type and instructions",
judge.status == "active"
and judge.name == judge_name
and judge.feedback_value_type == "bool"
and judge.instructions == judge_spec["instructions"]
and "{{ outputs }}" in (judge.instructions or ""),
f"{judge_id} {judge.name}",
)
dataset = caliber.eval_datasets.get(dataset_id)
check(
"the test set has its own name (not the judge's), owner, tags, version 1 and no rows",
dataset.name == dataset_name
and dataset.name != judge.name
and dataset.owner == admin_id
and dataset.version == 1
and sorted(dataset.tags) == sorted(dataset_spec["tags"])
and not caliber.eval_datasets.examples(dataset_id),
f"{dataset_id} {dataset.name}",
)
result.update(plan_id=plan_id, judge_id=judge_id, dataset_id=dataset_id)
# -- 3. Fill the test set -----------------------------------------------------------------
for case in cases:
caliber.eval_datasets.add_example(
dataset_id, input=case["input"], expected=case["expected"], tags=case["tags"]
)
rows = caliber.eval_datasets.examples(dataset_id)
by_question = {row.input["question"]: row for row in rows}
check(
"the test set holds the 30 cases, one version per row",
len(cases) == ROWS_EXPECTED
and len(rows) == ROWS_EXPECTED
and caliber.eval_datasets.get(dataset_id).version == 1 + ROWS_EXPECTED,
f"{len(rows)} rows, version {caliber.eval_datasets.get(dataset_id).version}",
)
check(
"every stored row is the file's row (input, expected answer, tags)",
all(
by_question[c["input"]["question"]].input == c["input"]
and by_question[c["input"]["question"]].expected == c["expected"]
and by_question[c["input"]["question"]].extra.get("tags") == c["tags"]
for c in cases
),
)
categories = sorted({c["tags"][0] for c in cases})
result["rows"] = {"count": len(rows), "categories": categories}
# -- 4. Run it in Evaluations ---------------------------------------------------------------
if real:
result["evaluation"] = _evaluate_for_real(
caliber, check, dataset_id, judge_id, suffix=suffix, prompts=prompts
)
else:
refusal = refused(lambda: caliber.evaluations.create(dataset_id, scorers=["non_empty"]))
check(
"Evaluations are refused without a real model (400): the judge cannot run here",
refusal is not None
and refusal.status_code == 400
and "real LLM provider" in str(refusal),
"simulated stack",
)
result["evaluation"] = "refused (simulated provider)"
# -- 5. Refusals --------------------------------------------------------------------------
# 5a. A goal with no steps.
nothing = caliber.aria.create_plan("Write me a poem about customer support.")
approve_empty = refused(lambda: caliber.aria.approve_plan(nothing.plan.plan_id))
check(
"a goal with no steps is created with a warning and refused at approval (409)",
nothing.plan.step_count == 0
and bool(nothing.extra.get("warnings"))
and approve_empty is not None
and approve_empty.status_code == 409,
)
caliber.aria.update_plan(nothing.plan.plan_id, status="cancelled")
# 5b. A cancelled draft cannot be approved or run.
draft = caliber.aria.create_plan("Create a judge.")
caliber.aria.update_plan(draft.plan.plan_id, status="cancelled")
approve_cancelled = refused(lambda: caliber.aria.approve_plan(draft.plan.plan_id))
execute_cancelled = refused(lambda: caliber.aria.execute_plan(draft.plan.plan_id))
check(
"a cancelled plan can be neither approved nor executed (409)",
approve_cancelled is not None
and approve_cancelled.status_code == 409
and execute_cancelled is not None
and execute_cancelled.status_code == 409,
)
# 5c. Answers the form refuses, then a step skipped.
first = start(caliber, "Create a judge.", autonomy="approve_plan")
form = next(i for i in caliber.aria.interactions(first.plan.plan_id) if i.status == "pending")
bad = {
"unknown field": {"name": "x", "instructions": "{{ outputs }}", "colour": "red"},
"wrong type": {"name": 7, "instructions": "{{ outputs }}"},
"empty name": {"name": "", "instructions": "{{ outputs }}"},
"missing field": {"name": "x"},
}
refusals = {
label: refused(partial(caliber.aria.answer, form.interaction_id, inputs=inputs))
for label, inputs in bad.items()
}
check(
"the form refuses an unknown field, a wrong type, an empty name and a missing field (409)",
all(e is not None and e.status_code == 409 for e in refusals.values()),
{label: str(e).split("] ")[1].split(" (POST")[0] for label, e in refusals.items() if e},
)
check(
"after four refusals the question is still pending",
[i.status for i in caliber.aria.interactions(first.plan.plan_id)] == ["pending"],
)
skipped, _ = walk(caliber, first.plan.plan_id, [("input", "skip")])
check(
"Skip step marks the step skipped and the plan completes",
skipped.plan.status == "completed" and step_status(skipped) == {"judge.create": "skipped"},
)
answered_again = refused(lambda: caliber.aria.answer(form.interaction_id, approved=False))
check(
"an answered question cannot be answered again (409)",
answered_again is not None and answered_again.status_code == 409,
)
# 5d. Deny one step, approve the other.
denied_judge = f"{NAME_PREFIX}denied-{suffix}"
denied_set = f"{NAME_PREFIX}kept-set-{suffix}"
denied, _ = run_plan(
caliber,
INTENT,
autonomy="ask_each",
moves=[
("input", {**judge_form, "name": denied_judge}),
("permission", "deny"),
("input", {"name": denied_set}),
("permission", "approve"),
],
)
check(
"denying the judge skips it; the test set step still runs and the plan completes",
denied.plan.status == "completed"
and step_status(denied) == {"judge.create": "skipped", "eval_dataset.create": "done"}
and denied_judge not in {j.name for j in caliber.judges.list()}
and denied_set in {d.name for d in caliber.eval_datasets.list()},
)
# 5e. A judge that uses no evaluation variable passes the form and fails the step.
broken_name = f"{NAME_PREFIX}no-variable-{suffix}"
broken, _ = run_plan(
caliber,
"Create a judge.",
autonomy="approve_plan",
moves=[
(
"input",
{"name": broken_name, "instructions": "Is {{ evidence }} faithful to the policy?"},
)
],
)
broken_error = str(broken.steps[0].error)
check(
"a judge with no evaluation variable fails its step and the plan, naming the field",
broken.plan.status == "failed"
and step_status(broken) == {"judge.create": "failed"}
and broken_error.startswith("invalid input: instructions: instructions must reference")
and broken_name not in {j.name for j in caliber.judges.list()},
broken_error[:90],
)
rerun = refused(lambda: caliber.aria.execute_plan(broken.plan.plan_id))
check(
"a failed plan cannot be run again (409): state the goal again",
rerun is not None and rerun.status_code == 409,
)
# 5f. A duplicate name fails the step.
duplicate, _ = run_plan(
caliber,
"Create a judge.",
autonomy="approve_plan",
moves=[("input", judge_form)],
)
duplicate_error = str(duplicate.steps[0].error)
check(
"a judge name that is already taken fails its step",
duplicate.plan.status == "failed" and "is already in use" in duplicate_error,
duplicate_error,
)
# 5g. Roles.
refused_judge = refused(
lambda: viewer.judges.create(
f"{NAME_PREFIX}viewer-{suffix}", instructions="Is {{ outputs }} fine?"
)
)
check(
"without the operator scope the judge route refuses the account (403)",
isinstance(refused_judge, CaliberPermissionError),
)
by_viewer = start(viewer, "Create a judge.", autonomy="approve_plan")
check(
"a plan owned by an account without the operator scope fails at execute, before it asks "
"for anything, and creates nothing",
by_viewer.plan.status == "failed"
and by_viewer.steps[0].error == "plan owner lacks required scope(s): operator"
and f"{NAME_PREFIX}viewer-{suffix}" not in {j.name for j in caliber.judges.list()},
by_viewer.steps[0].error,
)
own = start(caliber, "Create a judge.", autonomy="approve_plan")
waiting = next(i for i in caliber.aria.interactions(own.plan.plan_id) if i.status == "pending")
other_answer = refused(lambda: operator.aria.answer(waiting.interaction_id, approved=False))
check(
"an operator who does not own the plan cannot answer its question (403)",
isinstance(other_answer, CaliberPermissionError),
str(other_answer).split("] ")[1].split(" (POST")[0] if other_answer else "",
)
other_read = refused(lambda: operator.aria.get_plan(own.plan.plan_id))
check(
"nor can they see it (404): plans are private to their owner",
other_read is not None and other_read.status_code == 404,
)
walk(caliber, own.plan.plan_id, [("input", "skip")])
# -- 6. Ask Aria's chat, on a real stack ------------------------------------------------------
if real:
result["chat"] = _chat_for_real(caliber, check, suffix)
check.finish()
return result
def _evaluate_for_real(
caliber: CaliberClient,
check: Checks,
dataset_id: str,
judge_id: str,
*,
suffix: str,
prompts: list[str],
) -> dict[str, Any]:
"""Score the 30 rows with the judge for a grounded answerer and a careless control."""
grounded_ref = create_prompt(caliber, f"{NAME_PREFIX}grounded-answer-{suffix}", GROUNDED_PROMPT)
careless_ref = create_prompt(caliber, f"{NAME_PREFIX}careless-answer-{suffix}", CARELESS_PROMPT)
prompts.extend(ref.split("@")[0] for ref in (grounded_ref, careless_ref))
grounded = run_judged_evaluation(
caliber, dataset_id, judge_id, prompt_ref=grounded_ref, label=f"grounded {suffix}"
)
careless = run_judged_evaluation(
caliber, dataset_id, judge_id, prompt_ref=careless_ref, label=f"careless {suffix}"
)
summary: dict[str, Any] = {
"grounded": check_judged_evaluation(
check,
"grounded answerer",
grounded,
judge_id,
rows=ROWS_EXPECTED,
prompt_ref=grounded_ref,
),
"careless": check_judged_evaluation(
check,
"careless control",
careless,
judge_id,
rows=ROWS_EXPECTED,
prompt_ref=careless_ref,
),
}
gap = (judge_rate(grounded, judge_id) or 0.0) - (judge_rate(careless, judge_id) or 0.0)
check(
f"the judge tells the two answerers apart: grounded beats careless by at least "
f"{MIN_FAITHFUL_GAP}",
gap >= MIN_FAITHFUL_GAP,
f"grounded {judge_rate(grounded, judge_id)}, careless {judge_rate(careless, judge_id)}, "
f"gap {gap:+.2f}",
)
summary["gap"] = float(f"{gap:.3f}")
return summary
def _chat_for_real(caliber: CaliberClient, check: Checks, suffix: str) -> dict[str, Any]:
"""Ask Aria (the chat, not the Plans page) acts in build / auto_all and only reads otherwise."""
acting = f"{NAME_PREFIX}chat-judge-{suffix}"
reading = f"{NAME_PREFIX}chat-manual-{suffix}"
instructions = (
"Is {{ outputs }} faithful to the evidence in {{ inputs }}? Answer true or false."
)
def judge_names() -> set[str]:
return {j.name for j in caliber.judges.list()}
summary = check_chat_boundary(
caliber,
check,
tool="judge_create",
ask=(
f"Create a judge named {acting} with a boolean feedback value type and exactly these "
f"instructions: {instructions} Then tell me its id."
),
exists=lambda: acting in judge_names(),
absent_ask=(
f"Create a judge named {reading} with a boolean feedback value type and exactly "
f"these instructions: {instructions} Tell me what you did."
),
absent_exists=lambda: reading in judge_names(),
)
made = next((j for j in caliber.judges.list() if j.name == acting), None)
check(
"the chat's judge is active, boolean, and its instructions use an evaluation variable",
made is not None
and made.status == "active"
and made.feedback_value_type == "bool"
and "{{ outputs }}" in (made.instructions or ""),
made.judge_id if made else "",
)
return summary
def cleanup(caliber: CaliberClient) -> dict[str, int]:
"""Archive the judges and test sets earlier runs created (names start ``cookbook-12-``)."""
archived = {"judges": 0, "test_sets": 0, "prompts": 0}
for judge in caliber.judges.list():
if judge.name.startswith(NAME_PREFIX) and judge.status != "archived":
caliber.judges.update(judge.judge_id, status="archived")
archived["judges"] += 1
for dataset in caliber.eval_datasets.list():
if dataset.name.startswith(NAME_PREFIX) and dataset.status != "archived":
caliber.eval_datasets.update(dataset.dataset_id, status="archived")
archived["test_sets"] += 1
for prompt in caliber.prompts.list():
if prompt.prompt_name.startswith(NAME_PREFIX):
caliber.prompts.delete(prompt.prompt_name)
archived["prompts"] += 1
return archived
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
parser.add_argument("--cleanup", action="store_true", help="archive what earlier runs created")
parser.add_argument("--suffix", help="name suffix (default: a timestamp)")
args = parser.parse_args(argv)
base_url = os.environ["CALIBER_BASE_URL"]
password = env_password("COOKBOOK_ARIA_PASSWORD", DEFAULT_PASSWORD)
opened: list[CaliberClient] = []
with env_client(timeout=http_timeout()) as caliber:
try:
if args.cleanup:
print(json.dumps(cleanup(caliber), indent=2))
return 0
ensure_accounts(caliber, (OPERATOR_USER, VIEWER_USER), password)
clients = {}
for user in (OPERATOR_USER, VIEWER_USER):
clients[user] = CaliberClient(base_url, token=sign_in(base_url, user, password))
opened.append(clients[user])
result = run(
caliber,
operator=clients[OPERATOR_USER],
viewer=clients[VIEWER_USER],
suffix=args.suffix,
)
except (VerificationError, SetupError, CaliberAPIError) as exc:
print(f"\nVERIFICATION FAILED: {exc}", file=sys.stderr)
return 1
finally:
for client in opened:
client.close()
print(json.dumps(result, indent=2, sort_keys=True, default=str))
return 0
if __name__ == "__main__":
sys.exit(main())sdk/caliber-sdk/examples/cookbooks/cookbook_12_aria_evaluation_harness.py — executed by the SDK example test suite.Cookbook 13 — Aria: Human-Review Queue from Intent
Seed 30 flagged agent replies as MLflow traces, state one sentence of intent to Aria, answer its four questions so it creates a review queue and enqueues the 30 traces, review 12 of them as the queue's owner, and check that each answer landed on its trace as an assessment and as a labelled alignment example; then provoke the refusals (bad answers, a missing trace id, skipped, denied and failing steps, a non-operator account, an operator who does not own the queue) and assert the exact status codes. It needs CALIBER_FEATURE_ARIA=true, an admin-scoped token, CALIBER_OPERATOR_USERS=admin,olga (the script also creates vera, a non-operator), mlflow with MLFLOW_TRACKING_URI for the seed traces; no model is needed because Aria's planner is deterministic. It does not install a cookbook, and it reads the queue back with client.raw (GET /review-queues/{id}) in several places.
SDK surfaces: aria, review_queues, observability, auth
- Write the 30 flagged replies to MLflow as traces and draw a plan for each of the 26 goals in the dataset, checking every plan against the expected steps (every draft is cancelled, nothing runs).
- State the canonical intent and answer four questions: the queue's fields, an Approve, the 30 trace ids, an Approve; check the plan completed, the queue is active with its five questions, and it holds the 30 traces, all pending.
- Review 12 of the 30 as the queue's owner through
review_queues.submit, then check each answer is on its trace as an assessment and that the safety answers are 12 labelled examples for judge alignment. - Provoke the review refusals: a missing, mistyped, unknown-option or unknown-question answer (400), a second review (409), a non-operator (403), an operator who does not own the queue (404), and a trace id that does not exist (queued, then 502 on review).
- Provoke the plan refusals: a skipped queue skips the enqueue step, a denied enqueue keeps the empty queue, malformed forms stay open (409), a categorical question without options and a taken name fail their step, a goal with no steps is refused at approval, and a plan owned by a non-operator fails at execute.
"""Cookbook 13: give Aria one sentence and get a review queue with 30 flagged replies to label.
Runs the whole lab through the SDK against a live server and exits 0 only when every check below
holds. It is the API half of the lab README (docs-site/cookbooks/13-aria-review-governance-queue/
README.md) and prints the same values the README tells you to expect.
export CALIBER_BASE_URL=http://127.0.0.1:5001 # the server root, not the /ajax-api path
export CALIBER_TOKEN=calpat_... # an ADMIN personal access token
export MLFLOW_TRACKING_URI=http://127.0.0.1:5000 # where CALIBER's traces live
PYTHONPATH=sdk/caliber-sdk caliber/.venv/bin/python \
-m examples.cookbooks.cookbook_13_aria_review_queue
The server needs ``CALIBER_FEATURE_ARIA=true`` and ``CALIBER_OPERATOR_USERS=admin,olga``; the script
also creates ``vera``, who is not an operator. Nothing in the lab needs a model: Aria's planner is
deterministic and a review queue is people's work. What a real provider adds is told apart by
``GET /readiness``: on a stack started with
``scripts/cookbook-env.sh up NAME --flags cookbooks,aria --real-llm`` the script also checks a real
safety judge against the 12 human labels (agreement and kappa within ranges, never exact values)
and checks the Ask Aria chat on both sides of its permission boundary; a few cents and about a
minute. ``COOKBOOK_ARIA_HTTP_TIMEOUT`` (seconds, default 900) bounds one request.
What it does, in order:
1. Writes the 30 flagged replies of ``assets/dataset/agent-replies.jsonl`` to MLflow as traces
(``assets/seed_traces.py``), and draws a plan for each of the 26 goals in
``assets/dataset/goals.jsonl``, comparing it with the dataset (nothing runs).
2. States the canonical intent and answers four questions: the queue's fields, an Approve, the
trace ids (the queue's id is wired from the first step), an Approve. Checks the queue and its 30
pending items.
3. Reviews 12 of the 30 (``REVIEWED_IDS``) as the person who owns the queue, with the human
labels in the dataset, and
checks that every answer landed on its trace as an assessment and became a labelled example for
judge alignment. On a real stack a safety judge is then run against those 12 labels.
4. Provokes the refusals: answers the queue's questions do not fit, a trace id that does not exist,
a skipped producer step, a denied step, a malformed question schema, a taken name, an account
without the operator scope, and an operator who cannot see a queue they do not own.
5. Real stack only: Ask Aria's chat creates a review queue in a ``build`` / ``auto_all`` session and
is not offered the tool in the default session.
``--cleanup`` archives what earlier runs created.
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import os
import sys
import time
from collections.abc import Callable
from functools import partial
from pathlib import Path
from typing import Any
from caliber_sdk import CaliberClient
from caliber_sdk.errors import CaliberAPIError, CaliberPermissionError
from examples.cookbooks._aria_lab import (
Checks,
Report,
SetupError,
VerificationError,
check_chat_boundary,
check_goals_report,
ensure_accounts,
env_password,
form_values,
http_timeout,
is_real,
load_jsonl,
pending,
refused,
require_admin_and_aria,
require_scopes,
run_plan,
sign_in,
start,
step_keys,
step_status,
walk,
)
from examples.cookbooks._helpers import env_client
NAME_PREFIX = "cookbook-13-"
DEFAULT_PASSWORD = "cookbook-aria-lab-passphrase"
OPERATOR_USER = "olga"
VIEWER_USER = "vera"
INTENT = "Set up a review queue for human labeling of agent replies for safety, citation, and tone."
GOALS_EXPECTED = 26
REPLIES_EXPECTED = 30
#: The rows a person reviews by hand: clean replies, unsafe ones, wrong citations and bad tone.
REVIEWED_IDS = ("R01", "R03", "R05", "R09", "R11", "R12", "R13", "R15", "R18", "R22", "R23", "R27")
REVIEWED = len(REVIEWED_IDS)
#: A real run: the safety judge against the 12 human labels. Typical observed values are higher
#: (README); the bars only rule out a judge that is guessing or saying one thing about everything.
MIN_AGREEMENT = float(os.environ.get("COOKBOOK_13_MIN_AGREEMENT", "0.75"))
MIN_KAPPA = float(os.environ.get("COOKBOOK_13_MIN_KAPPA", "0.4"))
FLAGGED_REASONS = {
"thumbs_down",
"latency_over_8s",
"low_judge_score",
"keyword:medication",
"keyword:lawsuit",
"keyword:refund",
"pii_detected",
"jailbreak_pattern",
"escalation_ignored",
}
def default_assets_dir() -> Path:
return Path(
os.environ.get(
"COOKBOOK_13_ASSETS",
Path(__file__).resolve().parents[4]
/ "docs-site/cookbooks/13-aria-review-governance-queue/assets",
)
)
def seed_traces(assets: Path) -> dict[str, str]:
"""Write the 30 replies as traces (needs ``mlflow`` and ``MLFLOW_TRACKING_URI``)."""
spec = importlib.util.spec_from_file_location(
"cookbook13_seed_traces", assets / "seed_traces.py"
)
if spec is None or spec.loader is None:
raise SetupError(f"{assets / 'seed_traces.py'} not found")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return dict(module.seed(assets / "dataset" / "agent-replies.jsonl"))
def _reason(error: CaliberAPIError | None) -> str:
return str(error).split("] ", 1)[1].split(" (", 1)[0] if error else ""
def run(
caliber: CaliberClient,
*,
operator: CaliberClient,
viewer: CaliberClient,
suffix: str | None = None,
assets: Path | None = None,
traces: dict[str, str] | None = None,
report: Report = print,
sleep: Callable[[float], None] = time.sleep,
) -> dict[str, Any]:
"""Run the whole lab. ``caliber`` is the admin's client (the plan's owner and the reviewer);
``operator`` and ``viewer`` are the two other accounts' clients."""
assets = assets or default_assets_dir()
suffix = suffix or time.strftime("%Y%m%d-%H%M%S")
check = Checks(report)
result: dict[str, Any] = {"suffix": suffix}
goals = load_jsonl(assets / "dataset/goals.jsonl")
replies = load_jsonl(assets / "dataset/agent-replies.jsonl")
queue_spec = form_values(assets / "review-queues/agent-reply-review.queue.json")
queue_name = f"{NAME_PREFIX}{queue_spec['name']}-{suffix}"
queue_form = {**queue_spec, "name": queue_name}
require_admin_and_aria(caliber)
real = is_real(caliber)
result["mode"] = "real" if real else "simulated"
require_scopes(
{"olga": operator, "vera": viewer},
has={"olga": True, "vera": False},
hint=(
"start CALIBER with CALIBER_OPERATOR_USERS=admin,olga (olga is an operator who does "
"not own the queue, vera must not be one)"
),
)
# -- 1. The traces to review, and what Aria plans for 26 goals -----------------------------
trace_of = traces if traces is not None else seed_traces(assets)
check(
"the 30 flagged replies are in MLflow as traces, one per row",
len(replies) == REPLIES_EXPECTED
and set(trace_of) == {row["id"] for row in replies}
and len(set(trace_of.values())) == REPLIES_EXPECTED,
f"{len(trace_of)} traces",
)
check(
"every reply says why it was flagged",
{row["flag"] for row in replies} <= FLAGGED_REASONS,
sorted({row["flag"] for row in replies}),
)
check_goals_report(caliber, goals, GOALS_EXPECTED, check)
# -- 2. The canonical intent, through every question ----------------------------------------
drawn = caliber.aria.create_plan(INTENT, autonomy="ask_each")
plan_id = drawn.plan.plan_id
create_step, add_step = drawn.steps[0], drawn.steps[-1]
check(
"the intent draws review_queue.create then review_queue.add_items",
step_keys(drawn) == ["review_queue.create", "review_queue.add_items"],
plan_id,
)
check(
"the enqueue step's queue_id is wired from the create step, nothing else is",
add_step.extra.get("inputs")
== {"queue_id": {"$from_step": create_step.step_id, "path": "queue_id"}}
and add_step.depends_on == [create_step.step_id]
and not create_step.extra.get("inputs"),
)
caliber.aria.approve_plan(plan_id)
caliber.aria.execute_plan(plan_id)
walk(caliber, plan_id, [("input", queue_form), ("permission", "approve")])
enqueue_form = pending(caliber, plan_id)[0]
check(
"the enqueue form asks for trace ids only: the queue's id is already known",
enqueue_form.kind == "input" and enqueue_form.evidence["missing"] == ["trace_ids"],
enqueue_form.evidence["missing"],
)
trace_ids = [trace_of[row["id"]] for row in replies]
finished, _ = walk(
caliber,
plan_id,
[
("input", {"trace_ids": trace_ids, "assigned_to": "admin"}),
("permission", "approve"),
],
)
check(
"the plan completed with both steps done",
finished.plan.status == "completed" and set(step_status(finished).values()) == {"done"},
finished.plan.status,
)
queue_id = finished.steps[0].result["queue_id"]
check(
"the enqueue step reports 30 traces added to that queue",
finished.steps[1].result == {"queue_id": queue_id, "added": REPLIES_EXPECTED},
finished.steps[1].result,
)
detail = caliber.raw.get(f"/review-queues/{queue_id}")
queue, items = detail["queue"], detail["items"]
check(
"the queue is active with the typed name, five questions and its reviewers",
queue["status"] == "active"
and queue["name"] == queue_name
and [q["key"] for q in queue["questions"]]
== ["safety", "severity", "citation_ok", "tone_ok", "reviewer_notes"]
and queue["reviewers"] == queue_spec["reviewers"]
and queue["questions"][1]["options"] == ["low", "medium", "high"],
f"{queue_id} {queue['name']}",
)
check(
"it holds the 30 traces, all pending and assigned",
queue["item_count"] == REPLIES_EXPECTED
and queue["pending_count"] == REPLIES_EXPECTED
and {item["trace_id"] for item in items} == set(trace_ids)
and all(item["status"] == "pending" and item["assigned_to"] == "admin" for item in items),
f"{queue['item_count']} items, {queue['pending_count']} pending",
)
result.update(plan_id=plan_id, queue_id=queue_id)
# -- 3. Review twelve of them -------------------------------------------------------------
item_of = {item["trace_id"]: item["item_id"] for item in items}
reviewed_rows = [row for row in replies if row["id"] in REVIEWED_IDS]
for row in reviewed_rows:
caliber.review_queues.submit(queue_id, item_of[trace_of[row["id"]]], **row["review"])
after = caliber.raw.get(f"/review-queues/{queue_id}")
done = [item for item in after["items"] if item["status"] == "completed"]
check(
"twelve reviews are in: 12 completed, 18 still pending",
len(done) == REVIEWED and after["queue"]["pending_count"] == REPLIES_EXPECTED - REVIEWED,
f"{len(done)} completed, {after['queue']['pending_count']} pending",
)
wrong: list[str] = []
for row in reviewed_rows:
stored = {
a["name"]: a["value"]
for a in caliber.observability.trace(trace_of[row["id"]])["assessments"]
}
if stored != row["review"]:
wrong.append(f"{row['id']}: {stored}")
check(
"every answer is on its trace as an assessment, with the reviewer's value",
not wrong,
f"{REVIEWED} traces" if not wrong else wrong[:2],
)
labels = caliber.review_queues.alignment_examples(queue_id, question_key="safety")["examples"]
by_trace = {ex["provenance"]["trace_id"]: ex["label"] for ex in labels}
check(
"the safety answers are 12 labelled examples a judge can be checked against (lab 10)",
len(labels) == REVIEWED
and all(by_trace[trace_of[row["id"]]] is row["review"]["safety"] for row in reviewed_rows),
f"{sum(1 for v in by_trace.values() if v is False)} unsafe of {len(labels)}",
)
unsafe_seen = sum(1 for row in reviewed_rows if not row["review"]["safety"])
if real:
result["judge_alignment"] = _align_a_real_judge(
caliber, check, assets, labels, suffix=suffix
)
result["review"] = {
"reviewed": REVIEWED,
"pending": REPLIES_EXPECTED - REVIEWED,
"unsafe_in_reviewed": unsafe_seen,
}
# -- 4. What a review refuses -------------------------------------------------------------
spare = next(row for row in replies if row["id"] not in REVIEWED_IDS)
target = item_of[trace_of[spare["id"]]]
good = dict(spare["review"])
attempts = {
"a missing required answer": {k: v for k, v in good.items() if k != "citation_ok"},
"an answer of the wrong type": {**good, "safety": "yes"},
"an option the question does not have": {**good, "severity": "catastrophic"},
"an answer to a question that does not exist": {**good, "mood": "calm"},
}
refusals = {
label: refused(partial(caliber.review_queues.submit, queue_id, target, **answers))
for label, answers in attempts.items()
}
check(
"a review that does not fit the questions is refused (400) and names why",
all(e is not None and e.status_code == 400 for e in refusals.values()),
{label: _reason(e) for label, e in refusals.items()},
)
item_now = next(
i for i in caliber.raw.get(f"/review-queues/{queue_id}")["items"] if i["item_id"] == target
)
check("after four refusals the item is still pending", item_now["status"] == "pending")
resubmit = refused(
lambda: caliber.review_queues.submit(
queue_id, item_of[trace_of[reviewed_rows[0]["id"]]], **reviewed_rows[0]["review"]
)
)
check(
"a reviewed item cannot be reviewed again (409)",
resubmit is not None and resubmit.status_code == 409,
_reason(resubmit),
)
check(
"an account without the operator scope cannot review (403)",
isinstance(
refused(lambda: viewer.review_queues.submit(queue_id, target, **good)),
CaliberPermissionError,
),
)
olga_read = refused(lambda: operator.review_queues.get(queue_id))
olga_submit = refused(lambda: operator.review_queues.submit(queue_id, target, **good))
check(
"an operator the queue lists as a reviewer still cannot open or review it (404): "
"a personal queue belongs to its owner",
olga_read is not None
and olga_read.status_code == 404
and olga_submit is not None
and olga_submit.status_code == 404
and "olga" in queue["reviewers"],
"reviewers: " + ", ".join(queue["reviewers"]),
)
# A trace id that does not exist is queued; the reviewer finds out when they submit.
ghost = "tr-this-trace-does-not-exist"
caliber.review_queues.enqueue(queue_id, trace_ids=[ghost])
ghost_item = next(
i for i in caliber.raw.get(f"/review-queues/{queue_id}")["items"] if i["trace_id"] == ghost
)
ghost_submit = refused(
lambda: caliber.review_queues.submit(queue_id, ghost_item["item_id"], **good)
)
ghost_after = next(
i
for i in caliber.raw.get(f"/review-queues/{queue_id}")["items"]
if i["item_id"] == ghost_item["item_id"]
)
check(
"a trace id that does not exist is queued without complaint, and fails when reviewed "
"(502); the item stays pending",
ghost_item["status"] == "pending"
and ghost_submit is not None
and ghost_submit.status_code == 502
and "not found" in str(ghost_submit)
and ghost_after["status"] == "pending",
_reason(ghost_submit)[:70],
)
# -- 5. Plan refusals ---------------------------------------------------------------------
# 5a. Skip the queue: the enqueue step has nothing to act on and is skipped too.
skipped, _ = run_plan(caliber, INTENT, autonomy="approve_plan", moves=[("input", "skip")])
check(
"skipping the queue skips the enqueue step with it, and the plan completes",
skipped.plan.status == "completed"
and step_status(skipped)
== {"review_queue.create": "skipped", "review_queue.add_items": "skipped"}
and "step 1 (review_queue.create) was skipped" in str(skipped.steps[1].error),
str(skipped.steps[1].error),
)
# 5b. Create the queue, deny the enqueue: the queue is kept.
kept_name = f"{NAME_PREFIX}kept-{suffix}"
kept, _ = run_plan(
caliber,
INTENT,
autonomy="ask_each",
moves=[
("input", {**queue_form, "name": kept_name}),
("permission", "approve"),
("input", {"trace_ids": trace_ids[:2]}),
("permission", "deny"),
],
)
kept_queue = next(q for q in caliber.review_queues.list() if q.name == kept_name)
check(
"denying the enqueue leaves the queue created and empty; the plan completes",
kept.plan.status == "completed"
and step_status(kept)
== {"review_queue.create": "done", "review_queue.add_items": "skipped"}
and kept_queue.item_count == 0,
)
# 5c. Forms the schema refuses stay open; schemas the queue refuses fail the step.
first = start(caliber, INTENT, autonomy="approve_plan")
form = pending(caliber, first.plan.plan_id)[0]
bad_forms = {
"no questions": {"name": "x", "questions": []},
"an unknown field": {"name": "x", "questions": [{"key": "a", "title": "A?"}], "colour": 1},
"a question without a title": {"name": "x", "questions": [{"key": "a"}]},
"a question type that does not exist": {
"name": "x",
"questions": [{"key": "a", "title": "A?", "type": "likert"}],
},
}
form_refusals = {
label: refused(partial(caliber.aria.answer, form.interaction_id, inputs=inputs))
for label, inputs in bad_forms.items()
}
check(
"the form refuses no questions, an unknown field, an untitled question and a made-up "
"question type (409) and stays open",
all(e is not None and e.status_code == 409 for e in form_refusals.values())
and [i.status for i in caliber.aria.interactions(first.plan.plan_id)] == ["pending"],
{label: _reason(e) for label, e in form_refusals.items()},
)
walk(caliber, first.plan.plan_id, [("input", "skip")])
categorical, _ = run_plan(
caliber,
INTENT,
autonomy="approve_plan",
moves=[
(
"input",
{
"name": f"{NAME_PREFIX}no-options-{suffix}",
"questions": [{"key": "tone", "title": "Tone?", "type": "categorical"}],
},
)
],
)
check(
"a categorical question with no options passes the form and fails the step, naming it",
categorical.plan.status == "failed"
and str(categorical.steps[0].error)
== "invalid input: questions.0: categorical questions require a non-empty 'options' list",
categorical.steps[0].error,
)
taken, _ = run_plan(caliber, INTENT, autonomy="approve_plan", moves=[("input", queue_form)])
check(
"a queue name that is already taken fails its step",
taken.plan.status == "failed" and "is already in use" in str(taken.steps[0].error),
taken.steps[0].error,
)
rerun = refused(lambda: caliber.aria.execute_plan(taken.plan.plan_id))
check(
"a failed plan leaves the steps after it pending, and cannot be run again (409)",
step_status(taken)["review_queue.add_items"] == "pending"
and rerun is not None
and rerun.status_code == 409,
)
# 5d. A goal with no steps; a cancelled plan.
nothing = caliber.aria.create_plan("Write a poem about review season.")
approve_empty = refused(lambda: caliber.aria.approve_plan(nothing.plan.plan_id))
check(
"a goal with no steps is created with a warning and refused at approval (409)",
nothing.plan.step_count == 0
and bool(nothing.extra.get("warnings"))
and approve_empty is not None
and approve_empty.status_code == 409,
)
caliber.aria.update_plan(nothing.plan.plan_id, status="cancelled")
# 5e. Roles.
by_viewer = start(viewer, INTENT, autonomy="approve_plan")
check(
"a plan owned by an account without the operator scope fails at execute and creates "
"nothing",
by_viewer.plan.status == "failed"
and by_viewer.steps[0].error == "plan owner lacks required scope(s): operator",
by_viewer.steps[0].error,
)
own = start(caliber, INTENT, autonomy="approve_plan")
waiting = pending(caliber, own.plan.plan_id)[0]
other_answer = refused(lambda: operator.aria.answer(waiting.interaction_id, approved=False))
check(
"an operator who does not own the plan cannot answer its question (403)",
isinstance(other_answer, CaliberPermissionError),
_reason(other_answer),
)
walk(caliber, own.plan.plan_id, [("input", "skip")])
# -- 6. Ask Aria's chat, on a real stack ------------------------------------------------------
if real:
result["chat"] = _chat_for_real(caliber, check, suffix)
check.finish()
return result
def _align_a_real_judge(
caliber: CaliberClient,
check: Checks,
assets: Path,
labels: list[dict[str, Any]],
*,
suffix: str,
) -> dict[str, Any]:
"""Run a real safety judge over the 12 reviewed replies and compare it with the humans."""
spec = form_values(assets / "judges/reply-safety.judge.json")
judge = caliber.judges.create(
f"{NAME_PREFIX}{spec['name']}-{suffix}",
instructions=spec["instructions"],
feedback_value_type=spec["feedback_value_type"],
)
sendable = [{k: ex[k] for k in ("inputs", "outputs", "expectations", "label")} for ex in labels]
report = caliber.judges.alignment(judge.judge_id, examples=sendable)
per = report.per_example or []
judge_labels = [bool(r["judge_label"]) for r in per]
human_labels = [bool(r["human_label"]) for r in per]
agreed = sum(j == h for j, h in zip(judge_labels, human_labels, strict=True))
confusion = report.confusion or {}
check(
"the real judge scored all 12 reviewed replies (no row errored)",
report.n == REVIEWED and report.scored == REVIEWED and len(per) == REVIEWED,
f"n={report.n} scored={report.scored}",
)
check(
"the server's numbers are arithmetic over the labels: agreement and the confusion counts "
"add up",
report.agreement_rate is not None
and abs(agreed / REVIEWED - report.agreement_rate) < 5e-4
and sum(confusion.values()) == REVIEWED
and confusion.get("true_pos", 0) + confusion.get("false_neg", 0) == sum(human_labels),
confusion,
)
check(
f"the judge agrees with the reviewers: agreement >= {MIN_AGREEMENT:.0%}, kappa >= "
f"{MIN_KAPPA} (a judge that says one thing about everything has kappa 0)",
(report.agreement_rate or 0.0) >= MIN_AGREEMENT
and (report.cohen_kappa or 0.0) >= MIN_KAPPA,
f"agreement {report.agreement_rate}, kappa {report.cohen_kappa}",
)
caught = confusion.get("true_neg", 0)
unsafe = REVIEWED - sum(human_labels)
check(
"the judge flags at least half of the replies the reviewers called unsafe",
unsafe > 0 and caught * 2 >= unsafe,
f"{caught} of {unsafe}",
)
return {
"judge_id": judge.judge_id,
"n": report.n,
"agreement": report.agreement_rate,
"kappa": report.cohen_kappa,
"confusion": confusion,
}
def _chat_for_real(caliber: CaliberClient, check: Checks, suffix: str) -> dict[str, Any]:
"""Ask Aria (the chat, not the Plans page) acts in build / auto_all and only reads otherwise."""
acting = f"{NAME_PREFIX}chat-queue-{suffix}"
reading = f"{NAME_PREFIX}chat-manual-{suffix}"
spec = (
"with one pass_fail question: key safety, title 'Is the reply safe to send?'. "
"Then tell me its id."
)
def queue_names() -> set[str]:
return {q.name for q in caliber.review_queues.list()}
summary = check_chat_boundary(
caliber,
check,
tool="review_queue_create",
ask=f"Create a review queue named {acting} {spec}",
exists=lambda: acting in queue_names(),
absent_ask=f"Create a review queue named {reading} {spec}",
absent_exists=lambda: reading in queue_names(),
)
made = next((q for q in caliber.review_queues.list() if q.name == acting), None)
check(
"the chat's queue is active with the question that was asked for",
made is not None
and made.status == "active"
and [q["key"] for q in caliber.review_queues.get(made.queue_id).questions] == ["safety"],
made.queue_id if made else "",
)
return summary
def cleanup(caliber: CaliberClient) -> dict[str, int]:
"""Archive the review queues earlier runs created (names start ``cookbook-13-``)."""
archived = {"review_queues": 0, "judges": 0}
for queue in caliber.review_queues.list():
if queue.name.startswith(NAME_PREFIX):
caliber.review_queues.update(queue.queue_id, status="archived")
archived["review_queues"] += 1
for judge in caliber.judges.list():
if judge.name.startswith(NAME_PREFIX) and judge.status != "archived":
caliber.judges.update(judge.judge_id, status="archived")
archived["judges"] += 1
return archived
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
parser.add_argument("--cleanup", action="store_true", help="archive what earlier runs created")
parser.add_argument("--suffix", help="name suffix (default: a timestamp)")
args = parser.parse_args(argv)
base_url = os.environ["CALIBER_BASE_URL"]
password = env_password("COOKBOOK_ARIA_PASSWORD", DEFAULT_PASSWORD)
opened: list[CaliberClient] = []
with env_client(timeout=http_timeout()) as caliber:
try:
if args.cleanup:
print(json.dumps(cleanup(caliber), indent=2))
return 0
ensure_accounts(caliber, (OPERATOR_USER, VIEWER_USER), password)
clients = {}
for user in (OPERATOR_USER, VIEWER_USER):
clients[user] = CaliberClient(base_url, token=sign_in(base_url, user, password))
opened.append(clients[user])
result = run(
caliber,
operator=clients[OPERATOR_USER],
viewer=clients[VIEWER_USER],
suffix=args.suffix,
)
except (VerificationError, SetupError, CaliberAPIError) as exc:
print(f"\nVERIFICATION FAILED: {exc}", file=sys.stderr)
return 1
finally:
for client in opened:
client.close()
print(json.dumps(result, indent=2, sort_keys=True, default=str))
return 0
if __name__ == "__main__":
sys.exit(main())sdk/caliber-sdk/examples/cookbooks/cookbook_13_aria_review_queue.py — executed by the SDK example test suite.Cookbook 14 — Aria: Governance Starter Kit from Intent
State one sentence of intent to Aria and answer the seven questions its plan asks, so it creates a judge, a review queue and a test set (and skips the enqueue step, since no traces exist yet); then fill the test set with 30 cases, rerun the sentence under a lower autonomy level to show only the forms are asked, and provoke the refusals (a denied step that takes its dependent with it, a failure half way, an invalid judge, a goal with no steps, non-operator and non-owner accounts). It needs CALIBER_FEATURE_ARIA=true, an admin-scoped token and CALIBER_OPERATOR_USERS=admin,olga (the script also creates vera, a non-operator); no model is needed, and running the judge through Evaluations is expected to be refused (400) on a simulated provider, which the script verifies. It does not install a cookbook and does not use client.raw.
SDK surfaces: aria, judges, datasets, review_queues, evaluations, auth
- Draw a plan for each of the 28 goals in the dataset and compare it with the expected steps (every draft is cancelled, nothing runs).
- State the canonical intent under 'Stop before each change' and answer seven questions (three forms with an Approve each, then the enqueue form, skipped because there are no traces); check the judge, the review queue and the test set exist under three different names.
- Add the 30 cases of the dataset to the test set through
eval_datasets.add_example, check each stored row, and confirm that Evaluations are refused (400) without a real model. - Run the same sentence under 'Run everything it safely can' after changing the draft's autonomy, and check that only the four forms are asked and the same kit is built; a plan can no longer be edited after approval (409).
- Provoke the refusals: a denied queue skips the enqueue step with it, a taken queue name fails the plan after the judge was made, a judge with no evaluation variable fails before anything is made, a goal with no steps is refused at approval, and a non-operator or non-owner cannot run or answer the plan.
"""Cookbook 14: give Aria one sentence and get a judge, a test set and a review queue.
Runs the whole lab through the SDK against a live server and exits 0 only when every check below
holds. It is the API half of the lab README (docs-site/cookbooks/14-aria-governance-starter-kit/
README.md) and prints the same values the README tells you to expect.
export CALIBER_BASE_URL=http://127.0.0.1:5001 # the server root, not the /ajax-api path
export CALIBER_TOKEN=calpat_... # an ADMIN personal access token
PYTHONPATH=sdk/caliber-sdk caliber/.venv/bin/python \
-m examples.cookbooks.cookbook_14_aria_governance_starter_kit
The server needs ``CALIBER_FEATURE_ARIA=true`` and ``CALIBER_OPERATOR_USERS=admin,olga``; the script
also creates ``vera``, who is not an operator. Nothing in the planning needs a model: Aria's
planner is deterministic. The step that does, running the judge in Evaluations, has two modes, told
apart by ``GET /readiness``. On a simulated stack (the default) it is refused with a 400 and the
script verifies the refusal. On a stack started with
``scripts/cookbook-env.sh up NAME --flags cookbooks,aria --real-llm`` the script scores the 30
policy cases with the judge for real (an answerer prompt that sees the policy text), asserts
structure, ranges and the ``high-risk`` slice (never exact scores), and then checks the Ask Aria
chat on both sides of its permission boundary. That takes a few minutes and costs cents;
``COOKBOOK_ARIA_HTTP_TIMEOUT`` (seconds, default 900) bounds one request.
What it does, in order:
1. Draws a plan for each of the 28 goals in ``assets/dataset/goals.jsonl`` and compares it with the
dataset (nothing runs).
2. States the canonical intent under *Stop before each change* and answers the seven questions the
plan asks (three forms with an Approve each, then the enqueue form, which it skips because there
are no traces yet). Checks the judge, the review queue and the test set exist under three
different names.
3. Adds the 30 cases of ``assets/dataset/release-candidate-cases.jsonl`` to the test set and runs
it in Evaluations (refused on a simulated stack; judge-scored and checked by invariants on a
real one).
4. Runs the same sentence under *Run everything it safely can*, after changing the autonomy of the
draft, and shows that only the forms are asked.
5. Provokes the refusals: a denied step that takes its dependent with it, a failure half way (what
was made stays made), a plan with no steps, an account without the operator scope.
6. Real stack only: Ask Aria's chat creates a review queue in a ``build`` / ``auto_all`` session and
is not offered the tool in the default session.
``--cleanup`` archives what earlier runs created (and deletes the prompt of a real run).
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import time
from collections import Counter
from collections.abc import Callable
from pathlib import Path
from typing import Any
from caliber_sdk import CaliberClient
from caliber_sdk.errors import CaliberAPIError, CaliberPermissionError
from examples.cookbooks._aria_lab import (
GROUNDED_PROMPT,
Checks,
Report,
SetupError,
VerificationError,
check_chat_boundary,
check_goals_report,
check_judged_evaluation,
create_prompt,
ensure_accounts,
env_password,
form_values,
http_timeout,
is_real,
judge_rate,
load_jsonl,
pending,
refused,
require_admin_and_aria,
require_scopes,
run_judged_evaluation,
run_plan,
sign_in,
start,
step_keys,
step_status,
walk,
)
from examples.cookbooks._helpers import env_client
NAME_PREFIX = "cookbook-14-"
DEFAULT_PASSWORD = "cookbook-aria-lab-passphrase"
OPERATOR_USER = "olga"
VIEWER_USER = "vera"
INTENT = (
"Stand up our governance starter kit: a judge for answer faithfulness, an eval dataset to "
"score against, and a review queue for human checks."
)
KIT = ["judge.create", "review_queue.create", "eval_dataset.create", "review_queue.add_items"]
GOALS_EXPECTED = 28
CASES_EXPECTED = 30
HIGH_RISK_EXPECTED = 5
#: A real run: the share of the 30 policy cases the judge finds faithful must reach this. A grounded
#: answerer typically scores far higher (README); the bar only rules out a judge or an answerer
#: that does not work.
MIN_FAITHFUL_RATE = float(os.environ.get("COOKBOOK_14_MIN_RATE", "0.6"))
def default_assets_dir() -> Path:
return Path(
os.environ.get(
"COOKBOOK_14_ASSETS",
Path(__file__).resolve().parents[4]
/ "docs-site/cookbooks/14-aria-governance-starter-kit/assets",
)
)
def _reason(error: CaliberAPIError | None) -> str:
return str(error).split("] ", 1)[1].split(" (", 1)[0] if error else ""
def run(
caliber: CaliberClient,
*,
operator: CaliberClient,
viewer: CaliberClient,
suffix: str | None = None,
assets: Path | None = None,
report: Report = print,
sleep: Callable[[float], None] = time.sleep,
) -> dict[str, Any]:
"""Run the whole lab. ``caliber`` is the admin's client; ``operator`` and ``viewer`` are the
two other accounts' clients."""
assets = assets or default_assets_dir()
suffix = suffix or time.strftime("%Y%m%d-%H%M%S")
check = Checks(report)
result: dict[str, Any] = {"suffix": suffix}
goals = load_jsonl(assets / "dataset/goals.jsonl")
cases = load_jsonl(assets / "dataset/release-candidate-cases.jsonl")
judge_spec = form_values(assets / "judges/answer-faithfulness.judge.json")
queue_spec = form_values(assets / "review-queues/governance-review.queue.json")
dataset_spec = form_values(assets / "datasets/release-candidates.dataset.json")
def forms(tag: str) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]:
"""The three forms with names that cannot collide with another run of the kit."""
stem = f"{NAME_PREFIX}{{}}-{tag}-{suffix}"
return (
{**judge_spec, "name": stem.format(judge_spec["name"])},
{**queue_spec, "name": stem.format(queue_spec["name"])},
{**dataset_spec, "name": stem.format(dataset_spec["name"])},
)
def names() -> dict[str, set[str]]:
return {
"judges": {j.name for j in caliber.judges.list()},
"queues": {q.name for q in caliber.review_queues.list()},
"test_sets": {d.name for d in caliber.eval_datasets.list()},
}
require_admin_and_aria(caliber)
real = is_real(caliber)
result["mode"] = "real" if real else "simulated"
prompts: list[str] = []
result["prompts"] = prompts
require_scopes(
{"olga": operator, "vera": viewer},
has={"olga": True, "vera": False},
hint=(
"start CALIBER with CALIBER_OPERATOR_USERS=admin,olga (olga is an operator who does "
"not own the plan, vera must not be one)"
),
)
# -- 1. What Aria plans for 28 goals ------------------------------------------------------
check_goals_report(caliber, goals, GOALS_EXPECTED, check)
# -- 2. The canonical intent under "Stop before each change" ------------------------------
judge_form, queue_form, dataset_form = forms("kit")
drawn = caliber.aria.create_plan(INTENT, autonomy="ask_each")
plan_id = drawn.plan.plan_id
check(
"the intent draws judge, review queue, test set, then the enqueue step (registry order)",
step_keys(drawn) == KIT,
plan_id,
)
queue_step = drawn.steps[1]
wired = {s.capability_key: s.extra.get("inputs") for s in drawn.steps}
check(
"only the enqueue step has a wired input (the queue's id); the three names are asked for",
wired
== {
"judge.create": {},
"review_queue.create": {},
"eval_dataset.create": {},
"review_queue.add_items": {
"queue_id": {"$from_step": queue_step.step_id, "path": "queue_id"}
},
},
)
caliber.aria.approve_plan(plan_id)
caliber.aria.execute_plan(plan_id)
finished, trail = walk(
caliber,
plan_id,
[
("input", judge_form),
("permission", "approve"),
("input", queue_form),
("permission", "approve"),
("input", dataset_form),
("permission", "approve"),
("input", "skip"),
],
)
check(
"the plan asked 7 questions: a form and an approval for each of the three, then the "
"enqueue form",
trail
== [
("input", "judge.create"),
("permission", "judge.create"),
("input", "review_queue.create"),
("permission", "review_queue.create"),
("input", "eval_dataset.create"),
("permission", "eval_dataset.create"),
("input", "review_queue.add_items"),
],
)
check(
"the plan completed: three steps done, the enqueue step skipped (no traces yet)",
finished.plan.status == "completed"
and step_status(finished)
== {
"judge.create": "done",
"review_queue.create": "done",
"eval_dataset.create": "done",
"review_queue.add_items": "skipped",
},
finished.plan.status,
)
results = {s.capability_key: s.result for s in finished.steps}
judge = caliber.judges.get(results["judge.create"]["judge_id"])
queue = caliber.review_queues.get(results["review_queue.create"]["queue_id"])
dataset = caliber.eval_datasets.get(results["eval_dataset.create"]["dataset_id"])
check(
"the judge, the review queue and the test set exist under three different names",
len({judge.name, queue.name, dataset.name}) == 3
and (judge.name, queue.name, dataset.name)
== (judge_form["name"], queue_form["name"], dataset_form["name"]),
f"{judge.judge_id} {queue.queue_id} {dataset.dataset_id}",
)
check(
"the judge is active and boolean, the queue has its four questions, the test set is empty "
"at version 1",
judge.status == "active"
and judge.feedback_value_type == "bool"
and queue.status == "active"
and [q["key"] for q in queue.questions] == ["faithful", "citation_ok", "tone", "notes"]
and queue.item_count == 0
and dataset.version == 1
and not caliber.eval_datasets.examples(dataset.dataset_id),
)
result.update(
plan_id=plan_id,
judge_id=judge.judge_id,
queue_id=queue.queue_id,
dataset_id=dataset.dataset_id,
)
# -- 3. Fill the test set -----------------------------------------------------------------
for case in cases:
caliber.eval_datasets.add_example(
dataset.dataset_id, input=case["input"], expected=case["expected"], tags=case["tags"]
)
rows = caliber.eval_datasets.examples(dataset.dataset_id)
by_question = {row.input["question"]: row for row in rows}
check(
"the test set holds the 30 cases, one version per row",
len(cases) == CASES_EXPECTED
and len(rows) == CASES_EXPECTED
and caliber.eval_datasets.get(dataset.dataset_id).version == 1 + CASES_EXPECTED,
f"{len(rows)} rows, version {caliber.eval_datasets.get(dataset.dataset_id).version}",
)
check(
"every stored row is the file's row (input, expected answer, tags)",
all(
by_question[c["input"]["question"]].input == c["input"]
and by_question[c["input"]["question"]].expected == c["expected"]
and by_question[c["input"]["question"]].extra.get("tags") == c["tags"]
for c in cases
),
)
if real:
result["evaluation"] = _evaluate_for_real(
caliber, check, dataset.dataset_id, judge.judge_id, suffix=suffix, prompts=prompts
)
else:
refusal = refused(
lambda: caliber.evaluations.create(dataset.dataset_id, scorers=["non_empty"])
)
check(
"Evaluations are refused without a real model (400): the judge cannot run here",
refusal is not None
and refusal.status_code == 400
and "real LLM provider" in str(refusal),
"simulated stack",
)
result["evaluation"] = "refused (simulated provider)"
result["cases"] = {
"count": len(cases),
"categories": sorted({c["tags"][0] for c in cases}),
"high_risk": sum(1 for c in cases if "high-risk" in c["tags"]),
}
# -- 4. The same sentence, asking less ----------------------------------------------------
auto_judge, auto_queue, auto_dataset = forms("auto")
draft = caliber.aria.create_plan(INTENT)
check(
"a plan is drawn under the default autonomy ('Review the plan, then run')",
draft.plan.autonomy == "approve_plan",
)
switched = caliber.aria.update_plan(draft.plan.plan_id, autonomy="auto_guarded")
check(
"a draft's autonomy can be changed before it is approved",
switched.plan.autonomy == "auto_guarded" and switched.plan.status == "draft",
)
caliber.aria.approve_plan(draft.plan.plan_id)
edit_after_approval = refused(
lambda: caliber.aria.update_plan(draft.plan.plan_id, autonomy="ask_each")
)
check(
"after approval it can no longer be changed (409)",
edit_after_approval is not None and edit_after_approval.status_code == 409,
_reason(edit_after_approval),
)
caliber.aria.execute_plan(draft.plan.plan_id)
second, _ = walk(
caliber,
draft.plan.plan_id,
[
("input", auto_judge),
("input", auto_queue),
("input", auto_dataset),
("input", "skip"),
],
)
asked = Counter(i.kind for i in caliber.aria.interactions(draft.plan.plan_id))
first_asked = Counter(i.kind for i in caliber.aria.interactions(plan_id))
check(
"under 'Run everything it safely can' only the four forms are asked, no approvals; the "
"same kit is built",
second.plan.status == "completed"
and step_status(second) == step_status(finished)
and asked == Counter({"input": 4})
and first_asked == Counter({"input": 4, "permission": 3}),
f"ask_each: {dict(first_asked)}; auto_guarded: {dict(asked)}",
)
check(
"both kits are in the deployment, six artifacts under six names",
{auto_judge["name"], judge_form["name"]} <= names()["judges"]
and {auto_queue["name"], queue_form["name"]} <= names()["queues"]
and {auto_dataset["name"], dataset_form["name"]} <= names()["test_sets"],
)
# -- 5. Refusals --------------------------------------------------------------------------
# 5a. Deny the queue: the enqueue goes with it, the test set still gets made.
d_judge, d_queue, d_dataset = forms("denied")
denied, _ = run_plan(
caliber,
INTENT,
autonomy="ask_each",
moves=[
("input", d_judge),
("permission", "approve"),
("input", d_queue),
("permission", "deny"),
("input", d_dataset),
("permission", "approve"),
],
)
now = names()
check(
"denying the queue skips it and the enqueue step with it (never asked); the judge and the "
"test set are made",
denied.plan.status == "completed"
and step_status(denied)
== {
"judge.create": "done",
"review_queue.create": "skipped",
"eval_dataset.create": "done",
"review_queue.add_items": "skipped",
}
and d_judge["name"] in now["judges"]
and d_dataset["name"] in now["test_sets"]
and d_queue["name"] not in now["queues"],
str(denied.steps[3].error),
)
# 5b. A failure half way stops the plan; what was already made stays made.
f_judge, _unused_queue, f_dataset = forms("halfway")
halfway, _ = run_plan(
caliber,
INTENT,
autonomy="approve_plan",
moves=[("input", f_judge), ("input", {**queue_form, "name": queue_form["name"]})],
)
now = names()
check(
"a queue name that is taken fails the plan after the judge was made: the judge stays, "
"the steps after it never run",
halfway.plan.status == "failed"
and step_status(halfway)
== {
"judge.create": "done",
"review_queue.create": "failed",
"eval_dataset.create": "pending",
"review_queue.add_items": "pending",
}
and "is already in use" in str(halfway.steps[1].error)
and f_judge["name"] in now["judges"]
and f_dataset["name"] not in now["test_sets"],
halfway.steps[1].error,
)
broken_judge, _, broken_dataset = forms("broken")
broken, _ = run_plan(
caliber,
INTENT,
autonomy="approve_plan",
moves=[
(
"input",
{**broken_judge, "instructions": "Is the answer {{ faithful }} to the evidence?"},
)
],
)
check(
"a judge with no evaluation variable fails the plan before anything else is made",
broken.plan.status == "failed"
and str(broken.steps[0].error).startswith(
"invalid input: instructions: instructions must reference"
)
and set(step_status(broken).values()) == {"failed", "pending"}
and broken_judge["name"] not in names()["judges"]
and broken_dataset["name"] not in names()["test_sets"],
str(broken.steps[0].error)[:80],
)
# 5c. A goal with no steps.
nothing = caliber.aria.create_plan("Create the governance kit.")
approve_empty = refused(lambda: caliber.aria.approve_plan(nothing.plan.plan_id))
check(
"a goal with no steps (governance is not a domain word) is refused at approval (409)",
nothing.plan.step_count == 0
and bool(nothing.extra.get("warnings"))
and approve_empty is not None
and approve_empty.status_code == 409,
)
caliber.aria.update_plan(nothing.plan.plan_id, status="cancelled")
# 5d. Roles.
by_viewer = start(viewer, INTENT, autonomy="approve_plan")
check(
"a plan owned by an account without the operator scope fails at execute and creates "
"nothing",
by_viewer.plan.status == "failed"
and by_viewer.steps[0].error == "plan owner lacks required scope(s): operator"
and not any(s.status == "done" for s in by_viewer.steps),
by_viewer.steps[0].error,
)
own = start(caliber, INTENT, autonomy="approve_plan")
waiting = pending(caliber, own.plan.plan_id)[0]
other_answer = refused(lambda: operator.aria.answer(waiting.interaction_id, approved=False))
other_read = refused(lambda: operator.aria.get_plan(own.plan.plan_id))
check(
"an operator who does not own the plan cannot answer its question (403) or read it (404)",
isinstance(other_answer, CaliberPermissionError)
and other_read is not None
and other_read.status_code == 404,
_reason(other_answer),
)
skipped_all, skipped_trail = walk(
caliber, own.plan.plan_id, [("input", "skip"), ("input", "skip"), ("input", "skip")]
)
check(
"skipping the three forms skips everything: the enqueue step is never asked (its queue was "
"skipped), and the plan completes with nothing made",
skipped_all.plan.status == "completed"
and set(step_status(skipped_all).values()) == {"skipped"}
and [capability for _, capability in skipped_trail]
== ["judge.create", "review_queue.create", "eval_dataset.create"],
step_status(skipped_all),
)
# -- 6. Ask Aria's chat, on a real stack ------------------------------------------------------
if real:
result["chat"] = _chat_for_real(caliber, check, suffix)
check.finish()
return result
def _evaluate_for_real(
caliber: CaliberClient,
check: Checks,
dataset_id: str,
judge_id: str,
*,
suffix: str,
prompts: list[str],
) -> dict[str, Any]:
"""Score the 30 policy cases with the judge, the answers coming from a grounded prompt."""
prompt_ref = create_prompt(caliber, f"{NAME_PREFIX}grounded-answer-{suffix}", GROUNDED_PROMPT)
prompts.append(prompt_ref.split("@")[0])
run = run_judged_evaluation(
caliber, dataset_id, judge_id, prompt_ref=prompt_ref, label=f"release candidate {suffix}"
)
summary = check_judged_evaluation(
check, "release candidate", run, judge_id, rows=CASES_EXPECTED, prompt_ref=prompt_ref
)
rate = judge_rate(run, judge_id) or 0.0
check(
f"the judge finds at least {MIN_FAITHFUL_RATE:.0%} of the grounded answers faithful",
rate >= MIN_FAITHFUL_RATE,
f"{rate:.0%}",
)
slices = (run.evidence or {}).get("slices") or {}
check(
f"the evidence slices the run by tag, with the {HIGH_RISK_EXPECTED} high-risk cases apart",
(slices.get("high-risk") or {}).get("n_examples") == HIGH_RISK_EXPECTED,
{tag: (v or {}).get("n_examples") for tag, v in sorted(slices.items())},
)
summary["high_risk_rows"] = (slices.get("high-risk") or {}).get("n_examples")
return summary
def _chat_for_real(caliber: CaliberClient, check: Checks, suffix: str) -> dict[str, Any]:
"""Ask Aria (the chat, not the Plans page) acts in build / auto_all and only reads otherwise."""
acting = f"{NAME_PREFIX}chat-queue-{suffix}"
reading = f"{NAME_PREFIX}chat-manual-{suffix}"
spec = (
"with one pass_fail question: key faithful, title 'Is the answer faithful to the policy?'. "
"Then tell me its id."
)
def queue_names() -> set[str]:
return {q.name for q in caliber.review_queues.list()}
summary = check_chat_boundary(
caliber,
check,
tool="review_queue_create",
ask=f"Create a review queue named {acting} {spec}",
exists=lambda: acting in queue_names(),
absent_ask=f"Create a review queue named {reading} {spec}",
absent_exists=lambda: reading in queue_names(),
)
made = next((q for q in caliber.review_queues.list() if q.name == acting), None)
check(
"the chat's queue is active with the question that was asked for",
made is not None
and made.status == "active"
and [q["key"] for q in caliber.review_queues.get(made.queue_id).questions] == ["faithful"],
made.queue_id if made else "",
)
return summary
def cleanup(caliber: CaliberClient) -> dict[str, int]:
"""Archive the judges, queues and test sets earlier runs created (names ``cookbook-14-``)."""
archived = {"judges": 0, "review_queues": 0, "test_sets": 0, "prompts": 0}
for judge in caliber.judges.list():
if judge.name.startswith(NAME_PREFIX) and judge.status != "archived":
caliber.judges.update(judge.judge_id, status="archived")
archived["judges"] += 1
for queue in caliber.review_queues.list():
if queue.name.startswith(NAME_PREFIX):
caliber.review_queues.update(queue.queue_id, status="archived")
archived["review_queues"] += 1
for dataset in caliber.eval_datasets.list():
if dataset.name.startswith(NAME_PREFIX) and dataset.status != "archived":
caliber.eval_datasets.update(dataset.dataset_id, status="archived")
archived["test_sets"] += 1
for prompt in caliber.prompts.list():
if prompt.prompt_name.startswith(NAME_PREFIX):
caliber.prompts.delete(prompt.prompt_name)
archived["prompts"] += 1
return archived
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
parser.add_argument("--cleanup", action="store_true", help="archive what earlier runs created")
parser.add_argument("--suffix", help="name suffix (default: a timestamp)")
args = parser.parse_args(argv)
base_url = os.environ["CALIBER_BASE_URL"]
password = env_password("COOKBOOK_ARIA_PASSWORD", DEFAULT_PASSWORD)
opened: list[CaliberClient] = []
with env_client(timeout=http_timeout()) as caliber:
try:
if args.cleanup:
print(json.dumps(cleanup(caliber), indent=2))
return 0
ensure_accounts(caliber, (OPERATOR_USER, VIEWER_USER), password)
clients = {}
for user in (OPERATOR_USER, VIEWER_USER):
clients[user] = CaliberClient(base_url, token=sign_in(base_url, user, password))
opened.append(clients[user])
result = run(
caliber,
operator=clients[OPERATOR_USER],
viewer=clients[VIEWER_USER],
suffix=args.suffix,
)
except (VerificationError, SetupError, CaliberAPIError) as exc:
print(f"\nVERIFICATION FAILED: {exc}", file=sys.stderr)
return 1
finally:
for client in opened:
client.close()
print(json.dumps(result, indent=2, sort_keys=True, default=str))
return 0
if __name__ == "__main__":
sys.exit(main())sdk/caliber-sdk/examples/cookbooks/cookbook_14_aria_governance_starter_kit.py — executed by the SDK example test suite.Cookbook 15 — Aria: Triage & Recalibrate Loop
Register the existing subject Aria remediates (two tools, a published support workflow with its 30-case test set as deploy gate, an agent), seed 12 weak runs as MLflow traces, then state one sentence of intent and answer six questions so Aria creates a triage queue, enqueues the 12 traces and starts a real workflow calibration; the plan parks in waiting_job, is resumed by the plan worker (falling back to aria.poll_plan) and must end where the job ended, after which a reviewer triages three runs and the refusals are provoked. It needs CALIBER_FEATURE_ARIA=true, an admin-scoped token, CALIBER_OPERATOR_USERS=admin,olga (the script also creates vera, a non-operator), mlflow with MLFLOW_TRACKING_URI, and the server's plan and refinement workers running; no model is needed, and on a simulated deployment the calibration job ends rejected (gain 0.000, below the 0.02 gate) so the plan ends failed with that reason (a real model may reach candidate_ready, and the script accepts either). It does not install a cookbook; it reads the queue back with client.raw (GET /review-queues/{id}) twice.
SDK surfaces: aria, review_queues, observability, workflows, datasets, tools, jobs, auth
- Register the two tools, import and publish the support workflow with its test set as the deploy gate, and register an agent (the existing subject Aria remediates); write the 12 weak runs to MLflow as traces and check the planner's drawn plan for each of the 28 goals.
- State the canonical intent and answer six questions (the queue's fields, an Approve, the 12 trace ids, an Approve, the workflow and agent ids, an Approve); the last Approve enqueues a calibration job and parks the plan as
runningwith the stepwaiting_job, and a parked plan cannot be edited (409). - Wait for the plan worker to resume the plan (or advance it with
aria.poll_plan), then check it ends where the job ended, polling a finished plan changes nothing, and the job replayed 20 of the gate's 30 cases and reports its baseline. - Check the triage queue holds the 12 flagged traces pending, then have a reviewer triage three of them and verify the verdict, failure mode and expected answer land on their traces.
- Provoke the refusals: an unknown workflow, an unregistered agent and a workflow with no deploy-gate test set fail at once and queue no job, malformed forms stay open (409), a denied calibration queues nothing, and a non-operator or non-owner cannot run, answer or poll a plan.
"""Cookbook 15: give Aria one sentence about weak runs; it queues them for review and calibrates.
Runs the whole lab through the SDK against a live server and exits 0 only when every check below
holds. It is the API half of the lab README (docs-site/cookbooks/15-aria-triage-recalibrate-loop/
README.md) and prints the same values the README tells you to expect.
export CALIBER_BASE_URL=http://127.0.0.1:5001 # the server root, not the /ajax-api path
export CALIBER_TOKEN=calpat_... # an ADMIN personal access token
export MLFLOW_TRACKING_URI=http://127.0.0.1:5000 # where CALIBER's traces live
PYTHONPATH=sdk/caliber-sdk caliber/.venv/bin/python \
-m examples.cookbooks.cookbook_15_aria_triage_recalibrate_loop
The server needs ``CALIBER_FEATURE_ARIA=true``, ``CALIBER_OPERATOR_USERS=admin,olga``, and its
background workers on (the plan worker resumes the parked plan, the refinement worker runs the
calibration); the script also creates ``vera``, who is not an operator. Nothing here needs a model:
Aria's planner is deterministic and the calibration replays the test set through a simulated
executor. That is also why the calibration finds nothing to apply on a simulated deployment (see
below).
What it does, in order:
1. Registers the two tools, imports and publishes the support workflow with its test set as the
deploy gate, and registers an agent: the *existing* things Aria remediates (it creates none of
them). Writes the 12 weak runs of ``assets/dataset/support-runs.jsonl`` to MLflow as traces, and
draws a plan for each of the 28 goals in ``assets/dataset/goals.jsonl`` (nothing runs).
2. States the canonical intent and answers six questions: the queue's fields, an Approve, the 12
trace ids, an Approve, the workflow and agent ids, an Approve. The last Approve enqueues a real
calibration job and the plan *parks*: ``running``, the step ``waiting_job``. It then waits for
the plan worker to resume it (falling back to ``POST /aria/plans/{id}/poll``) and checks that the
plan ends where the job ended.
3. Has a reviewer triage three of the flagged runs, with feedback and an expectation.
4. Provokes the refusals: a step that fails at once (an unknown workflow, an unregistered agent, a
workflow with no test set), a denied calibration, a parked plan that cannot be edited, a plan
with no steps, an account without the operator scope.
On a simulated deployment the calibration job ends ``rejected``: the fake executor gives a candidate
the same outputs as the baseline, so the quality gain is 0.000, below the 0.02 it must clear, and
the plan ends ``failed`` with that reason. On a stack with a real model the job can reach
``candidate_ready`` and the plan completes; the script accepts either, and asserts that the plan
mirrors the job.
``--cleanup`` archives what earlier runs created.
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import os
import sys
import time
from collections.abc import Callable
from functools import partial
from pathlib import Path
from typing import Any
from caliber_sdk import CaliberClient
from caliber_sdk.errors import CaliberAPIError, CaliberPermissionError
from examples.cookbooks._aria_lab import (
Checks,
Report,
SetupError,
VerificationError,
check_chat_boundary,
check_goals_report,
ensure_accounts,
env_password,
form_values,
http_timeout,
is_real,
load_json,
load_jsonl,
pending,
refused,
require_admin_and_aria,
require_scopes,
run_plan,
sign_in,
start,
step_keys,
step_status,
walk,
)
from examples.cookbooks._helpers import env_client
NAME_PREFIX = "cookbook-15-"
DEFAULT_PASSWORD = "cookbook-aria-lab-passphrase"
OPERATOR_USER = "olga"
VIEWER_USER = "vera"
INTENT = (
"Our workflow's recent runs look weak - set up a review queue for the flagged traces and "
"kick off a workflow calibration."
)
GOALS_EXPECTED = 28
RUNS_EXPECTED = 30
WEAK_EXPECTED = 12
TRIAGED = ("S19", "S21", "S24") # the flagged runs a reviewer triages by hand
#: How long the plan worker gets to resume the parked plan before the script calls ``poll``.
WORKER_PATIENCE_SECONDS = 75.0
#: The same on a stack with a real model, where the calibration job takes minutes.
REAL_PATIENCE_SECONDS = 1800.0
TERMINAL = {"completed", "failed", "cancelled"}
def default_assets_dir() -> Path:
return Path(
os.environ.get(
"COOKBOOK_15_ASSETS",
Path(__file__).resolve().parents[4]
/ "docs-site/cookbooks/15-aria-triage-recalibrate-loop/assets",
)
)
def seed_traces(assets: Path) -> dict[str, str]:
"""Write the 12 weak runs as traces (needs ``mlflow`` and ``MLFLOW_TRACKING_URI``)."""
spec = importlib.util.spec_from_file_location(
"cookbook15_seed_traces", assets / "seed_traces.py"
)
if spec is None or spec.loader is None:
raise SetupError(f"{assets / 'seed_traces.py'} not found")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return dict(module.seed(assets / "dataset" / "support-runs.jsonl"))
def _reason(error: CaliberAPIError | None) -> str:
return str(error).split("] ", 1)[1].split(" (", 1)[0] if error else ""
def load_subject_setup(assets: Path) -> Any:
"""The lab's ``assets/setup_subject.py`` as a module (registers the tools, imports the workflow
and its test set, registers an agent)."""
spec = importlib.util.spec_from_file_location(
"cookbook15_setup_subject", assets / "setup_subject.py"
)
if spec is None or spec.loader is None:
raise SetupError(f"{assets / 'setup_subject.py'} not found")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def wait_for_resume(
caliber: CaliberClient,
plan_id: str,
*,
patience: float,
sleep: Callable[[float], None],
clock: Callable[[], float] = time.monotonic,
) -> tuple[Any, str]:
"""Wait for a parked plan to reach a terminal state.
Gives the plan worker ``patience`` seconds to do it on its own; after that the script advances
the plan itself with ``POST /aria/plans/{id}/poll``, which is the same thing on demand. Returns
the plan and who advanced it (``"worker"`` or ``"poll"``).
"""
started = clock()
detail = caliber.aria.get_plan(plan_id)
while detail.plan.status not in TERMINAL:
if clock() - started > patience:
for _ in range(60):
detail = caliber.aria.poll_plan(plan_id)
if detail.plan.status in TERMINAL:
return detail, "poll"
sleep(2)
return detail, "poll"
sleep(3)
detail = caliber.aria.get_plan(plan_id)
return detail, "worker"
def run(
caliber: CaliberClient,
*,
operator: CaliberClient,
viewer: CaliberClient,
suffix: str | None = None,
assets: Path | None = None,
traces: dict[str, str] | None = None,
report: Report = print,
sleep: Callable[[float], None] = time.sleep,
patience: float | None = None,
) -> dict[str, Any]:
"""Run the whole lab. ``caliber`` is the admin's client (the plan's owner and the reviewer);
``operator`` and ``viewer`` are the two other accounts' clients."""
assets = assets or default_assets_dir()
suffix = suffix or time.strftime("%Y%m%d-%H%M%S")
check = Checks(report)
result: dict[str, Any] = {"suffix": suffix}
goals = load_jsonl(assets / "dataset/goals.jsonl")
runs = load_jsonl(assets / "dataset/support-runs.jsonl")
weak = [row for row in runs if row["weak"]]
queue_spec = form_values(assets / "review-queues/triage-review.queue.json")
queue_form = {**queue_spec, "name": f"{NAME_PREFIX}{queue_spec['name']}-{suffix}"}
admin_id = require_admin_and_aria(caliber)
real = is_real(caliber)
result["mode"] = "real" if real else "simulated"
if patience is None:
# A simulated calibration is over in seconds; a real one replays the test set through a
# model (about 80 workflow runs, so minutes). The worker resumes the plan either way.
patience = float(
os.environ.get(
"COOKBOOK_15_CALIBRATION_TIMEOUT",
REAL_PATIENCE_SECONDS if real else WORKER_PATIENCE_SECONDS,
)
)
require_scopes(
{"olga": operator, "vera": viewer},
has={"olga": True, "vera": False},
hint=(
"start CALIBER with CALIBER_OPERATOR_USERS=admin,olga (olga is an operator who does "
"not own the plan, vera must not be one)"
),
)
# -- 1. The things Aria remediates (it creates none of them) ------------------------------
subject = load_subject_setup(assets).setup(caliber, suffix, assets)
workflow_id, agent_id = subject["workflow_id"], subject["agent_id"]
gate_name, gate_id = subject["gate_name"], subject["dataset_id"]
stored = caliber.workflows.versions.get(subject["version_id"]).manifest
gate_ref = next(iter(stored["deploy_gates"].values()))["dataset_ref"]
check(
"the two tools are registered, the workflow is imported and published with the 30-case "
"test set as its deploy gate, and an agent is registered",
subject["tools"] == ["get_order", "lookup_policy"]
and caliber.workflows.versions.get(subject["version_id"]).status == "published"
and stored["artifacts"]["eval_datasets"][gate_ref]["dataset_name"] == gate_name
and len(caliber.eval_datasets.examples(gate_id)) == RUNS_EXPECTED,
f"{workflow_id}, gate '{gate_name}'",
)
result.update(workflow_id=workflow_id, agent_id=agent_id)
trace_of = traces if traces is not None else seed_traces(assets)
check(
"the recorded runs are consistent: a run is weak exactly when it skipped a tool its "
"question needs",
len(runs) == RUNS_EXPECTED
and len(weak) == WEAK_EXPECTED
and all(
row["weak"] == (not set(row["required_tools"]) <= set(row["tools_called"]))
for row in runs
),
f"{len(weak)} weak of {len(runs)}",
)
check(
"the 12 weak runs are in MLflow as traces, one per run",
set(trace_of) == {row["id"] for row in weak}
and len(set(trace_of.values())) == WEAK_EXPECTED,
f"{len(trace_of)} traces",
)
check_goals_report(caliber, goals, GOALS_EXPECTED, check)
# -- 2. The canonical intent: forms, approvals, and a plan that parks on a job ------------
drawn = caliber.aria.create_plan(INTENT, autonomy="ask_each")
plan_id = drawn.plan.plan_id
create_step = drawn.steps[0]
check(
"the intent draws review_queue.create, review_queue.add_items, workflow.calibrate",
step_keys(drawn) == ["review_queue.create", "review_queue.add_items", "workflow.calibrate"],
plan_id,
)
check(
"only the enqueue step's queue_id is wired (from the create step); the calibrate step "
"depends on nothing",
[s.extra.get("inputs") for s in drawn.steps]
== [{}, {"queue_id": {"$from_step": create_step.step_id, "path": "queue_id"}}, {}]
and drawn.steps[2].depends_on == [],
)
caliber.aria.approve_plan(plan_id)
caliber.aria.execute_plan(plan_id)
flagged_ids = [trace_of[row["id"]] for row in weak]
_, first_trail = walk(
caliber,
plan_id,
[
("input", queue_form),
("permission", "approve"),
("input", {"trace_ids": flagged_ids, "assigned_to": admin_id}),
("permission", "approve"),
(
"input",
{"workflow_id": workflow_id, "agent_id": agent_id},
),
],
)
parked_before = caliber.aria.get_plan(plan_id)
check(
"before the last approval the plan has made the queue and queued the 12 traces, and the "
"calibration has not started",
step_status(parked_before)
== {
"review_queue.create": "done",
"review_queue.add_items": "done",
"workflow.calibrate": "waiting_input",
}
and parked_before.steps[1].result["added"] == WEAK_EXPECTED,
parked_before.steps[1].result,
)
jobs_before = {job.job_id for job in caliber.jobs.list()}
parked, _ = walk(caliber, plan_id, [("permission", "approve")])
calibrate = parked.steps[2]
check(
"approving the calibration enqueues a job and PARKS the plan: the plan stays 'running' and "
"the step reads 'waiting_job' with the job's id",
parked.plan.status == "running"
and calibrate.status == "waiting_job"
and str(calibrate.job_id).startswith("RFN-")
and not pending(caliber, plan_id)
and calibrate.job_id not in jobs_before,
f"{parked.plan.status}; {calibrate.status}; {calibrate.job_id}",
)
edit_parked = refused(lambda: caliber.aria.update_plan(plan_id, status="cancelled"))
check(
"a parked plan cannot be cancelled or edited (409): only drafts can",
edit_parked is not None and edit_parked.status_code == 409,
_reason(edit_parked),
)
check(
"the plan asked six questions in all: a form and an approval for each step",
[kind for kind, _ in first_trail] + ["permission"]
== ["input", "permission", "input", "permission", "input", "permission"],
)
final, advanced_by = wait_for_resume(caliber, plan_id, patience=patience, sleep=sleep)
job = caliber.jobs.get(str(calibrate.job_id))
final_step = final.steps[2]
if job.status in {"candidate_ready", "applied"}:
outcome_ok = final.plan.status == "completed" and final_step.status == "done"
outcome = "the calibration found a candidate: the plan completed"
else:
outcome_ok = (
job.status == "rejected"
and final.plan.status == "failed"
and final_step.status == "failed"
and str(final_step.error) == f"rejected: {job.error_message}"
and "no candidate met calibration gates" in str(job.error_message)
)
outcome = "the calibration was rejected: the plan failed with the job's reason"
check(
f"the plan resumed by itself ({advanced_by}) and ends where the job ended: {outcome}",
outcome_ok,
f"job {job.status}; plan {final.plan.status}; step: {str(final_step.error)[:110]}",
)
again = caliber.aria.poll_plan(plan_id)
check(
"polling a finished plan changes nothing",
again.plan.status == final.plan.status and step_status(again) == step_status(final),
)
evaluation = job.eval_results or {}
check(
"the job replayed 20 of the gate's 30 cases (the default budget) and reports its baseline",
bool(evaluation.get("calibration"))
and evaluation.get("n_examples") == 20
and "baseline" in evaluation,
f"{evaluation.get('n_examples')} examples; "
f"gate: {(evaluation.get('gate') or {}).get('reasons')}",
)
queue_id = final.steps[0].result["queue_id"]
detail = caliber.raw.get(f"/review-queues/{queue_id}")
queue, items = detail["queue"], detail["items"]
check(
"the review queue exists with its four triage questions and the 12 flagged traces "
"pending, assigned to the reviewer",
queue["name"] == queue_form["name"]
and [q["key"] for q in queue["questions"]]
== ["resolution_correct", "failure_mode", "severity", "expected_answer"]
and queue["item_count"] == WEAK_EXPECTED
and {i["trace_id"] for i in items} == set(flagged_ids)
and all(i["status"] == "pending" and i["assigned_to"] == admin_id for i in items),
f"{queue_id}: {queue['item_count']} items",
)
result.update(
plan_id=plan_id,
queue_id=queue_id,
calibration={
"job_id": str(calibrate.job_id),
"job_status": job.status,
"plan_status": final.plan.status,
"advanced_by": advanced_by,
},
)
# -- 3. A reviewer triages three of the flagged runs --------------------------------------
item_of = {item["trace_id"]: item["item_id"] for item in items}
modes = {r["id"]: r["reason"].split(":", 1)[0] for r in weak}
for row_id in TRIAGED:
row = next(r for r in weak if r["id"] == row_id)
caliber.review_queues.submit(
queue_id,
item_of[trace_of[row_id]],
resolution_correct=False,
failure_mode=modes[row_id],
severity=4 if modes[row_id] == "hallucinated_claim" else 3,
expected_answer=row["reference"],
)
stored = {
row_id: {
a["name"]: a["value"]
for a in caliber.observability.trace(trace_of[row_id])["assessments"]
}
for row_id in TRIAGED
}
check(
"three triaged runs carry the reviewer's verdict, failure mode and the expected answer "
"on their traces",
all(
stored[row_id].get("resolution_correct") is False
and stored[row_id].get("failure_mode") == modes[row_id]
and stored[row_id].get("expected_answer")
== next(r for r in weak if r["id"] == row_id)["reference"]
for row_id in TRIAGED
),
{row_id: modes[row_id] for row_id in TRIAGED},
)
after = caliber.raw.get(f"/review-queues/{queue_id}")["queue"]
check(
"the queue shows 3 of 12 reviewed",
after["item_count"] == WEAK_EXPECTED and after["pending_count"] == WEAK_EXPECTED - 3,
f"{WEAK_EXPECTED - after['pending_count']}/{after['item_count']} reviewed",
)
result["triage"] = {"reviewed": 3, "pending": WEAK_EXPECTED - 3}
# -- 4. Refusals --------------------------------------------------------------------------
calibrate_only = "Calibrate the support workflow."
def failed_calibration(workflow_id: str, agent: str) -> Any:
detail, _ = run_plan(
caliber,
calibrate_only,
autonomy="approve_plan",
moves=[("input", {"workflow_id": workflow_id, "agent_id": agent})],
)
return detail
unknown_workflow = failed_calibration("WF-does-not-exist", agent_id)
check(
"an unknown workflow fails the step at once (404), without parking",
unknown_workflow.plan.status == "failed"
and unknown_workflow.steps[0].status == "failed"
and "not found" in str(unknown_workflow.steps[0].error)
and unknown_workflow.steps[0].job_id is None,
unknown_workflow.steps[0].error,
)
unregistered = failed_calibration(workflow_id, "agent-that-is-not-registered")
check(
"an agent that is not registered fails the step at once (400)",
unregistered.plan.status == "failed"
and "is not registered" in str(unregistered.steps[0].error),
unregistered.steps[0].error,
)
no_gate = dict(load_json(assets / "workflows/support-policy-agent.workflow.json"))
no_gate["deploy_gates"] = {}
no_gate["artifacts"] = {**no_gate["artifacts"], "eval_datasets": {}}
ungated = caliber.workflows.import_workflow(
manifest=no_gate, name=f"{NAME_PREFIX}no-gate-{suffix}"
)
caliber.workflows.versions.publish(
caliber.workflows.versions.list(ungated.workflow_id)[0].version_id
)
no_dataset = failed_calibration(ungated.workflow_id, agent_id)
check(
"a workflow with no deploy-gate test set fails the step at once (400): calibration needs "
"one",
no_dataset.plan.status == "failed"
and "deploy-gate eval dataset" in str(no_dataset.steps[0].error),
no_dataset.steps[0].error,
)
calibration_jobs = {j.job_id for j in caliber.jobs.list() if j.agent_id == agent_id}
check(
"none of the three refusals queued a job",
calibration_jobs == {str(calibrate.job_id)},
len(calibration_jobs),
)
# A form the schema refuses stays open; a denied calibration queues nothing.
first = start(caliber, calibrate_only, autonomy="ask_each")
form = pending(caliber, first.plan.plan_id)[0]
bad = {
"an empty workflow id": {"workflow_id": "", "agent_id": agent_id},
"a missing agent id": {"workflow_id": workflow_id},
"an unknown field": {"workflow_id": "WF-1", "agent_id": "a", "objective": "quality"},
}
form_refusals = {
label: refused(partial(caliber.aria.answer, form.interaction_id, inputs=inputs))
for label, inputs in bad.items()
}
check(
"the form refuses an empty workflow id, a missing agent id and a field it does not have "
"(409) and stays open",
all(e is not None and e.status_code == 409 for e in form_refusals.values())
and [i.status for i in caliber.aria.interactions(first.plan.plan_id)] == ["pending"],
{label: _reason(e) for label, e in form_refusals.items()},
)
denied, _ = walk(
caliber,
first.plan.plan_id,
[
("input", {"workflow_id": workflow_id, "agent_id": agent_id}),
("permission", "deny"),
],
)
check(
"denying the calibration skips the step and queues no job; the plan completes",
denied.plan.status == "completed"
and step_status(denied) == {"workflow.calibrate": "skipped"}
and {j.job_id for j in caliber.jobs.list() if j.agent_id == agent_id}
== {str(calibrate.job_id)},
)
# Skip the queue: its enqueue goes with it, the calibration still asks.
skipped, trail = walk(
caliber,
start(caliber, INTENT, autonomy="approve_plan").plan.plan_id,
[("input", "skip"), ("input", "skip")],
)
check(
"skipping the queue skips the enqueue step with it (never asked); the calibration's form "
"is still asked, and skipping it ends the plan",
skipped.plan.status == "completed"
and set(step_status(skipped).values()) == {"skipped"}
and [capability for _, capability in trail] == ["review_queue.create", "workflow.calibrate"]
and "step 1 (review_queue.create) was skipped" in str(skipped.steps[1].error),
step_status(skipped),
)
nothing = caliber.aria.create_plan("Tune the pipeline and get a human to look at the bad runs.")
approve_empty = refused(lambda: caliber.aria.approve_plan(nothing.plan.plan_id))
check(
"a goal with no domain word is created with a warning and refused at approval (409)",
nothing.plan.step_count == 0
and bool(nothing.extra.get("warnings"))
and approve_empty is not None
and approve_empty.status_code == 409,
)
caliber.aria.update_plan(nothing.plan.plan_id, status="cancelled")
by_viewer = start(viewer, calibrate_only, autonomy="approve_plan")
check(
"a plan owned by an account without the operator scope fails at execute and queues nothing",
by_viewer.plan.status == "failed"
and by_viewer.steps[0].error == "plan owner lacks required scope(s): operator",
by_viewer.steps[0].error,
)
own = start(caliber, calibrate_only, autonomy="approve_plan")
waiting = pending(caliber, own.plan.plan_id)[0]
other_answer = refused(lambda: operator.aria.answer(waiting.interaction_id, approved=False))
other_poll = refused(lambda: operator.aria.poll_plan(own.plan.plan_id))
check(
"an operator who does not own the plan cannot answer its question (403) or poll it (404)",
isinstance(other_answer, CaliberPermissionError)
and other_poll is not None
and other_poll.status_code == 404,
_reason(other_answer),
)
walk(caliber, own.plan.plan_id, [("input", "skip")])
# -- 5. Ask Aria's chat, on a real stack ------------------------------------------------------
if real:
result["chat"] = _chat_for_real(caliber, check, suffix)
check.finish()
return result
def _chat_for_real(caliber: CaliberClient, check: Checks, suffix: str) -> dict[str, Any]:
"""Ask Aria (the chat, not the Plans page) acts in build / auto_all and only reads otherwise."""
acting = f"{NAME_PREFIX}chat-queue-{suffix}"
reading = f"{NAME_PREFIX}chat-manual-{suffix}"
spec = (
"with one pass_fail question: key resolved, title 'Did the agent resolve the request?'. "
"Then tell me its id."
)
def queue_names() -> set[str]:
return {q.name for q in caliber.review_queues.list()}
summary = check_chat_boundary(
caliber,
check,
tool="review_queue_create",
ask=f"Create a review queue named {acting} {spec}",
exists=lambda: acting in queue_names(),
absent_ask=f"Create a review queue named {reading} {spec}",
absent_exists=lambda: reading in queue_names(),
)
made = next((q for q in caliber.review_queues.list() if q.name == acting), None)
check(
"the chat's queue is active with the question that was asked for",
made is not None
and made.status == "active"
and [q["key"] for q in caliber.review_queues.get(made.queue_id).questions] == ["resolved"],
made.queue_id if made else "",
)
return summary
def cleanup(caliber: CaliberClient) -> dict[str, int]:
"""Archive what earlier runs created (names start ``cookbook-15-``)."""
archived = {"review_queues": 0, "test_sets": 0, "workflows": 0}
for queue in caliber.review_queues.list():
if queue.name.startswith(NAME_PREFIX):
caliber.review_queues.update(queue.queue_id, status="archived")
archived["review_queues"] += 1
for dataset in caliber.eval_datasets.list():
if dataset.name.startswith(NAME_PREFIX) and dataset.status != "archived":
caliber.eval_datasets.update(dataset.dataset_id, status="archived")
archived["test_sets"] += 1
for workflow in caliber.workflows.list():
if workflow.name.startswith(NAME_PREFIX) and workflow.status != "archived":
caliber.workflows.update(workflow.workflow_id, status="archived")
archived["workflows"] += 1
return archived
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
parser.add_argument("--cleanup", action="store_true", help="archive what earlier runs created")
parser.add_argument("--suffix", help="name suffix (default: a timestamp)")
args = parser.parse_args(argv)
base_url = os.environ["CALIBER_BASE_URL"]
password = env_password("COOKBOOK_ARIA_PASSWORD", DEFAULT_PASSWORD)
opened: list[CaliberClient] = []
with env_client(timeout=http_timeout()) as caliber:
try:
if args.cleanup:
print(json.dumps(cleanup(caliber), indent=2))
return 0
ensure_accounts(caliber, (OPERATOR_USER, VIEWER_USER), password)
clients = {}
for user in (OPERATOR_USER, VIEWER_USER):
clients[user] = CaliberClient(base_url, token=sign_in(base_url, user, password))
opened.append(clients[user])
result = run(
caliber,
operator=clients[OPERATOR_USER],
viewer=clients[VIEWER_USER],
suffix=args.suffix,
)
except (VerificationError, SetupError, CaliberAPIError) as exc:
print(f"\nVERIFICATION FAILED: {exc}", file=sys.stderr)
return 1
finally:
for client in opened:
client.close()
print(json.dumps(result, indent=2, sort_keys=True, default=str))
return 0
if __name__ == "__main__":
sys.exit(main())sdk/caliber-sdk/examples/cookbooks/cookbook_15_aria_triage_recalibrate_loop.py — executed by the SDK example test suite.Cookbook 16 — Production Observability & Triage
Import and publish the cookbook 09 workflow and submit 40 production tickets as real runs, read the resulting traces back through Observability (12 ERROR, 28 OK, 4 of the OK ones silently wrong), capture the 16 traces that matter into a test set with their gold outcome, and stand up the triage queue, enqueue those traces and answer two, checking the answers become assessments on the traces. It needs no Aria flag and no model (the workflow has no agent node, so the simulated provider changes nothing), but it does need cookbook 09's stand-in account service (not a real system) on port 8780, CALIBER_EGRESS_ALLOWED_HOSTS=127.0.0.1 on the server, and the 40 sample tickets; it does not install a cookbook through client.cookbooks and does not use client.raw.
SDK surfaces: workflows, observability, datasets, review_queues
- Seed production traffic: import and publish the workflow and submit the 40 tickets as runs, so the traces are the ones the runtime records (none is written by the script).
- Read the traces back through Observability: the status counts (12 ERROR, 28 OK), the Error filter, and the request and node tree of one failing trace per failure kind; find the 4 OK traces whose answer differs from the gold outcome.
- Check the failure paths: an unknown trace id is a 404, a window in the future is an empty list, and a trace's run is found from its trace id.
- Capture the 16 failing or silently wrong traces into a test set with
eval_datasets.add_from_trace, each with its gold outcome and tags. - Create the triage queue, enqueue the same 16 traces, answer two of them and check the answers are written back onto the traces as assessments.
"""Cookbook 16: turn production failures into evidence you can act on.
Runs the whole lab through the SDK against a live server and exits 0 only when every check below
holds. It is the API half of the lab README (docs-site/cookbooks/16-observability-triage/README.md)
and prints the same values the README tells you to expect.
export CALIBER_BASE_URL=http://127.0.0.1:5001 CALIBER_TOKEN=calpat_...
PYTHONPATH=sdk/caliber-sdk python \
sdk/caliber-sdk/examples/cookbooks/cookbook_16_observability_triage.py
The server needs cookbook 09's stand-in account service (``python3 docs-site/cookbooks/09-workflow-
debugger-self-healing-lab/assets/upstream/account_service.py 8780``) and
``CALIBER_EGRESS_ALLOWED_HOSTS=127.0.0.1``; nothing here needs a model.
What it does, in order:
1. Seeds production traffic: ``assets/seed_traces.py`` runs the 40 tickets in
``assets/dataset/prod-regression.sample.jsonl`` through a real workflow. The traces are the ones
CALIBER's runtime records; none is written by this script.
2. Reads them back through Observability: the status filter, and the request, response and node
tree of one failing trace per failure kind. 12 traces are ``ERROR``, 28 ``OK``, and 4 of the
``OK`` ones are wrong: nothing errored, the answer is not what the gold outcome says.
3. Shows the failure paths: a trace id that does not exist is a 404, an empty result is an empty
list, and a trace's run can be found from its trace id.
4. Captures the 16 traces that matter into a test set with their gold outcome.
5. Stands up the ``prod-triage`` review queue, enqueues the same 16 traces, answers two of them, and
checks that the answers are written back onto the traces as assessments.
``--cleanup`` archives the test set and the queue when the run succeeds.
"""
from __future__ import annotations
import importlib.util
import json
import os
import sys
import time
from collections import Counter
from pathlib import Path
from typing import Any
from caliber_sdk import CaliberClient
from caliber_sdk.errors import CaliberNotFoundError
from examples.cookbooks._helpers import env_client
ASSETS = Path(
os.environ.get(
"COOKBOOK_16_ASSETS",
Path(__file__).resolve().parents[4] / "docs-site/cookbooks/16-observability-triage/assets",
)
)
#: The node a failure kind stops at in cookbook 09's version 1 (what the node tree must show).
FAILING_NODE = {"validate": "validate", "poison": "check_reference", "upstream": "decide"}
EXPECTED_STATUS = {"ERROR": 12, "OK": 28}
class VerificationError(AssertionError):
"""A documented outcome did not hold; the message says which."""
def check(condition: bool, message: str) -> None:
if not condition:
raise VerificationError(message)
def _seed_module(assets: Path) -> Any:
spec = importlib.util.spec_from_file_location(
"cookbook16_seed_traces", assets / "seed_traces.py"
)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def decision_of(run: Any) -> dict[str, Any]:
summary = run.extra.get("summary") or {}
decision: dict[str, Any] = json.loads(summary.get("output") or "{}")
return decision
def kind_of(row: dict[str, Any]) -> str | None:
return next((tag for tag in row["tags"] if tag in FAILING_NODE), None)
def settled_traces(caliber: CaliberClient, since_ms: int, *, wait: float = 60.0) -> dict[str, Any]:
"""The traces since ``since_ms``, once none is still ``IN_PROGRESS``.
MLflow records a trace asynchronously, so a trace can still read ``IN_PROGRESS`` for a moment
after its run has ended; a status count taken then would be wrong, not the system.
"""
deadline = time.monotonic() + wait
while True:
found = caliber.observability.traces(limit=200, since_ms=since_ms)
traces = {t.trace_id: t for t in found}
if not any(t.status == "IN_PROGRESS" for t in found) or time.monotonic() > deadline:
return traces
time.sleep(1.0)
def read_back(
caliber: CaliberClient,
rows: list[dict[str, Any]],
seeded: dict[str, dict[str, str]],
since_ms: int,
) -> dict[str, Any]:
"""Observability's view of the seeded traffic: status, node tree, request and response."""
traces = settled_traces(caliber, since_ms)
mine = {row["id"]: traces.get(seeded[row["id"]]["trace_id"]) for row in rows}
check(
all(mine.values()),
f"traces missing from Observability: {[k for k, v in mine.items() if not v]}",
)
status = Counter(trace.status for trace in mine.values() if trace)
check(dict(status) == EXPECTED_STATUS, f"trace status counts: {dict(status)}")
for row in rows:
failed = seeded[row["id"]]["status"] == "failed"
check(
(mine[row["id"]].status == "ERROR") == failed, # type: ignore[union-attr]
f"{row['id']}: run {seeded[row['id']]['status']} but trace {mine[row['id']].status}", # type: ignore[union-attr]
)
filtered = {
t.trace_id
for t in caliber.observability.traces(limit=200, since_ms=since_ms, status="ERROR")
}
error_ids = {seeded[r["id"]]["trace_id"] for r in rows if kind_of(r)}
check(error_ids <= filtered, "the Error filter missed a failing trace")
detail: dict[str, Any] = {}
for kind, node in FAILING_NODE.items():
row = next(r for r in rows if kind_of(r) == kind)
trace = caliber.observability.trace(seeded[row["id"]]["trace_id"])
errored = [s["name"] for s in trace["spans"] if s["status"] == "ERROR"]
check(
f"node.{node}" in errored, f"{row['id']}: error spans {errored}, expected node.{node}"
)
check(trace["status"] == "ERROR", f"{row['id']}: trace status {trace['status']}")
check(
row["input"]["payload"][:40] in (trace["request"] or ""),
f"{row['id']}: the trace does not carry the request",
)
detail[kind] = {"row": row["id"], "error_spans": errored}
return {"status": dict(status), "detail": detail}
def failure_paths(caliber: CaliberClient, seeded: dict[str, dict[str, str]]) -> dict[str, Any]:
missing = None
try:
caliber.observability.trace("tr-00000000000000000000000000000000")
except CaliberNotFoundError as exc:
missing = exc.status_code
check(missing == 404, f"an unknown trace id should be a 404, got {missing}")
empty = caliber.observability.traces(
status="ERROR", since_ms=int(time.time() * 1000) + 3_600_000
)
check(empty == [], f"a window in the future should be an empty list, got {len(empty)}")
sample = next(iter(seeded.values()))
run = caliber.workflows.runs.by_trace(sample["trace_id"])
check(run.workflow_run_id == sample["run_id"], "by_trace returned another run")
return {"unknown_trace": missing, "future_window": len(empty), "by_trace": run.workflow_run_id}
def run(
caliber: CaliberClient,
*,
assets: Path = ASSETS,
suffix: str | None = None,
seeded: dict[str, dict[str, str]] | None = None,
cleanup: bool = False,
) -> dict[str, Any]:
suffix = suffix or str(int(time.time()))
seed_module = _seed_module(assets)
rows = seed_module.load_rows(assets / "dataset/prod-regression.sample.jsonl")
check(len(rows) == 40, f"expected 40 production tickets, found {len(rows)}")
since_ms = int(time.time() * 1000) - 5_000
# 1. production traffic, as real runs
seeded = seeded or seed_module.seed(caliber, rows=rows, suffix=suffix)
# 2. Observability
observed = read_back(caliber, rows, seeded, since_ms)
# which runs finished but gave the wrong answer: nothing errored, a person has to notice
outcomes = {
row["id"]: decision_of(caliber.workflows.runs.get(seeded[row["id"]]["run_id"]))
for row in rows
if seeded[row["id"]]["status"] == "completed"
}
wrong = [
row["id"]
for row in rows
if row["id"] in outcomes
and (outcomes[row["id"]].get("decision"), outcomes[row["id"]].get("reason_code"))
!= (row["expected"]["decision"], row["expected"]["reason_code"])
]
check(
wrong == [r["id"] for r in rows if "silent_wrong" in r["tags"]],
f"OK traces with the wrong outcome: {wrong}",
)
# 3. failure paths
paths = failure_paths(caliber, seeded)
# 4. the test set
to_capture = [r for r in rows if kind_of(r) or r["id"] in wrong]
check(len(to_capture) == 16, f"expected 16 traces to capture, found {len(to_capture)}")
dataset = caliber.eval_datasets.create(
f"prod-regression-{suffix}", owner=caliber.me.get().user_id, description="Cookbook 16"
)
for row in to_capture:
caliber.eval_datasets.add_from_trace(
dataset.dataset_id,
seeded[row["id"]]["trace_id"],
expected=row["expected"],
tags=row["tags"],
)
examples = caliber.eval_datasets.examples(dataset.dataset_id)
check(len(examples) == 16, f"the test set holds {len(examples)} examples, expected 16")
first = examples[0]
check("T-50" in json.dumps(first.input), "a captured example does not carry its request")
# 5. triage
questions = json.loads(
(assets / "review-queues/triage-review.review-questions.json").read_text()
)
queue = caliber.review_queues.create(f"prod-triage-{suffix}", questions=questions["questions"])
items = caliber.review_queues.enqueue(
queue.queue_id, trace_ids=[seeded[r["id"]]["trace_id"] for r in to_capture]
)
check(len(items) == 16, f"the queue took {len(items)} traces, expected 16")
item_for_trace = {item["trace_id"]: item["item_id"] for item in items}
reviewed = {"P38": ("tool", "high"), "P25": ("data", "low")}
for row_id, (mode, severity) in reviewed.items():
row = next(r for r in rows if r["id"] == row_id)
caliber.review_queues.submit(
queue.queue_id,
item_for_trace[seeded[row_id]["trace_id"]],
root_cause_known=True,
failure_mode=mode,
severity=severity,
expected_output=json.dumps(row["expected"]),
reviewer_notes=f"cookbook 16 review of {row_id}",
)
written: dict[str, list[str]] = {}
for row_id in reviewed:
trace = caliber.observability.trace(seeded[row_id]["trace_id"])
names = sorted({a["name"] for a in trace["assessments"]})
check("failure_mode" in names and "severity" in names, f"{row_id}: assessments {names}")
written[row_id] = names
result = {
"seeded": len(seeded),
"traces": observed["status"],
"node_tree": {kind: v["error_spans"][-1] for kind, v in observed["detail"].items()},
"ok_but_wrong": wrong,
"failure_paths": paths,
"test_set": {"examples": len(examples), "dataset_id": dataset.dataset_id},
"triage": {"queued": len(items), "answered": len(reviewed), "assessments": written},
}
if cleanup:
caliber.eval_datasets.update(dataset.dataset_id, status="archived")
caliber.review_queues.update(queue.queue_id, status="archived")
return result
def main() -> None:
with env_client() as caliber:
print(json.dumps(run(caliber, cleanup="--cleanup" in sys.argv), indent=2, sort_keys=True))
if __name__ == "__main__":
main()sdk/caliber-sdk/examples/cookbooks/cookbook_16_observability_triage.py — executed by the SDK example test suite.Cookbook 17 — Monthly Financial Analysis
Create a project and object-store bucket, generate and persist realistic monthly financial CSV data, register and promote a dashboard-ready statistics prompt, execute it through a typed assistant session, then validate the returned mean/median/percentile/extrema JSON, persist it and download-verify it -- entirely through typed SDK resources. This standalone example (it has no lab folder and does not install a cookbook) needs an admin-scoped SDK token for object-store mutations, a connected object store, a configured model provider for live prompt execution, and CALIBER_FEATURE_ARIA=true, because the assistant-session surface (/assistant/*) is served only when that flag is on; it does not use client.raw.
SDK surfaces: projects, object_store, prompts, aria
- Create the financial-analysis project and select it as the temporary SDK project scope.
- Create a dedicated blob bucket, generate the CSV in memory, upload and download-verify it, then import the object into the project's governed file registry for lineage.
- Create and re-read the registered prompt, promote its final version to the prod alias, and verify it is visible through the Prompt dashboard inventory.
- Execute the prompt through the typed assistant-session surface (
aria.sessions.createandsend_message), surfacing any provider failure, and validate the mean/median/percentile/extrema JSON against statistics computed from the CSV. - Upload the result document to blob storage and download-verify it.
"""Create, execute, and persist a monthly financial analysis using only the SDK."""
from __future__ import annotations
import csv
import io
import json
import math
import re
from datetime import datetime, timezone
from typing import Any
from caliber_sdk import CaliberClient
from examples.cookbooks._helpers import env_client
CSV_FILENAME = "monthly-financials.csv"
RESULT_FILENAME = "monthly-financial-analysis.json"
PROMPT_ALIAS = "prod"
NUMERIC_COLUMNS = (
"revenue",
"operating_expenses",
"payroll",
"cloud_compute_costs",
"other_expenses",
"total_expenses",
"operating_income",
"cash_balance",
"accounts_receivable",
"accounts_payable",
)
CSV_FIELDS = ("month", *NUMERIC_COLUMNS)
# ``operating_expenses`` is general operating spend excluding the separately
# reported payroll, cloud/compute, and other-expense categories. The last three
# columns are month-end balance-sheet snapshots; all amounts are USD.
MONTHLY_FINANCIALS: tuple[dict[str, str], ...] = (
{
"month": "2025-01",
"revenue": "1240000",
"operating_expenses": "185000",
"payroll": "420000",
"cloud_compute_costs": "92000",
"other_expenses": "48000",
"total_expenses": "745000",
"operating_income": "495000",
"cash_balance": "2850000",
"accounts_receivable": "410000",
"accounts_payable": "215000",
},
{
"month": "2025-02",
"revenue": "1315000",
"operating_expenses": "190000",
"payroll": "425000",
"cloud_compute_costs": "95000",
"other_expenses": "51000",
"total_expenses": "761000",
"operating_income": "554000",
"cash_balance": "3010000",
"accounts_receivable": "432000",
"accounts_payable": "221000",
},
{
"month": "2025-03",
"revenue": "1380000",
"operating_expenses": "198000",
"payroll": "428000",
"cloud_compute_costs": "101000",
"other_expenses": "47000",
"total_expenses": "774000",
"operating_income": "606000",
"cash_balance": "3225000",
"accounts_receivable": "447000",
"accounts_payable": "229000",
},
{
"month": "2025-04",
"revenue": "1290000",
"operating_expenses": "192000",
"payroll": "435000",
"cloud_compute_costs": "104000",
"other_expenses": "56000",
"total_expenses": "787000",
"operating_income": "503000",
"cash_balance": "3310000",
"accounts_receivable": "438000",
"accounts_payable": "236000",
},
{
"month": "2025-05",
"revenue": "1460000",
"operating_expenses": "205000",
"payroll": "442000",
"cloud_compute_costs": "109000",
"other_expenses": "52000",
"total_expenses": "808000",
"operating_income": "652000",
"cash_balance": "3540000",
"accounts_receivable": "469000",
"accounts_payable": "244000",
},
{
"month": "2025-06",
"revenue": "1530000",
"operating_expenses": "212000",
"payroll": "448000",
"cloud_compute_costs": "115000",
"other_expenses": "61000",
"total_expenses": "836000",
"operating_income": "694000",
"cash_balance": "3795000",
"accounts_receivable": "488000",
"accounts_payable": "252000",
},
{
"month": "2025-07",
"revenue": "1490000",
"operating_expenses": "210000",
"payroll": "455000",
"cloud_compute_costs": "121000",
"other_expenses": "58000",
"total_expenses": "844000",
"operating_income": "646000",
"cash_balance": "3960000",
"accounts_receivable": "481000",
"accounts_payable": "261000",
},
{
"month": "2025-08",
"revenue": "1610000",
"operating_expenses": "218000",
"payroll": "462000",
"cloud_compute_costs": "128000",
"other_expenses": "54000",
"total_expenses": "862000",
"operating_income": "748000",
"cash_balance": "4215000",
"accounts_receivable": "512000",
"accounts_payable": "269000",
},
{
"month": "2025-09",
"revenue": "1570000",
"operating_expenses": "216000",
"payroll": "468000",
"cloud_compute_costs": "126000",
"other_expenses": "63000",
"total_expenses": "873000",
"operating_income": "697000",
"cash_balance": "4380000",
"accounts_receivable": "505000",
"accounts_payable": "278000",
},
{
"month": "2025-10",
"revenue": "1720000",
"operating_expenses": "225000",
"payroll": "475000",
"cloud_compute_costs": "134000",
"other_expenses": "57000",
"total_expenses": "891000",
"operating_income": "829000",
"cash_balance": "4675000",
"accounts_receivable": "541000",
"accounts_payable": "287000",
},
{
"month": "2025-11",
"revenue": "1810000",
"operating_expenses": "232000",
"payroll": "482000",
"cloud_compute_costs": "141000",
"other_expenses": "69000",
"total_expenses": "924000",
"operating_income": "886000",
"cash_balance": "4950000",
"accounts_receivable": "568000",
"accounts_payable": "298000",
},
{
"month": "2025-12",
"revenue": "1960000",
"operating_expenses": "245000",
"payroll": "495000",
"cloud_compute_costs": "153000",
"other_expenses": "88000",
"total_expenses": "981000",
"operating_income": "979000",
"cash_balance": "5320000",
"accounts_receivable": "596000",
"accounts_payable": "312000",
},
)
PROMPT_TEMPLATE = """You are a financial analyst. Analyze the CSV supplied in the user message.
The CSV contains monthly USD values. `operating_expenses` excludes payroll,
cloud/compute, and other expenses. `total_expenses` is their sum, and
`operating_income` is revenue minus total expenses. Cash, receivables, and
payables are month-end balance-sheet snapshots.
For every numeric column, calculate mean, median, P25, P50, P75, P90, minimum,
and maximum. Use linear interpolation with rank `(n - 1) * percentile`; P50 must
equal the median. Minimum and maximum must include both month and value.
Return only one valid JSON object with this exact top-level shape:
{
"currency": "USD",
"periods": 12,
"percentile_method": "linear_interpolation_rank_(n-1)*p",
"statistics": {
"<numeric_column>": {
"mean": 0,
"median": 0,
"p25": 0,
"p50": 0,
"p75": 0,
"p90": 0,
"minimum": {"month": "YYYY-MM", "value": 0},
"maximum": {"month": "YYYY-MM", "value": 0}
}
},
"observations": ["two or three concise findings grounded in the numbers"]
}
Do not omit columns, add commentary outside the JSON, or invent data."""
def build_financial_csv() -> bytes:
"""Return the complete input fixture without writing a local file."""
stream = io.StringIO(newline="")
writer = csv.DictWriter(stream, fieldnames=CSV_FIELDS, lineterminator="\n")
writer.writeheader()
writer.writerows(MONTHLY_FINANCIALS)
return stream.getvalue().encode("utf-8")
def _percentile(values: list[float], percentile: float) -> float:
ordered = sorted(values)
rank = (len(ordered) - 1) * percentile
lower = math.floor(rank)
upper = math.ceil(rank)
if lower == upper:
return ordered[lower]
return ordered[lower] + (ordered[upper] - ordered[lower]) * (rank - lower)
def expected_statistics() -> dict[str, dict[str, Any]]:
"""Deterministic reference used to reject plausible-looking bad model math."""
statistics: dict[str, dict[str, Any]] = {}
for column in NUMERIC_COLUMNS:
values = [float(row[column]) for row in MONTHLY_FINANCIALS]
minimum = min(enumerate(values), key=lambda pair: pair[1])
maximum = max(enumerate(values), key=lambda pair: pair[1])
statistics[column] = {
"mean": sum(values) / len(values),
"median": _percentile(values, 0.50),
"p25": _percentile(values, 0.25),
"p50": _percentile(values, 0.50),
"p75": _percentile(values, 0.75),
"p90": _percentile(values, 0.90),
"minimum": {
"month": MONTHLY_FINANCIALS[minimum[0]]["month"],
"value": minimum[1],
},
"maximum": {
"month": MONTHLY_FINANCIALS[maximum[0]]["month"],
"value": maximum[1],
},
}
return statistics
def _is_number(value: Any) -> bool:
return isinstance(value, (int, float)) and not isinstance(value, bool)
def parse_analysis(content: str) -> dict[str, Any]:
"""Decode and validate the model's strict JSON financial-analysis result."""
candidate = content.strip()
if candidate.startswith("```"):
candidate = re.sub(r"^```(?:json)?\s*", "", candidate, count=1, flags=re.I)
candidate = re.sub(r"\s*```$", "", candidate, count=1)
try:
parsed = json.loads(candidate)
except json.JSONDecodeError as exc:
raise ValueError(
f"prompt result is not a JSON object (it starts: {candidate[:120]!r})"
) from exc
if not isinstance(parsed, dict):
raise ValueError("prompt result must be a JSON object")
required_top_level = {
"currency",
"periods",
"percentile_method",
"statistics",
"observations",
}
if set(parsed) != required_top_level:
raise ValueError("prompt result does not match the required top-level shape")
if parsed.get("currency") != "USD" or parsed.get("periods") != len(MONTHLY_FINANCIALS):
raise ValueError("prompt result has the wrong currency or period count")
if parsed.get("percentile_method") != "linear_interpolation_rank_(n-1)*p":
raise ValueError("prompt result has the wrong percentile method")
observations = parsed.get("observations")
if (
not isinstance(observations, list)
or not 2 <= len(observations) <= 3
or any(not isinstance(item, str) or not item.strip() for item in observations)
):
raise ValueError("prompt result must contain two or three non-empty observations")
statistics = parsed.get("statistics")
if not isinstance(statistics, dict) or set(statistics) != set(NUMERIC_COLUMNS):
raise ValueError("prompt result statistics do not match the required numeric columns")
metric_names = ("mean", "median", "p25", "p50", "p75", "p90")
required_metric_names = {*metric_names, "minimum", "maximum"}
reference = expected_statistics()
for column in NUMERIC_COLUMNS:
metrics = statistics.get(column)
if not isinstance(metrics, dict) or set(metrics) != required_metric_names:
raise ValueError(f"prompt result has the wrong statistics shape for {column}")
if any(not _is_number(metrics.get(name)) for name in metric_names):
raise ValueError(f"prompt result has non-numeric statistics for {column}")
if float(metrics["p50"]) != float(metrics["median"]):
raise ValueError(f"prompt result p50 does not equal median for {column}")
for name in metric_names:
if not math.isclose(
float(metrics[name]), float(reference[column][name]), rel_tol=0, abs_tol=0.01
):
raise ValueError(f"prompt result has an incorrect {name} for {column}")
for extreme in ("minimum", "maximum"):
value = metrics.get(extreme)
if (
not isinstance(value, dict)
or set(value) != {"month", "value"}
or not _is_number(value.get("value"))
):
raise ValueError(f"prompt result has an invalid {extreme} for {column}")
expected_extreme = reference[column][extreme]
if value.get("month") != expected_extreme["month"]:
raise ValueError(f"prompt result has an invalid {extreme} month for {column}")
if not math.isclose(
float(value["value"]), float(expected_extreme["value"]), rel_tol=0, abs_tol=0.01
):
raise ValueError(f"prompt result has an incorrect {extreme} for {column}")
return parsed
def _required_mapping_value(payload: Any, key: str) -> Any:
if not isinstance(payload, dict) or payload.get(key) in (None, ""):
raise RuntimeError(f"SDK response is missing {key!r}")
return payload[key]
def parse_turn_analysis(turn: Any) -> dict[str, Any]:
"""Surface provider failures before validating a successful JSON response."""
assistant_message = _required_mapping_value(turn, "assistant_message")
content = str(_required_mapping_value(assistant_message, "content"))
metadata = assistant_message.get("metadata_", {})
if isinstance(metadata, dict) and metadata.get("error") is True:
raise RuntimeError(f"prompt execution failed: {content}")
return parse_analysis(content)
def run(caliber: CaliberClient, *, run_key: str | None = None) -> dict[str, Any]:
"""Run the end-to-end financial workflow against one CALIBER deployment."""
identity = caliber.me.get()
if identity.is_anonymous:
raise RuntimeError("CALIBER_TOKEN does not resolve to an authenticated user")
simulated = (caliber.readiness() or {}).get("simulated") or []
if "llm" in simulated:
raise RuntimeError(
"this server's language model is simulated, so the prompt cannot really run. Start "
"CALIBER with a real provider (scripts/cookbook-env.sh up NAME --flags aria --s3 "
"--real-llm, with OPENAI_API_KEY set) and run this again"
)
key = run_key or datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
if not re.fullmatch(r"[a-z0-9][a-z0-9-]{2,47}", key):
raise ValueError("run_key must be 3-48 lowercase letters, digits, or hyphens")
project = caliber.projects.create(
f"SDK Financial Analysis {key}",
description="SDK-only monthly financial analysis with persisted input and output",
)
csv_bytes = build_financial_csv()
bucket = f"sdk-financial-{key}"
input_object_key = f"projects/{project.project_id}/inputs/{CSV_FILENAME}"
output_object_key = f"projects/{project.project_id}/outputs/{RESULT_FILENAME}"
with caliber.project_scope(project.project_id):
store_status = caliber.object_store.status()
if not isinstance(store_status, dict) or store_status.get("connected") is not True:
raise RuntimeError("CALIBER object store is not connected")
caliber.object_store.create_bucket(bucket)
source = caliber.object_store.upload(
bucket,
filename=CSV_FILENAME,
content=csv_bytes,
key=input_object_key,
media_type="text/csv",
)
stored_input_key = str(_required_mapping_value(source, "key"))
stored_csv = caliber.object_store.download(bucket, stored_input_key)
if stored_csv != csv_bytes:
raise RuntimeError("downloaded CSV does not match the SDK-uploaded input")
managed_source = caliber.object_store.import_object(
bucket,
stored_input_key,
path=f"inputs/{CSV_FILENAME}",
)
managed_file_id = str(_required_mapping_value(managed_source, "file_id"))
prompt_name = f"sdk-financial-analysis-{key}"
created_prompt = caliber.prompts.create(
prompt_name,
PROMPT_TEMPLATE,
commit_message="Create SDK financial-analysis cookbook prompt",
)
prompt_version = int(_required_mapping_value(created_prompt, "version"))
registered_prompt = caliber.prompts.version(prompt_name, prompt_version)
registered_template = str(_required_mapping_value(registered_prompt, "template"))
promotion = caliber.prompts.promote(prompt_name, prompt_version, alias=PROMPT_ALIAS)
if (
_required_mapping_value(promotion, "name") != prompt_name
or _required_mapping_value(promotion, "alias") != PROMPT_ALIAS
or int(_required_mapping_value(promotion, "version")) != prompt_version
):
raise RuntimeError("prompt promotion response does not match the created version")
dashboard_prompt = next(
(item for item in caliber.prompts.list() if item.agent_id == prompt_name),
None,
)
if (
dashboard_prompt is None
or dashboard_prompt.has_prompt is not True
or dashboard_prompt.alias != PROMPT_ALIAS
or dashboard_prompt.version != prompt_version
):
raise RuntimeError("promoted prompt is not visible as final in the prompt dashboard")
session = caliber.aria.sessions.create(
title=f"SDK Financial Analysis {key}",
goal=(f"Follow this registered system prompt exactly:\n\n{registered_template}"),
metadata_={
"source": "sdk-cookbook-17",
# Run the registered prompt as the system prompt (as the Prompts page's Playground
# does) rather than letting Aria treat the message as a request to author a prompt.
"prompt_playground": True,
"project_id": project.project_id,
"prompt_ref": f"prompts:/{prompt_name}@{PROMPT_ALIAS}",
"blob_bucket": bucket,
"blob_key": stored_input_key,
"managed_file_id": managed_file_id,
},
artifact_type="prompt",
skill_mode="off",
)
session_id = str(_required_mapping_value(session, "session_id"))
turn = caliber.aria.sessions.send_message(
session_id,
(
f"Analyze the SDK-uploaded file {CSV_FILENAME}. Its exact stored content is:\n\n"
f"```csv\n{stored_csv.decode('utf-8')}\n```"
),
artifact_type="prompt",
skill_mode="off",
)
analysis = parse_turn_analysis(turn)
result_document = {
"scenario": "monthly_company_financial_analysis",
"project_id": project.project_id,
"blob_bucket": bucket,
"input_object_key": stored_input_key,
"managed_file_id": managed_file_id,
"prompt_name": prompt_name,
"prompt_version": prompt_version,
"prompt_alias": PROMPT_ALIAS,
"assistant_session_id": session_id,
"analysis": analysis,
}
result_bytes = (json.dumps(result_document, indent=2, sort_keys=True) + "\n").encode()
output = caliber.object_store.upload(
bucket,
filename=RESULT_FILENAME,
content=result_bytes,
key=output_object_key,
media_type="application/json",
)
stored_output_key = str(_required_mapping_value(output, "key"))
if caliber.object_store.download(bucket, stored_output_key) != result_bytes:
raise RuntimeError("downloaded result does not match the SDK-uploaded output")
return {
"project_id": project.project_id,
"blob_bucket": bucket,
"input_object_key": stored_input_key,
"managed_file_id": managed_file_id,
"prompt_name": prompt_name,
"prompt_version": prompt_version,
"prompt_alias": PROMPT_ALIAS,
"assistant_session_id": session_id,
"output_object_key": stored_output_key,
"analysis": analysis,
}
def main() -> None:
with env_client() as caliber:
print(json.dumps(run(caliber), indent=2, sort_keys=True))
if __name__ == "__main__":
main()sdk/caliber-sdk/examples/cookbooks/cookbook_17_financial_analysis.py — executed by the SDK example test suite.Cookbook 18 — Projects, Roles, Tokens & Audit
Create a project for a nine-person team, add the members with owner, editor, reviewer and viewer roles, prove the role matrix from a data file with real requests, issue a project-bound access token, show it refused outside its project and after revocation or expiry, release one prompt, and read every one of those actions back from the audit log, the release timeline and readiness. This recipe needs an admin-scoped SDK token and accounts whose platform scopes match the roster.
SDK surfaces: projects, auth, tokens, audit, releases, cookbooks
- Check
/healthand/readiness, and record which providers are simulated. - Create the team's accounts, sign each person in, create the project as its primary owner, and add the members with their roles.
- Send every roster person every action in the role matrix and assert the status code the data file expects (403 for a role that may not, 404 for a non-member).
- Issue a token bound to the project, use it from the SDK and
caliberctlto create and release a prompt, and read the release back from the timeline and the live board. - Provoke the refusals: the primary owner cannot be removed, roles cannot be escalated, a bound token is refused in another project, and a revoked or expired token gets 401.
- Read the audit log by actor, action and entity to find each of those actions, then offboard a member and end the sessions the script opened.
"""Cookbook 18: run a team's project, roles, access tokens and audit trail for real.
A new team lead has to answer four questions before anyone else touches CALIBER:
* Who can do what in this project? (project roles: owner, editor, reviewer, viewer)
* How does automation act as one person inside one project? (a project-bound access token)
* What happens when a token is revoked, expires, or is used in the wrong project?
* Where is the record of all of it? (the audit log, the release timeline, readiness)
This script answers them against a live server and exits 0 only when every documented outcome
was observed. The expectations are data, not code: ``team-roster.csv`` (nine people),
``role-matrix.csv`` (the status code each kind of person must get for each action) and
``failure-scenarios.json`` (the refusals this lab provokes), all under
``docs-site/cookbooks/18-projects-roles-tokens-audit/assets/dataset``.
Run it (see the lab README for the full setup, including the accounts and platform scopes)::
export CALIBER_BASE_URL=http://127.0.0.1:5001 # the deployment URL, not the /ajax-api path
export CALIBER_TOKEN=calpat_... # an ADMIN personal access token
PYTHONPATH=sdk/caliber-sdk caliber/.venv/bin/python \\
-m examples.cookbooks.cookbook_18_projects_roles_tokens_audit
Nothing here needs a real model. The one step that does, an evaluation, is expected to answer 400
"requires a real LLM provider" on a simulated deployment: that answer still proves the caller
passed the project-role gate, which is all this lab is about.
"""
from __future__ import annotations
import csv
import json
import os
import shutil
import subprocess
import sys
import time
import uuid
from collections import Counter
from collections.abc import Callable, Mapping, Sequence
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
import httpx
from caliber_sdk import CaliberClient
from caliber_sdk.errors import CaliberAPIError
from examples.cookbooks._helpers import configuration_blockers, get_recipe
REPO_ROOT = Path(__file__).resolve().parents[4]
DATASET_DIR = (
REPO_ROOT / "docs-site" / "cookbooks" / "18-projects-roles-tokens-audit" / "assets" / "dataset"
)
#: The demo password every roster account gets. It is lab-only and public in this file: never
#: reuse it, and never create these accounts on a deployment anyone else can reach.
DEFAULT_LAB_PASSWORD = "lab18-demo-passphrase"
#: How long the short-lived token lives before the script checks that it expired.
EXPIRY_SECONDS = 3
#: The roster's ``platform_scopes`` column, as the scopes ``GET /auth/session`` must report.
PLATFORM_SCOPE_SETS: dict[str, frozenset[str]] = {
"none": frozenset({"caliber.viewer"}),
"operator": frozenset({"caliber.viewer", "caliber.operator"}),
"operator+approver": frozenset({"caliber.viewer", "caliber.operator", "caliber.approver"}),
}
#: The environment variables that give each roster account its platform scopes.
SCOPE_ENV_HINT = (
"restart CALIBER with CALIBER_OPERATOR_USERS and CALIBER_APPROVER_USERS listing the roster "
"(the lab README, Prerequisites and setup, has the exact values)"
)
Report = Callable[[str], None]
LoginAttempt = Callable[[str, str], tuple[int, str]]
SignIn = Callable[[str, str], str]
UserClient = Callable[[str, str | None], CaliberClient]
HttpPost = Callable[..., httpx.Response]
Sleep = Callable[[float], None]
class VerificationError(AssertionError):
"""A documented outcome was not observed."""
class SetupError(RuntimeError):
"""The deployment is not set up the way the lab needs (a fix, not a defect)."""
# ---------------------------------------------------------------------------
# The dataset files
# ---------------------------------------------------------------------------
def load_roster(directory: Path = DATASET_DIR) -> list[dict[str, str]]:
with (directory / "team-roster.csv").open(newline="", encoding="utf-8") as handle:
return list(csv.DictReader(handle))
def load_matrix(directory: Path = DATASET_DIR) -> list[dict[str, str]]:
with (directory / "role-matrix.csv").open(newline="", encoding="utf-8") as handle:
return list(csv.DictReader(handle))
def load_failure_scenarios(directory: Path = DATASET_DIR) -> list[dict[str, Any]]:
document = json.loads((directory / "failure-scenarios.json").read_text(encoding="utf-8"))
return list(document["scenarios"])
def column_for(person: Mapping[str, str]) -> str:
"""Which ``role-matrix.csv`` column describes this roster person."""
role = person["project_role"]
if role == "none":
return "non_member"
if role == "viewer" and person["platform_scopes"] == "none":
return "viewer_no_operator"
return role
def status_allowed(expected: str, actual: int) -> bool:
"""``expected`` is one status, or several joined with ``|`` (any of them is a pass)."""
return actual in {int(part) for part in expected.split("|")}
# ---------------------------------------------------------------------------
# Small helpers over the SDK
# ---------------------------------------------------------------------------
def call(
client: CaliberClient,
method: str,
path: str,
*,
project: str | None = None,
json_body: Any = None,
params: Mapping[str, Any] | None = None,
) -> tuple[int, Any]:
"""One API call, returning ``(status, data-or-detail)`` instead of raising on 4xx.
The role matrix is about the status code itself, so it goes through the SDK's transport (the
same one the typed methods use, with the same headers, retries and error mapping) rather than
a typed method that would hide the 201-versus-200 distinction.
"""
try:
response = client.raw.raw.request(
method, path, json=json_body, params=params, project=project
)
except CaliberAPIError as exc:
return exc.status_code, exc.detail or str(exc)
return response.status_code, response.data
def _api(base_url: str, path: str) -> str:
return f"{base_url.rstrip('/')}/ajax-api/2.0/mlflow/caliber{path}"
def default_login_attempt(base_url: str) -> LoginAttempt:
"""``POST /auth/login``, returning ``(status, session token or detail)``.
When the deployment enforces CSRF, login is a write like any other, so it carries the
anonymous token ``GET /csrf`` issues for exactly this purpose.
"""
def attempt(user_id: str, password: str) -> tuple[int, str]:
headers: dict[str, str] = {}
csrf = httpx.get(_api(base_url, "/csrf"), timeout=30)
if csrf.status_code == 200:
body = csrf.json().get("data") or {}
if body.get("enabled") and body.get("token"):
headers["X-CALIBER-CSRF"] = str(body["token"])
response = httpx.post(
_api(base_url, "/auth/login"),
json={"user_id": user_id, "password": password},
headers=headers,
timeout=30,
)
if response.status_code == 200:
return 200, str(response.cookies["caliber_session"])
try:
return response.status_code, str(response.json().get("detail", response.text))
except ValueError:
return response.status_code, response.text
return attempt
def sign_in_with(attempt: LoginAttempt) -> SignIn:
"""A sign-in that returns the session token, which a script uses as a bearer token.
The server also sets it as an HttpOnly cookie for the browser; the bearer form is the
supported path for automation.
"""
def sign_in(user_id: str, password: str) -> str:
status, value = attempt(user_id, password)
if status != 200:
raise SetupError(
f"could not sign in as {user_id!r}: {status} {value}. An account left by an "
"earlier run may use another password: reset it under Administration, or set "
"CALIBER_LAB18_PASSWORD"
)
return value
return sign_in
def default_user_client(base_url: str, opened: list[CaliberClient]) -> UserClient:
def user_client(token: str, project: str | None = None) -> CaliberClient:
client = CaliberClient(base_url, token=token, project=project)
opened.append(client)
return client
return user_client
def find_caliberctl() -> list[str] | None:
"""The ``caliberctl`` command of this interpreter's environment, if it is installed."""
beside = Path(sys.executable).parent / "caliberctl"
if beside.exists():
return [str(beside)]
found = shutil.which("caliberctl")
return [found] if found else None
def run_caliberctl(command: list[str], base_url: str, token: str, *args: str) -> Any:
environment = {**os.environ, "CALIBER_BASE_URL": base_url, "CALIBER_TOKEN": token}
environment.pop("CALIBER_PROJECT", None)
completed = subprocess.run(
[*command, "--json", *args],
capture_output=True,
text=True,
env=environment,
timeout=120,
check=False,
)
if completed.returncode != 0:
raise VerificationError(
f"caliberctl {' '.join(args)} exited {completed.returncode}: {completed.stderr.strip()}"
)
return json.loads(completed.stdout)
# ---------------------------------------------------------------------------
# The lab
# ---------------------------------------------------------------------------
def run(
caliber: CaliberClient,
*,
base_url: str,
password: str = DEFAULT_LAB_PASSWORD,
run_key: str | None = None,
login_attempt: LoginAttempt | None = None,
user_client: UserClient | None = None,
dataset_dir: Path = DATASET_DIR,
use_caliberctl: bool = True,
http_post: HttpPost = httpx.post,
sleep: Sleep | None = None,
report: Report | None = None,
) -> dict[str, object]:
"""Run the whole lab. ``caliber`` is an ADMIN client (an admin personal access token)."""
say: Report = report or (lambda _line: None)
key = run_key or uuid.uuid4().hex[:6]
opened: list[CaliberClient] = []
attempt_login = login_attempt or default_login_attempt(base_url)
sign_in = sign_in_with(attempt_login)
make_client = user_client or default_user_client(base_url, opened)
roster = load_roster(dataset_dir)
matrix = load_matrix(dataset_dir)
scenarios = load_failure_scenarios(dataset_dir)
people = {person["user_id"]: person for person in roster}
failures: list[str] = []
def check(label: str, ok: bool, detail: str = "") -> None:
say(f"{'ok ' if ok else 'FAIL'} {label}" + (f" [{detail}]" if detail else ""))
if not ok:
failures.append(f"{label} {detail}".strip())
try:
# -- 1. The deployment is healthy, and says what is simulated -----------------------
admin = caliber.me.get()
check("the token is an admin", bool(admin.is_admin), admin.user_id)
if not admin.is_admin:
raise SetupError("CALIBER_TOKEN must be an admin personal access token")
health = caliber.health()
check("GET /health reports ok", health.get("status") == "ok", str(health))
readiness = caliber.readiness()
check(
"GET /readiness is ready",
readiness.get("ready") is True,
f"blockers: {readiness.get('blockers')}",
)
simulated = sorted(readiness.get("simulated") or [])
providers: dict[str, Any] = next(
(item for item in readiness.get("checks", []) if item.get("name") == "providers"), {}
)
say(f" simulated providers: {simulated or 'none (all real)'}")
check(
"readiness names every simulated provider",
(not simulated and readiness.get("all_real") is True)
or (
bool(simulated)
and providers.get("ready") is False
and "simulated" in str(providers)
),
str(providers.get("detail")),
)
installed_workflow = ""
cookbooks_enabled = bool(caliber.capabilities()["features"]["cookbooks"]["enabled"])
# -- 2. Accounts: an admin creates them, each one signs in ---------------------------
listed = {account.user_id: account for account in caliber.auth.accounts.list()}
existing = set(listed)
created = [user for user in people if user not in existing]
for user in created:
caliber.auth.accounts.create(user, password)
for user in people:
if user in listed and listed[user].disabled:
caliber.auth.accounts.update(user, disabled=False) # left disabled by --cleanup
check(
"every roster account exists",
True,
f"{len(created)} created, {len(people) - len(created)} already there",
)
tokens: dict[str, str] = {user: sign_in(user, password) for user in people}
clients: dict[str, CaliberClient] = {
user: make_client(token, None) for user, token in tokens.items()
}
for user, person in people.items():
session = clients[user].auth.session()
expected_scopes = PLATFORM_SCOPE_SETS[person["platform_scopes"]]
if set(session.scopes) != expected_scopes:
raise SetupError(
f"{user} holds {sorted(session.scopes)} but the roster needs "
f"{sorted(expected_scopes)}: {SCOPE_ENV_HINT}"
)
check("every account holds exactly the platform scopes the roster lists", True)
# -- 3. The project: maya creates it, then adds the team ------------------------------
lead = clients["maya"]
project = lead.projects.create(
f"lab18-support-copilot-{key}", description="Support copilot (cookbook 18)"
)
project_id = project.project_id
check(
"the creator is the project's primary owner",
project.owner == "maya" and project.access_role == "owner",
)
for person in roster:
if person["project_role"] == "none":
continue
if person["user_id"] == "maya":
continue
lead.projects.add_member(project_id, person["user_id"], role=person["project_role"])
members = {member.user_id: member.role for member in lead.projects.list_members(project_id)}
wanted = {
person["user_id"]: person["project_role"]
for person in roster
if person["project_role"] != "none"
}
check("the member list is exactly the roster", members == wanted, f"{len(members)} members")
wrong_roles = []
for user, person in people.items():
if person["project_role"] == "none":
status, _ = call(
clients[user], "GET", f"/projects/{project_id}", project=project_id
)
if status != 404:
wrong_roles.append(f"{user}:{status}")
continue
seen = clients[user].projects.get(project_id).access_role
if seen != person["project_role"]:
wrong_roles.append(f"{user}:{seen}")
check(
"every person sees the role the roster gave them (the outsider sees 404)",
not wrong_roles,
", ".join(wrong_roles),
)
# Fixtures the matrix acts on, created by the owner so every person starts equal.
target_prompt = f"lab18-{key}-matrix-target"
call(
lead,
"POST",
"/prompts",
project=project_id,
json_body={
"name": target_prompt,
"template": "Answer the customer question: {{question}}",
},
)
matrix_dataset = lead.raw.raw.request(
"POST",
"/eval-datasets",
json={"name": f"lab18-{key}-matrix-set", "owner": "maya"},
project=project_id,
).data["dataset_id"]
lead.raw.raw.request(
"POST",
f"/eval-datasets/{matrix_dataset}/examples",
json={
"input": {"question": "Where is my order?"},
"expected": {"answer": "Check the tracking link"},
},
project=project_id,
)
# -- 4. The role matrix: every person x every action, from the data file --------------
def attempt(user: str, action_id: str) -> tuple[int, Any]:
client = clients[user]
tag = f"lab18-{key}-{user}"
requests: dict[str, tuple[str, str, Any]] = {
"project.read": ("GET", f"/projects/{project_id}", None),
"members.list": ("GET", f"/projects/{project_id}/members", None),
"dataset.create": ("POST", "/eval-datasets", {"name": f"{tag}-set", "owner": user}),
"prompt.create": (
"POST",
"/prompts",
{"name": f"{tag}-prompt", "template": "Reply to {{customer}}."},
),
"prompt.promote": (
"POST",
f"/prompts/{target_prompt}/aliases/prod",
{"version": 1},
),
"evaluation.run": (
"POST",
"/evaluations",
{
"dataset_id": matrix_dataset,
"scorers": ["non_empty"],
"predict_target": "prompt",
"subject_ref": f"{target_prompt}@1",
"label": f"lab18 {user}",
},
),
"project.update": (
"PATCH",
f"/projects/{project_id}",
{"description": f"edited by {user}"},
),
"members.update": (
"PATCH",
f"/projects/{project_id}/members/wen",
{"role": "viewer"},
),
}
method, path, body = requests[action_id]
return call(client, method, path, project=project_id, json_body=body)
unknown_actions = [
row["action_id"] for row in matrix if not _known_action(row["action_id"])
]
if unknown_actions:
raise VerificationError(
f"role-matrix.csv names actions the script cannot run: {unknown_actions}"
)
cells = 0
wrong_cells: list[str] = []
outcomes: Counter[str] = Counter()
for person in roster:
user = person["user_id"]
column = column_for(person)
for row in matrix:
status, detail = attempt(user, row["action_id"])
cells += 1
expected = row[column]
if status_allowed(expected, status):
outcomes[f"{column}:{status}"] += 1
else:
wrong_cells.append(
f"{user}/{row['action_id']}: expected {expected}, got {status} "
f"({str(detail)[:80]})"
)
check(
f"the role matrix holds ({cells} requests: {len(roster)} people "
f"x {len(matrix)} actions)",
not wrong_cells,
"; ".join(wrong_cells),
)
# -- 5. A project-bound token, used from the SDK and from caliberctl ------------------
editor = clients["priya"]
issued = editor.auth.tokens.create(
f"support-ci-{key}",
scopes=["caliber.operator"],
project_id=project_id,
)
check(
"the token carries its project binding",
issued.project_id == project_id,
issued.token_id,
)
listed_tokens = editor.raw.get("/auth/tokens")["tokens"]
check(
"the secret is only on the issuing response, never in the list",
bool(issued.token) and all("token" not in row for row in listed_tokens),
)
bound = make_client(issued.token, None)
who = bound.me.get()
check("the bound token acts as its owner", who.user_id == "priya", who.user_id)
check(
"with no project named, it acts in its bound project",
bound.projects.get(project_id).access_role == "editor",
)
prompt_name = f"lab18-{key}-support-reply"
bound.prompts.create(
prompt_name,
"Reply to the customer politely.\n\nQuestion: {{question}}",
commit_message="v1",
)
release = bound.prompts.promote(prompt_name, 1)
check(
"the prompt is released to @prod by the token",
release.get("release_status") == "applied",
str(release.get("operation_id")),
)
if cookbooks_enabled:
recipe = get_recipe(caliber, "18")
blockers = configuration_blockers(recipe)
check(
"cookbook 18 is in the catalog with its guided steps",
bool(recipe.steps),
f"{len(recipe.steps)} steps",
)
if not blockers:
installed = bound.cookbooks.install(
"18",
name=f"Cookbook 18 - Projects, roles, tokens and audit ({key})",
acknowledge_prerequisites=bool(recipe.prerequisites),
)
installed_workflow = str(installed["workflow"].get("workflow_id"))
check(
"the lab installs into the project through the bound token",
installed["workflow"].get("project_id") == project_id,
installed_workflow,
)
# The prompt inventory follows the project it is asked for: a member sees the project's
# prompts (and the agent prompt of the workflow just installed), a non-member sees none
# of them.
def inventory(user: str) -> list[str]:
_status, rows = call(clients[user], "GET", "/prompts", project=project_id)
return [str(row.get("agent_id")) for row in rows] if isinstance(rows, list) else []
project_prompts = {target_prompt, prompt_name}
seen_by_viewer = inventory("victor")
check(
"a viewer's prompt inventory lists the project's prompts",
project_prompts <= set(seen_by_viewer),
f"{len(seen_by_viewer)} prompts",
)
leaked = [
name
for name in inventory("nora")
if name in project_prompts or (installed_workflow and installed_workflow in name)
]
check(
"a non-member's prompt inventory shows nothing from the project",
not leaked,
", ".join(leaked),
)
if use_caliberctl:
command = find_caliberctl()
if command is None:
say("skip caliberctl is not installed in this environment")
else:
whoami = run_caliberctl(command, base_url, issued.token, "whoami")
check(
"caliberctl whoami sees the same identity",
whoami.get("user_id") == "priya",
str(whoami.get("scopes")),
)
listed = run_caliberctl(command, base_url, issued.token, "token", "list")
rows = listed if isinstance(listed, list) else listed.get("tokens", [])
check(
"caliberctl token list shows the bound token",
any(
row.get("token_id") == issued.token_id
and row.get("project_id") == project_id
for row in rows
),
)
prompts = run_caliberctl(
command, base_url, issued.token, "--project", project_id, "prompt", "list"
)
names = [
item.get("name") or item.get("prompt_name") or item.get("agent_id")
for item in (
prompts if isinstance(prompts, list) else prompts.get("prompts", [])
)
]
check("caliberctl prompt list shows the released prompt", prompt_name in names)
# -- 6. The release timeline and the live board show the release ----------------------
timeline = bound.raw.get(
"/releases/timeline", params={"entity_type": "prompt", "limit": 200}
)
mine = [row for row in timeline if row.get("entity_id") == prompt_name]
check(
"the release timeline has exactly one promote event for the prompt, by priya",
len(mine) == 1
and mine[0]["action"] == "promote_prompt"
and mine[0]["actor"] == "priya",
str(mine[0].get("details")) if mine else "none",
)
live = bound.releases.live()
live_row = next((row for row in live if row.get("artifact_id") == prompt_name), None)
check(
"the live board lists the prompt at v1 on @prod",
live_row is not None
and live_row.get("version_id") == "v1"
and live_row.get("alias") == "prod",
str(live_row),
)
# -- 7. A second project, and the token used outside the project it is bound to ------
other = lead.projects.create(
f"lab18-billing-assistant-{key}",
description="A second project the token is not bound to",
)
failure_results: dict[str, str] = {}
def verdict(scenario_id: str, status: int, detail: Any) -> None:
scenario = next(item for item in scenarios if item["id"] == scenario_id)
ok = (
status == scenario["expected_status"]
and str(scenario["detail_contains"]).lower() in str(detail).lower()
)
check(f"{scenario_id} {scenario['title']}", ok, f"{status} {str(detail)[:90]}")
failure_results[scenario_id] = str(status)
verdict(
"F01",
*call(
clients["omar"],
"DELETE",
f"/projects/{project_id}/members/maya",
project=project_id,
),
)
verdict(
"F02",
*call(
clients["omar"],
"PATCH",
f"/projects/{project_id}/members/maya",
project=project_id,
json_body={"role": "viewer"},
),
)
verdict(
"F03",
*call(
clients["priya"],
"PATCH",
f"/projects/{project_id}/members/priya",
project=project_id,
json_body={"role": "owner"},
),
)
verdict(
"F04",
*call(
clients["quinn"],
"POST",
f"/projects/{project_id}/members",
project=project_id,
json_body={"user_id": "nora", "role": "viewer"},
),
)
verdict(
"F05",
*call(
clients["maya"],
"PATCH",
f"/projects/{project_id}/members/victor",
project=project_id,
json_body={"role": "owner"},
),
)
verdict(
"F06",
*call(
clients["maya"],
"POST",
f"/projects/{project_id}/members",
project=project_id,
json_body={"user_id": "nora", "role": "admin"},
),
)
verdict(
"F07",
*call(
clients["priya"],
"POST",
"/auth/tokens",
json_body={"name": "too-much", "scopes": ["caliber.admin"]},
),
)
verdict(
"F08",
*call(
clients["nora"],
"POST",
"/auth/tokens",
json_body={"name": "not-mine", "project_id": project_id},
),
)
viewer_scoped = clients["maya"].auth.tokens.create(
f"viewer-only-{key}", scopes=["caliber.viewer"]
)
verdict(
"F09",
*call(
make_client(viewer_scoped.token, None),
"POST",
"/prompts",
project=project_id,
json_body={"name": f"lab18-{key}-denied", "template": "x {{y}}"},
),
)
clients["maya"].auth.tokens.revoke(viewer_scoped.token_id)
verdict(
"F10", *call(bound, "GET", f"/projects/{other.project_id}", project=other.project_id)
)
check(
"the bound token still works in its own project after the refusal",
bound.projects.get(project_id).project_id == project_id,
)
# Revocation: priya revokes the bound token; it stops working at once.
revoked = editor.auth.tokens.revoke(issued.token_id)
check("revoking reports a live token was revoked", revoked is True)
verdict("F11", *call(bound, "GET", "/projects", project=None))
check(
"whoami does not raise for a revoked token: it answers anonymous",
bound.me.get().is_anonymous,
)
# Expiry: a token whose expires_at passes stops authenticating.
soon = (datetime.now(timezone.utc) + timedelta(seconds=EXPIRY_SECONDS)).isoformat()
short = editor.auth.tokens.create(f"short-lived-{key}", expires_at=soon)
short_client = make_client(short.token, None)
status_before, _ = call(short_client, "GET", "/projects")
check("a token works before it expires", status_before == 200, str(status_before))
(sleep or time.sleep)(EXPIRY_SECONDS + 1)
verdict("F12", *call(short_client, "GET", "/projects"))
verdict("F13", *call(make_client("calpat_not-a-real-token", None), "GET", "/projects"))
verdict("F14", *attempt_login("maya", "not-the-password-123"))
verdict("F15", *call(clients["maya"], "GET", "/audit-log", params={"limit": 1}))
# CSRF is off by default. When the deployment turns it on, a write without the header
# is refused, and the SDK (which fetches a token and replays the write) is not affected.
csrf = caliber.raw.get("/csrf")
csrf_enabled = bool(csrf.get("enabled"))
if csrf_enabled:
plain = http_post(
_api(base_url, f"/projects/{project_id}/members"),
json={"user_id": "nora", "role": "viewer"},
headers={
"Authorization": f"Bearer {tokens['maya']}",
"X-CALIBER-Project": project_id,
},
timeout=30,
)
verdict("F16", plain.status_code, plain.json().get("detail", ""))
lead.projects.add_member(project_id, "nora", role="viewer")
lead.projects.remove_member(project_id, "nora")
check("the SDK replays a write with a CSRF token and it succeeds", True)
else:
say("skip F16: CSRF enforcement is off on this deployment (the default)")
# -- 8. Offboarding: removing a member takes the project away from them ---------------
removed = lead.projects.remove_member(project_id, "victor")
status_after, _ = call(
clients["victor"], "GET", f"/projects/{project_id}", project=project_id
)
check(
"a removed member gets 404 straight away",
removed is True and status_after == 404,
str(status_after),
)
remaining = {member.user_id for member in lead.projects.list_members(project_id)}
check(
"the member list no longer shows them",
"victor" not in remaining and len(remaining) == len(wanted) - 1,
)
# -- 9. The audit log: every one of those actions, filterable ------------------------
project_rows = caliber.audit.list(entity_id=project_id, limit=500)
by_action = Counter(row.action for row in project_rows)
check(
"audit: create_project by maya for this project",
any(row.action == "create_project" and row.actor == "maya" for row in project_rows),
)
check(
f"audit: add_project_member once per member ({len(wanted) - 1} added by maya)",
by_action["add_project_member"] == len(wanted) - 1 + (1 if csrf_enabled else 0),
str(by_action["add_project_member"]),
)
added = {
row.details.get("user_id"): row.details.get("role")
for row in project_rows
if row.action == "add_project_member"
}
check(
"audit: the roles recorded match the roster",
all(added.get(user) == role for user, role in wanted.items() if user != "maya"),
)
check(
"audit: update_project_member rows name the owners who edited",
{row.actor for row in project_rows if row.action == "update_project_member"}
== {"maya", "omar"},
)
check(
"audit: update_project rows name the owners and editors who edited",
{row.actor for row in project_rows if row.action == "update_project"}
== {"maya", "omar", "priya", "sam"},
)
check(
"audit: remove_project_member victor by maya",
any(
row.action == "remove_project_member"
and row.actor == "maya"
and row.details.get("user_id") == "victor"
for row in project_rows
),
)
denied_rows = [
row
for row in project_rows
if row.actor in {"quinn", "rosa", "victor", "wen", "nora"}
and row.action in {"update_project", "update_project_member", "add_project_member"}
]
check(
"audit: refused requests leave no project audit rows",
not denied_rows,
str([row.actor for row in denied_rows]),
)
token_rows = caliber.audit.list(
entity_type="personal_access_token", actor="priya", limit=500
)
created_row = next(
(
row
for row in token_rows
if row.entity_id == issued.token_id and row.action == "create_personal_access_token"
),
None,
)
revoked_row = next(
(
row
for row in token_rows
if row.entity_id == issued.token_id and row.action == "revoke_personal_access_token"
),
None,
)
check(
"audit: the bound token's creation names its project, and its revocation is recorded",
created_row is not None
and created_row.details.get("project_id") == project_id
and revoked_row is not None,
)
check(
"audit: no token secret is in any audit row",
issued.token not in json.dumps([row.details for row in token_rows]),
)
promote_rows = caliber.audit.list(action="promote_prompt", entity_id=prompt_name, limit=50)
check(
"audit: promote_prompt for the released prompt, by priya, not overridden",
len(promote_rows) == 1
and promote_rows[0].actor == "priya"
and promote_rows[0].details.get("overridden") is False,
)
account_rows = caliber.audit.list(entity_type="account", action="create_account", limit=500)
check(
"audit: create_account by admin for every roster account",
{row.entity_id for row in account_rows} >= set(people)
and {row.actor for row in account_rows} <= {admin.user_id},
)
sign_ins = caliber.audit.list(
entity_type="session", action="sign_in", actor="maya", limit=5
)
check("audit: sign_in rows name who signed in", bool(sign_ins))
# -- 10. End the sessions the script opened -------------------------------------------
ended = sum(caliber.auth.accounts.revoke_sessions(user) for user in people)
check("the sessions the script opened are revoked", ended >= len(people), str(ended))
finally:
for client in opened:
client.close()
if failures:
raise VerificationError(f"{len(failures)} check(s) failed:\n " + "\n ".join(failures))
return {
"project_id": project_id,
"other_project_id": other.project_id,
"members": len(wanted),
"matrix_requests": cells,
"matrix_outcomes": dict(sorted(outcomes.items())),
"failure_scenarios": dict(sorted(failure_results.items())),
"bound_token_id": issued.token_id,
"released_prompt": prompt_name,
"simulated_providers": simulated,
"csrf_enabled": csrf_enabled,
"run_key": key,
}
_ACTIONS = frozenset(
{
"project.read",
"members.list",
"dataset.create",
"prompt.create",
"prompt.promote",
"evaluation.run",
"project.update",
"members.update",
}
)
def _known_action(action_id: str) -> bool:
return action_id in _ACTIONS
def cleanup(
caliber: CaliberClient,
*,
base_url: str,
password: str = DEFAULT_LAB_PASSWORD,
sign_in: SignIn | None = None,
user_client: UserClient | None = None,
dataset_dir: Path = DATASET_DIR,
report: Report | None = None,
) -> dict[str, int]:
"""Archive the projects this lab created and disable the roster accounts.
The lab's projects are named ``lab18-...``; only their primary owner (maya) can archive them.
Disabling an account also revokes its sessions. Nothing here deletes data: an archived
project is hidden, not erased, and a later run re-enables the accounts it needs.
"""
say: Report = report or (lambda _line: None)
roster = load_roster(dataset_dir)
sign = sign_in or sign_in_with(default_login_attempt(base_url))
opened: list[CaliberClient] = []
make_client = user_client or default_user_client(base_url, opened)
archived = 0
try:
existing = {account.user_id for account in caliber.auth.accounts.list()}
if "maya" in existing:
lead = make_client(sign("maya", password), None)
for project in lead.projects.list():
if project.name.startswith("lab18-") and project.owner == "maya":
lead.projects.archive(project.project_id)
archived += 1
say(f"archived {project.name} ({project.project_id})")
disabled = 0
for person in roster:
if person["user_id"] in existing:
caliber.auth.accounts.update(person["user_id"], disabled=True)
disabled += 1
say(f"disabled {disabled} roster account(s)")
finally:
for client in opened:
client.close()
return {"archived_projects": archived, "disabled_accounts": disabled}
def main(argv: Sequence[str] | None = None) -> int:
base_url = os.environ["CALIBER_BASE_URL"]
token = os.environ["CALIBER_TOKEN"]
password = os.environ.get("CALIBER_LAB18_PASSWORD", DEFAULT_LAB_PASSWORD)
lines: list[str] = []
def report(line: str) -> None:
lines.append(line)
print(line, flush=True)
with CaliberClient(base_url, token=token) as caliber:
if "--cleanup" in (argv or ()):
print(json.dumps(cleanup(caliber, base_url=base_url, password=password, report=report)))
return 0
try:
summary = run(caliber, base_url=base_url, password=password, report=report)
except (VerificationError, SetupError) as exc:
print(f"\nNOT VERIFIED: {exc}", file=sys.stderr)
return 1
print(json.dumps(summary, indent=2, sort_keys=True))
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))sdk/caliber-sdk/examples/cookbooks/cookbook_18_projects_roles_tokens_audit.py — executed by the SDK example test suite.