Errors and retries

Errors and retries

Every exception the SDK raises for an API, connection or configuration problem subclasses CLIError, importable from cli_sdk. Invalid query or resource arguments raise ConfigurationError at construction time, before anything reaches the network; ConfigurationError is also a ValueError, so existing except ValueError code keeps working.

Exception map

ExceptionRaised whenRetried by default
AuthenticationError401: missing, invalid or revoked API key, or the key’s creator left the organizationNo
ValidationError422: the request failed validation. .field names the offending field when the server reports one.No
InsufficientCalibrationErrorA profile is too small or not ready for the requested guarantee, and you opted into strict mode (see below); also a 424 from any non-evaluate endpoint, for example auditing a profile that was never calibratedNo
RateLimitError429 after retries are exhausted. .retry_after holds the server’s retry-after in seconds, if numeric.Yes
BackendError502: the model backend failed or timed out, or cannot reach the pinned access level. 529: the service or your provider is overloaded.Yes
APIConnectionErrorThe API could not be reached (connection refused, DNS failure, timeout) after the configured retriesYes
ConfigurationErrorClient-side misconfiguration, raised before any request (also a ValueError): a query missing a required field or with an invalid one (Set with fewer than 2 options, Gate with target outside (0,1)(0, 1), Route with guarantee="cost_budget" and no target_cents, …); an invalid calibration_profiles.create method or alpha; an invalid monitor type, missing target or false_alarm_rate; a CalibrationExample with an unknown source; no API key for a non-local base_url; no backend for a query that does not declare its own cascade (Route, or Judge with cascade); an empty queries map or a value that is not a query; a backend dict without "provider"; a hosted backend without model or with an unknown access_hint; VLLMBackend or SGLangBackend without base_url; an unknown CustomBackend.access_level; a response_model that is not an EvaluateResponse subclassNo
CLIErrorAny other HTTP status of 400 or above, as "HTTP <status>: <message>": for example 402 (provider quota), 403 (missing scope), 404 (unknown profile, monitor or job), 409 (profile exists, request in flight), 413, 504No

Not wrapped in CLIError:

ExceptionRaised when
ValueErrorAn invalid RetryConfig; an unsupported LocalMonitor type; a declared response_model answer that is missing from the response; invalid arrays passed to cli_sdk.stats functions
TypeErrorA declared response_model answer has the wrong type
NotImplementedErrorA CustomBackend evidence method a query needs is not implemented
from cli_sdk import (
    AuthenticationError, BackendError, CLIClient, CLIError, ConfigurationError,
    InsufficientCalibrationError, RateLimitError, ValidationError,
)
 
try:
    result = client.evaluate(context=ticket, backend=backend, queries=queries)
except ValidationError as err:
    log.error("bad request field=%s: %s", err.field, err)
except RateLimitError as err:
    schedule_retry(after=err.retry_after or 30)
except BackendError:
    fall_back_to_human_queue()
except InsufficientCalibrationError:
    fall_back_to_human_queue()        # strict mode: no heuristic answers
except CLIError as err:
    log.exception("evaluate failed: %s", err)
    fall_back_to_human_queue()

An unknown profile, monitor or job is 404 on its own routes, which the SDK raises as CLIError (HTTP 404: ...). An evaluate whose query names a profile that was never created is 422 profile_not_found (ValidationError, with field set to queries.<id>.calibration_profile).

Heuristic answers and 424

When a query cannot be answered with a guarantee, the service answers with HTTP 424 Failed Dependency and a body that still contains an answer for every query, with the affected answers’ cards labelled heuristic and a warnings entry saying why:

WhyWhat to do
The profile has no examples, or fewer than the query needs (below ⌈(1−α)/α⌉\lceil (1-\alpha)/\alpha \rceil, or underpowered for the requested bound)Add examples
Calibration is running as a background jobWait for the job, or for profile.status == "serving"
The profile is stale: a strict profile saw a different backend, a monitor with on_alarm="stale" alarmed, or a zero-retention profile cannot re-scoreUse the calibrated backend, or recalibrate
A non-strict profile is recalibrating for a new backendWait for the job

By default, evaluate returns that response instead of raising: the answers are usable, and they say plainly that no formal guarantee backs them. A heuristic answer takes its safe form: a Set returns every option, a Gate escalates, a Belief returns [0,1][0, 1], an Interval every level, a Claim retains nothing, and a Judge or Route goes to the human queue.

result = client.evaluate(context=ticket, backend=backend, queries=queries)
 
if result.heuristic_answers:                       # e.g. ["route"]
    for qid in result.heuristic_answers:
        print(qid, result.answers[qid].guarantee.describe())
        # No guarantee: profile 'support-auto-route-v3' is being calibrated
    print(result.warnings)
 
gate = result.answers["route"]
if gate.approved and not gate.is_heuristic:
    auto_route()
else:
    send_to_human()

The SDK applies the same rule to every response, whatever its status: an answer whose card is missing, or whose type is not one of the eight known guarantee types, is treated as heuristic. A Gate decision other than auto_approve, escalate, or abstain is read as escalate. The SDK never turns an unrecognized answer into an approval.

strict_guarantees

Pass strict_guarantees=True to refuse heuristic answers outright:

client = CLIClient(strict_guarantees=True)

evaluate then raises InsufficientCalibrationError whenever any answer in the response is heuristic — on a 424, and also on a 200 response that contains a heuristic answer. The message lists the query ids. Use strict mode in paths where acting on an unguaranteed answer is never acceptable, and handle the exception by falling back to human review.

Strict mode changes what you receive, not what is guaranteed. A non-heuristic answer is still a marginal or group-conditional guarantee over exchangeable data, never a promise about the one request in front of you.

Error codes

Every error body is {"message", "code", "field"?, "details"?, "request_id"}. Provider error bodies are never echoed: the service classifies them into the codes below and logs the detail against the request id.

Authentication and permissions

CodeStatusMeaning
missing_api_key401No Authorization: Bearer header
invalid_api_key401Unknown key
revoked_api_key401The key was revoked
key_owner_removed401The key’s creator is no longer in its organization
insufficient_scope403The key lacks the scope this route needs; WWW-Authenticate names it
forbidden_role403Your role does not allow this action (dashboard routes, zero-retention changes)

Request shape

CodeStatusMeaning
invalid_json, body_not_object422The body is not a JSON object
unknown_field422A field the route does not accept; field names it
validation_error422Any other invalid value; field names it
unknown_query_type422A query type other than the seven primitives
unknown_provider422A backend.provider the service does not serve
unsupported_option422An option the hosted engine does not implement, for example a Gate loss other than zero_one
invalid_name422A profile name with characters outside letters, digits, ., _, -
payload_too_large413 (422 for too many examples in one call)Over a size limit
unsupported_media_type415OTLP ingest with a content type other than protobuf or JSON
route_not_found, method_not_allowed404, 405No such route or method

Idempotency, rate limits, availability

CodeStatusMeaning
invalid_idempotency_key422Not 1 to 255 printable ASCII characters
idempotency_key_reused422The key was used for a different request
idempotency_in_flight409The original request with this key is still running; retry after Retry-After
rate_limited429The API key’s request rate
concurrency_limited429Too many concurrent writes for the organization or key
service_overloaded529The service is saturated
service_unavailable, accounts_unavailable503A store is unavailable; retry later
gateway_timeout504The hosted proxy waited 300 s
upstream_unavailable502The hosted proxy could not reach the service
internal_error500An unexpected error; quote the request_id

Providers and connections

CodeStatusMeaning
connection_required422No connection for this provider: add one (Provider connections)
connection_not_found422No connection with that name
connection_unverified422A vLLM, SGLang, OpenAI-compatible or Azure connection has not passed Test
connection_mode_mismatch422provider: "vertex" needs a Gemini connection in Vertex mode
egress_denied422The endpoint is not allowed, or base_url does not match the connection’s origin
provider_auth_failed422The provider rejected your credential (field: backend.connection)
provider_model_not_found422The provider does not know the model or deployment (field: backend.model)
provider_bad_request422The provider rejected the request
context_too_long422The context exceeds the model’s window
provider_quota_exhausted402Your provider account is out of quota or billing
provider_rate_limited429Your provider rate-limited your key; its Retry-After is passed through
provider_overloaded529Your provider is overloaded
provider_unavailable, provider_timeout502A transient provider failure
backend_error502The backend could not produce evidence for the query
access_level_unavailable502The pinned access level is beyond what this backend reaches; no model call was made

Profiles, calibration, monitors, jobs

CodeStatusMeaning
profile_not_found404 (422 inside evaluate)No profile with this name; create it first
profile_exists409The name exists with a different configuration; details.differences lists the fields. Use a new name
query_mismatch422The profile is bound to a different query; use one profile per query
profile_not_bound422The route needs a bound profile (outcomes, calibrate, label-with-judge); evaluate against it first
profile_empty422No eligible labelled examples to calibrate with
profile_full, profile_limit422100,000 examples per profile, 1,000 profiles per organization
profile_busy409Another operation holds the profile; retry shortly
contexts_required422A zero-retention profile cannot do this without the contexts it discarded
insufficient_calibration424The profile is not calibrated yet (audits and other non-evaluate routes)
audit_too_large422Send "async": true to run the audit as a job
audit_not_supported422Belief profiles are not audited; audit a Gate or Set on the same question
monitor_not_found, monitor_limit404, 422Unknown monitor; 20 monitors per profile
job_not_found404Unknown job

Telemetry

CodeStatusMeaning
invalid_filter422A malformed search; details.errors lists each term
invalid_cursor, invalid_time_range422A bad cursor, from or to
request_not_found404Unknown request id
otlp_decode_failed422The OTLP body does not decode

The dashboard’s own routes add codes for connections (connection_exists), alert channels, OTLP destinations, organizations and single sign-on (sso_*); they appear in the dashboard, not to API keys.

Retries

429, 502 and 529, connection errors and timeouts are retried automatically; everything else (authentication, validation, insufficient calibration) is returned immediately, because retrying cannot change the outcome. Every POST carries an Idempotency-Key header, one value per logical call reused across its retries, so a retried write (for example add_examples after a 502 that the server had already committed) is applied once.

from cli_sdk import CLIClient, RetryConfig
from cli_sdk.client import NO_RETRY
 
client = CLIClient(retry=RetryConfig(max_attempts=5, base_delay=0.5, max_delay=8.0))
no_retries = CLIClient(retry=NO_RETRY)          # RetryConfig(max_attempts=1)
RetryConfig fieldDefaultMeaning
max_attempts4Total attempts, including the first. Must be at least 1.
base_delay0.5Seconds; the backoff ceiling for the first retry.
max_delay8.0Seconds; cap on a backoff wait.
max_retry_after60.0Seconds; the longest server retry-after the client waits for. A longer one stops retrying and raises (RateLimitError carries .retry_after).
retry_connection_errorsTrueRetry connection errors and timeouts; after the last attempt they raise APIConnectionError.
retry_statusesfrozenset({429, 502, 529})Statuses that trigger a retry.

Before retry kk (the wait after failed attempt kk), the client sleeps:

  • the server’s retry-after value in full, if it is numeric (and at most max_retry_after); otherwise
  • a uniform random time in [0, min⁡(max_delay, base_delay⋅2k−1)]\big[0,\ \min(\text{max\_delay},\ \text{base\_delay} \cdot 2^{k-1})\big] (full-jitter exponential backoff).

When the last attempt still fails, the matching exception is raised (RateLimitError for 429, BackendError for 502 and 529, APIConnectionError for a connection error or timeout).

What to do with the codes the SDK does not retry:

SituationAction
402 provider_quota_exhaustedFix billing or quota on the provider account; retrying will not help
409 idempotency_in_flight, 409 profile_busyWait the Retry-After and retry; add 409 to retry_statuses if your workload hits it often
504 gateway_timeoutThe work may still be finishing. Over HTTP, resending the same Idempotency-Key returns the stored result once it completes (the SDK uses a new key per call). Better, move long work to a job ("async": true for audits, smaller example batches)
422 provider_auth_failed, connection_required, connection_unverifiedFix the connection in the dashboard
422 query_mismatch, 409 profile_existsUse a new profile name for the new query or configuration
424 on a non-evaluate routeCalibrate the profile first (evaluate binds it)

A few consequences worth knowing:

  • Size timeout for L0 backends, which make one model call per sample, and for synchronous audits: CLIClient(timeout=300). A client timeout is retried with the same key; while the first attempt is still running, the service answers the retry with 409 idempotency_in_flight.
  • With a CustomBackend, evidence is computed once, before the first attempt; retries resend the same evidence and do not call your model again.
  • RetryConfig is a frozen dataclass. Share one instance across clients.

Request ids

Every response carries a request id (result.request_id, from the x-request-id header; every JSON body also has "request_id"). Log it next to any decision you act on: it opens the request’s full trace in the dashboard and in GET /v1/requests/{id}, and together with the guarantee card’s calibration_profile, profile_version and last_audited it traces a decision back to the exact calibration that backed it. Quote it when you report a problem.