Sign in Get started

Error handling

Every Pictograph SDK exception and API error code, when each fires and what to do, and how the SDK retries 5xx and network failures safely.

View as Markdown
On this page

Every SDK error subclasses PictographError. Catch a subclass, or branch on e.code, the API’s stable error code:

from pictograph.exceptions import ApiError

try:
    client.datasets.get(dataset="road-signs")
except ApiError as e:
    if e.code == "not_found":
        ...                          # create it
    elif e.code == "insufficient_credits":
        show_upgrade(e.upgrade_url)  # a PaymentRequiredError
    else:
        raise

Source: exceptions.py

Hierarchy

PictographError
├── ConfigurationError        - missing API key, invalid base URL
├── PollTimeoutError          - a job didn't finish within its timeout
├── StreamStalledError        - a live stream sent no frame for its reader's idle_timeout
├── NetworkError              - connection / DNS / TLS failure
│   └── RequestTimeoutError   - a request ran past the SDK's timeout
└── ApiError                  - the server answered with an error status
    ├── AuthError             - 401 (bad / missing / revoked key)
    ├── PaymentRequiredError  - 402 (out of credits)
    ├── ForbiddenError        - 403 (role lacks permission)
    ├── NotFoundError         - 404 (resource missing)
    ├── ConflictError         - 409 (name in use, or a change that met another)
    ├── ValidationError       - 400 / 422 (payload rejected)
    ├── RateLimitError        - 429 (the key's rate limit)
    └── ServerError           - 5xx (the API failed; usually brief)

Every name imports from pictograph.exceptions.

The error envelope

Every error the API returns has the same shape:

{
  "error": {
    "code": "not_found",
    "message": "The requested resource was not found.",
    "details": null
  },
  "detail": "The requested resource was not found."
}
  • error.code - the code to branch on (e.code): one per status (unauthorized, forbidden, not_found, conflict, validation_error, payment_required, rate_limited, internal_error) or more specific (insufficient_credits, idempotency_conflict)
  • error.message - what went wrong
  • error.details - context when there is some: field errors, the credit check, retry_after
  • detail - repeats error.message

When each fires

Exception Common cause What to do
ConfigurationError No api_key= and no PICTOGRAPH_API_KEY Set the variable or pass api_key
AuthError (401) A revoked or mistyped key Check the key, or create a new one
ForbiddenError (403) The key’s role or the plan doesn’t allow the call Use a key with a higher role, or upgrade
NotFoundError (404) A misspelled name (names are case-sensitive) Check the name, e.g. with datasets list
ConflictError (409) An image name the directory already holds Use another name; upload_from_directory skips names already there
ValidationError (400, 422) class instead of name, a flat polygon array Fix the request (Annotation format)
PaymentRequiredError (402) Not enough compute credit Buy credits, or show e.upgrade_url to the user
RateLimitError (429) The key’s rate limit The SDK waits and retries when Retry-After is 120 seconds or less
ServerError (5xx) The API failed The SDK retries; one that keeps failing is raised
NetworkError The connection dropped The SDK retries; a change it retries is applied once
PollTimeoutError A job ran past timeout The job keeps running; read it later, e.g. client.training.get(run=...)
StreamStalledError No frame within frames(idle_timeout=...): the camera stalled or the connection dropped Read frames() again to keep waiting, or stop() the stream; e.alive says whether it’s still up
ApiError, code job_failed / job_cancelled A wait_for_* helper’s job ended failed or cancelled Read e.response (the job, with its error message), fix the cause, start a new job

From the CLI

The CLI exits with one code per exception (exit codes). With --json it also prints the error as one line of JSON on stderr (code, message, fix, details).

Retry behavior

The SDK retries what’s likely to pass a moment later:

  • A 5xx or a network failure: up to 3 retries, 1, 2 then 4 seconds apart.
  • A 429 with Retry-After of 120 seconds or less: it waits, then retries.
  • A 409 idempotency_key_in_use (the same request’s first try still running): it waits for that answer, up to 10 minutes.

Every call that changes something carries an Idempotency-Key header, held 24 hours, so a retry (yours or the SDK’s) applies once. The same key with a different body is a 409 idempotency_conflict.

timeout (seconds per request, default 30) and max_retries (default 3) are set on the client:

client = Client(timeout=30.0, max_retries=5)

PaymentRequiredError details

from pictograph.exceptions import PaymentRequiredError

try:
    client.training.create(
        dataset="road-signs",
        export="road-signs-v1",
        pipeline_type="yolox",
        name="run-1",
    )
except PaymentRequiredError as e:
    # Amounts are integer micro-USD (1 USD = 1,000,000 µUSD)
    print(f"Need ${e.credit_cost / 1e6:.2f}, you have ${e.credits_remaining / 1e6:.2f}")
    print(f"Top up at: {e.upgrade_url}")

credit_cost and credits_remaining are micro-USD (e.unit == "micro_usd"). e.upgrade_url opens Settings → Usage in the app, where credits are bought. str(e) is a message for a person.

ValidationError details

The response body lists every offending field:

from pictograph.exceptions import ValidationError

try:
    client.annotations.save(
        dataset="road-signs",
        image="img-001.jpg",
        annotations=[{"class": "person", "type": "bbox"}],
    )
except ValidationError as e:
    print(e)              # human-readable summary
    print(e.field_errors) # list of {"loc": [...], "msg": "...", "type": "..."}

PollTimeoutError and recovery

A call that waits for a job (training.create, a batch auto-annotation, a large import) raises PollTimeoutError when its timeout runs out; the job keeps running.

from pictograph.exceptions import PollTimeoutError

# Start without blocking, keep the id, then wait on your terms.
run = client.training.create(
    dataset="ds",
    export="ds-v1",
    pipeline_type="yolox",
    name="ds-detector",
    wait=False,
)

try:
    run = client.training.wait_for_completion(
        run=run.id,
        timeout=60.0,
    )
except PollTimeoutError:
    # Still running: read it later with the id you kept.
    run = client.training.get(run=run.id)
Copied to clipboard