Calibration profiles

Calibration profiles

A calibration profile is a versioned, auditable resource: the labelled data, the backend fingerprint, the method, and the target α\alpha that back every guarantee CLI issues. Every primitive names one with calibration_profile=..., and every guarantee card names it back.

All profile operations live on client.calibration_profiles (the same methods, awaited, on AsyncCLIClient).

Lifecycle

A profile calibrates one query definition against one backend. It moves through these states, shown as profile.status:

statusMeaning
collectingCreated; examples may be stored, but no query is bound yet, or there are too few scored examples
calibratingThe first calibration is running as a background job
servingCalibrated with enough examples: answers carry guarantees
staleSomething the calibration depends on changed (profile.stale on the card says what)
  1. Create the profile with a name, a backend and a method. Nothing is scored yet.
  2. Add examples. Before the first evaluate, they are stored as they are.
  3. The first evaluate that names the profile binds it: the query’s type, instructions, options or levels, criteria, support source and task, and the backend, are recorded, and the stored examples are scored. When that needs at most 200 estimated model calls, calibration runs inside the request and the answer already carries a guarantee. Otherwise it runs as a background job: the status is calibrating, and answers are heuristic (424) with a warning naming the job until it finishes.
  4. Examples added later are appended: they are scored and folded in, n grows and version stays. Small appends run inline; larger ones run as a job, and the card shows pending_n and job meanwhile.
  5. A full recalibration (POST .../calibrate, or a backend change on a non-strict profile) re-scores every example and increments version. The last 10 versions are kept.
import time
 
def wait_until_serving(client, name, every_s=10, timeout_s=3600):
    """Block until the profile's calibration job has finished."""
    deadline = time.monotonic() + timeout_s
    while True:
        profile = client.calibration_profiles.get(name)
        if profile.status == "serving":
            return profile
        if time.monotonic() > deadline:
            raise TimeoutError(f"{name} is still {profile.status}")
        time.sleep(every_s)

One profile per query

Because the profile stores scores computed for one query, a different query against a bound profile is refused with 422 query_mismatch. Give every query its own profile: a Set and the Gate that decides whether to act on it are two profiles, as in the support routing guide.

Part of the queryOn a bound profile
type, instructions, options, levels, criteria, support_source, taskFixed: changing one is 422 query_mismatch
alpha, target, delta, method, a Gate’s guarantee, a Route’s target_centsMay change per request: the threshold is recomputed from the stored scores, with no new model calls

Profiles are versioned resources, so their configuration never changes after creation either. Creating a profile again with an identical configuration returns the existing one (200); with a different one it fails with 409 profile_exists, and details.differences names the fields. Use a new name, such as support-routing-v4, for a new configuration.

Creating a profile

from cli_sdk import CLIClient, OpenAIBackend
 
with CLIClient() as client:
    profile = client.calibration_profiles.create(
        name="support-routing-v3",
        backend=OpenAIBackend(model="gpt-4.1-2025-04-14"),
        method="APS",
        alpha=0.10,
        prompt_template_hash="sha256:9f2c...",   # optional, recorded in the fingerprint
    )
    print(profile.status)    # "collecting"
ArgumentDefaultMeaning
namerequiredProfile name, referenced by queries. Letters, digits, ., _ or -, at most 128 characters; unique per organization, ignoring case.
backendrequiredThe backend the profile is calibrated against (object or dict).
method"APS"One of LAC, APS, RAPS, CQR, ordinal-aps, CRC, RCPS, LTT, IVAP, CVAP, conformal-factuality, trust-or-escalate, calibrated-cascade.
alpha0.10Target level, in (0,1)(0, 1).
group_byNoneContext field for group-conditional (Mondrian) calibration.
prompt_template_hashNoneHash of the prompt template, part of the backend fingerprint.
strict_fingerprintTrueWhat a request with a different backend does (below).

An unknown method or an alpha outside (0,1)(0, 1) raises ConfigurationError (a ValueError) before any request is sent. Once the profile is bound, the card’s method and alpha are those of the bound query; the values given at creation stay on the card as registered.

A profile can also be created with "retention": "zero" over HTTP, which the SDK’s create does not send; see zero retention.

Adding examples

from cli_sdk import CalibrationExample
 
profile = client.calibration_profiles.add_examples(
    "support-routing-v3",
    examples=[
        CalibrationExample(context={"ticket": "I was charged twice."}, label="billing"),
        {"context": {"ticket": "The export button does nothing."}, "label": "technical"},
    ],
)
print(profile.n, profile.status)

Examples can be CalibrationExample objects or plain dicts with context and label keys. Dicts may carry extra keys the service accepts, such as evidence (below) or your own id.

CalibrationExample fieldDefaultMeaning
contextrequiredThe same shape you pass to evaluate.
labelrequiredThe correct answer: an option key (Set, Route), a level name (Interval), True/False (Belief, Gate), "response_a"/"response_b" (Judge), or a list of {"text", "supported"} claims (Claim).
source"human""human" or "judge": who produced the label. Judge-labelled rows are stored but never set conformal thresholds. Anything else raises ConfigurationError.
groupNoneMondrian group, when the group_by field is not in context.
metadata{}Free-form metadata stored with the example (at most 8 KB).

On a bound profile, labels are checked against the query when you upload them (422 naming the example). Before binding they are checked when the query binds, and examples whose label does not fit are counted as ineligible on the card. Up to 10,000 examples per call and 100,000 per profile.

Calibration examples must be exchangeable with the traffic the guarantee will cover: a random sample of real production inputs, labelled, not a curated set of hard or easy cases. See Exchangeability.

Client-evidence examples

When the profile’s backend is your own model (a CustomBackend), the service never calls a model, so it cannot score examples itself. Each human-labelled example must carry the evidence your backend produces for its context, computed exactly as evaluate computes it:

from cli_sdk import CLIClient, Set
 
DEPARTMENT = Set(
    instructions="Which team should handle this ticket?",
    options={"billing": "Payments, invoicing, refunds", "technical": "Bugs, outages, integrations"},
    calibration_profile="triage-inhouse-v1",
    alpha=0.10,
)
model = MyEngine()          # your CustomBackend
 
with CLIClient(backend=model) as client:
    client.calibration_profiles.create("triage-inhouse-v1", backend=model, method="APS", alpha=0.10)
    client.calibration_profiles.add_examples("triage-inhouse-v1", examples=[
        {
            "context": context,
            "label": label,
            "evidence": model.collect_evidence(DEPARTMENT.to_payload(), context,
                                               sample_count=client.sample_count),
        }
        for context, label in labelled
    ])

Use the same query object, and the same sample_count at L0, that you evaluate with: the evidence is the scoring function. Examples without evidence are refused once the profile is bound to client evidence, and counted as ineligible before. Client-evidence calibration makes no model calls, so it always runs inline. For Claim, the evidence is a list of {"text", "score"} claims, which needs a collect_evidence override.

Route examples

A Route profile is calibrated on examples with a context and the correct label, an option key of the route’s task. The service runs every stage of the cascade on each example’s context to learn the escalation threshold, so calibrating a route costs one scoring pass per stage and example. A tier_outputs field is accepted and stored, but the hosted engine does not use it.

Backend changes and strict_fingerprint

Each request’s backend is fingerprinted (provider, model, access level, sample count at L0, endpoint, engine settings, prompt template hash; see Backends) and compared with the fingerprint the profile was calibrated with.

strict_fingerprint=True (default)strict_fingerprint=False
A request arrives with a different backendThe profile becomes stale (reason backend_changed); this request’s answers fail closed (424, heuristic)A recalibration job for the new backend is queued (at most once every 10 minutes); answers are heuristic until it finishes
Requests with the calibrated backendKeep being served, with a warningServed by the new calibration once it is done
To adopt the new backendPOST .../calibrate with the new backendAutomatic

Strict is the right default for anything that acts on answers: a model swap is something to decide, not something a request should trigger. POST .../calibrate re-scores every stored example with the backend you send (or the bound one), promotes a new version and clears the stale state; the SDK has no method for it, so call it over HTTP:

import os
import uuid
 
import httpx
 
API = os.environ.get("CLI_BASE_URL", "https://cci.gitdate.ink/api/v1").rstrip("/")
 
 
def recalibrate(name, backend=None):
    body = {"backend": backend} if backend else {}
    response = httpx.post(f"{API}/calibration-profiles/{name}/calibrate", json=body, timeout=300,
                          headers={"Authorization": f"Bearer {os.environ['CLI_API_KEY']}",
                                   "Idempotency-Key": str(uuid.uuid4())})
    response.raise_for_status()
    return response.json()      # {"status": "completed", ...} or 202 {"status": "queued", "job": {...}}
 
 
recalibrate("support-routing-v3", {"provider": "openai", "model": "gpt-4.1-2025-06-01"})

A recalibration that produces a new version supersedes the profile’s monitors (their status becomes superseded): create new monitors for the new version. A zero-retention profile has no contexts to re-score, so a backend change makes it stale with reason contexts_required instead; upload the examples again, or use a new profile.

Reading a profile

profile = client.calibration_profiles.get("support-routing-v3")
print(profile.status)                # "serving"
print(profile.n)                     # 1204
print(profile.version)               # 3
print(profile.minimum_n)             # 9
print(profile.recommended_n)         # 1000
print(profile.realized_coverage_ci)  # (0.886, 0.914)
print(profile.can_serve_guarantees)  # True
print(profile.last_audit)            # {"id": "aud_...", "date": "2026-09-18", "sample": 300, "result": "pass", ...}
print(profile.backend_fingerprint)   # {"provider": "openai", "model": "gpt-4.1-2025-04-14", "access_level": "L1", ...}
 
for p in client.calibration_profiles.list():
    print(p.name, p.version, p.status)
AttributeMeaning
name, version, method, alphaIdentity and configuration.
nLabelled examples currently backing the threshold.
minimum_nThe hard floor for the bound query: ⌈(1−α)/α⌉\lceil (1-\alpha)/\alpha \rceil for coverage, more for some guarantees (for example 22 for a Route cost budget at α=0.10\alpha = 0.10).
recommended_nSize for a stable guarantee (see Sizing).
realized_coverage_ciInterval for realized coverage given this calibration set.
can_serve_guaranteesn >= minimum_n.
last_auditThe most recent audit record, if any.
backend_fingerprintWhat the profile was calibrated against.
group_by, groupsMondrian field, and per-group GroupStatus(n, status).
status"collecting", "calibrating", "serving", or "stale".

The card the service returns has more than the SDK’s CalibrationProfile keeps: pending_n, counts, binding, stale ({reason, since, ...}), job, retention, monitors_count and served_count. Read them with GET /v1/calibration-profiles/{name} (API reference), or in the dashboard under Observability > Profiles.

Sizing

α\alphaHard minimum ⌈(1−α)/α⌉\lceil (1-\alpha)/\alpha \rceilRecommended for a stable guarantee
0.204about 300
0.109about 1,000
0.0519about 1,500
0.0199about 2,500

A profile below its hard minimum cannot serve coverage, risk, or fdr guarantees at all — queries against it return a heuristic-labelled answer instead (see Errors and retries). Below the recommended size, CLI still serves the guarantee but reports a wider coverage_ci, so callers see the real uncertainty in the calibration itself rather than a false sense of precision.

The same numbers are available offline:

from cli_sdk.calibration import recommended_size
from cli_sdk.stats.conformal import coverage_confidence_interval, minimum_calibration_size
 
minimum_calibration_size(0.10)                 # 9
recommended_size(0.10)                         # 1000
coverage_confidence_interval(1204, 0.10)       # 90% interval for realized coverage

Realized coverage given a fixed calibration set of size nn follows a Beta(n+1−ℓ, ℓ)\mathrm{Beta}(n+1-\ell,\ \ell) distribution with ℓ=⌊(n+1)α⌋\ell = \lfloor (n+1)\alpha \rfloor, centred just above 1−α1-\alpha, and its spread shrinks roughly as 1/n1/\sqrt{n}. The guarantee is the average over calibration draws; the interval tells you how far your particular draw can sit from it.

Group-conditional (Mondrian) profiles

client.calibration_profiles.create(
    name="support-routing-by-tier",
    backend=OpenAIBackend(model="gpt-4.1-2025-04-14"),
    method="APS",
    alpha=0.10,
    group_by="account_tier",
)
 
profile = client.calibration_profiles.get("support-routing-by-tier")
for tier, status in profile.groups.items():
    print(tier, status.n, status.status)   # e.g. "enterprise 212 calibrated", "startup 6 underpowered"

Each distinct value of account_tier seen in the calibration examples gets its own quantile, and its own minimum-nn enforcement. Groups below the minimum fall back to the marginal (ungrouped) threshold and are reported with status == "underpowered": their answers carry the marginal guarantee, not a per-group one, and the response says so in warnings.

Label-efficient calibration

Human labelling is almost always the bottleneck. A profile can combine a large judge-labelled pool with a small, random human-labelled sample through prediction-powered inference (PPI). The combined estimate is unbiased whatever the judge’s quality: a poor judge widens its interval, it does not bias it. The interval is a large-sample (central limit theorem) interval, not a finite-sample one. The finite-sample conformal guarantees on the profile’s answers rest on the human-labelled examples; the judge-labelled pool narrows estimates, it does not replace them.

job = client.calibration_profiles.label_with_judge(
    "support-routing-v3",
    judge=OpenAIBackend(model="gpt-4.1-2025-04-14", connection="openai-eval"),
    unlabelled_examples=unlabelled,       # contexts, or dicts with a "context" key
    human_labelled_sample_size=300,
)
print(job["status"], job["ppi_valid"], job["seed"])     # "awaiting_human_labels", True, ...
for task in job["human_tasks"]:
    send_to_reviewers(task["id"], task["context"], task["judge_label"])
print(job["judge_quality"])
  • The profile must already be bound (call evaluate against it once); otherwise the service answers 422 profile_not_bound. It works for Belief, Set, Interval, Gate, Judge and Route profiles, and the judge must be a hosted backend with a connection.
  • The judge labels every item of the pool (up to 20,000), and the labels are stored on the profile as source: "judge" rows, which never set conformal thresholds.
  • The items for humans are selected uniformly at random, with the seed returned, so prediction-powered estimates stay valid (ppi_valid: true). Over HTTP you can pass "strategy": "uncertainty" to pick the items the judge is least sure of instead, which is not PPI-valid, and your own seed.
  • judge_quality (agreement_with_humans, correlation, effective_label_multiplier, scored_against_n_existing_examples) compares the judge with human-labelled examples already on the profile, and is null when there are none.
  • A small pool is labelled within the request. A large one runs as a job: the response is {"job_id", "status": "queued", ...}, and GET /v1/calibration-profiles/{name}/label-with-judge/{job_id} returns the result when it is done.

human_labelled_sample_size must be at least 2. Label the selected items and upload them with add_examples(..., CalibrationExample(..., source="human")).

You can run the same estimate locally before paying for labels:

from cli_sdk.calibration import estimate_rate_with_judge, judge_quality
 
quality = judge_quality(human_labels, judge_labels_on_same_items)
print(quality.agreement_with_humans, quality.correlation, quality.effective_label_multiplier)
 
estimate = estimate_rate_with_judge(
    human_labels,
    judge_labels_on_same_items,
    judge_labels_on_pool,
    alpha=0.05,
)
print(estimate.estimate, estimate.ci_lower, estimate.ci_upper)

A judge that is no more accurate than the model being evaluated cannot reduce the required number of human labels by more than about half — a mathematical limit of debiasing, not a CLI restriction. The judge-quality diagnostic shows whether you are near that limit. The label-efficient calibration guide and E-values: prediction-powered inference explain the estimator.

Auditing

audit = client.calibration_profiles.audit(
    "support-routing-v3",
    fresh_examples=recent_labelled_sample,
)
print(audit.result)             # "pass" or "fail"
print(audit.passed)             # True
print(audit.realized_coverage)  # e.g. 0.903
print(audit.ci_lower, audit.ci_upper, audit.sample, audit.target)

The service answers each fresh example with the profile’s calibrated backend and current version, then checks realized coverage (or, for a Gate, realized risk) with a 95% Clopper-Pearson interval. An audit fails only when the whole interval sits on the wrong side of the target, that is, when the fresh sample gives real evidence of under-coverage rather than landing a little under by chance. The offline equivalents are cli_sdk.calibration.audit_coverage(covered, target, confidence=0.95) and, for 0/1 losses, audit_risk(losses, target), which reports realized_coverage = 1 - risk so both results have the same shape.

Audits are stored: the profile’s last_audit shows the latest, guarantee cards served from the audited version carry last_audited, and GET /v1/calibration-profiles/{name}/audits lists every one.

  • A profile that has not been calibrated yet answers 424, which the SDK raises as InsufficientCalibrationError.
  • Belief profiles are not audited (422 audit_not_supported): audit a Gate or Set built on the same question.
  • An audit is synchronous up to about 1,500 estimated model calls (and at most 2,000 examples). A larger one fails with 422 audit_too_large: split the sample, or send "async": true over HTTP to run it as a job. Give synchronous audits room with CLIClient(timeout=300).

Run audits on a schedule, or wire them into CI with the command-line tool so a deploy is blocked when an audit fails:

cli calibration audit support-routing-v3 --examples fresh.jsonl --fail-below 0.88

Zero retention

A profile with retention: "zero" discards each example’s raw context once it is scored, keeping a salted hash, the label, the source, the group and the evidence. Answers, appends, audits, outcomes and monitors keep working, because callers send contexts with each call; a backend change cannot be re-scored and makes the profile stale with reason contexts_required. Details, and how to turn it on, are on Observability: zero retention.