Build with Jev / Lesson 14 of 24

Build with the Python SDK

Use sync and async clients, Pydantic responses, cancellation boundaries, and a total retry budget.

After this moduleYou can integrate native Jev into synchronous or asynchronous Python services.

Choose a synchronous or asynchronous client

The Python SDK wraps the same native contract as the TypeScript client, but its lifecycle and retry budget differ. Install it with pip install typesafe-sdk. A synchronous worker can use TypeSafeClient; an async service should use AsyncTypeSafeClient so network waits do not block the event loop. Both read TYPESAFE_API_KEY by default.

context manager: a Python lifecycle boundary that closes owned resources when execution leaves its block. Use with for the synchronous client and async with for the asynchronous client. Explicit close() and await aclose() are available when application startup owns a long-lived client. Closing also closes a caller-supplied HTTP client, so decide and document transport ownership instead of sharing one client casually across unrelated services.

from typesafe_sdk import Choice, Noul, Score, TypeSafeClient

with TypeSafeClient(model="jev-1.13.0", timeout=8.0) as client:
    result = client.system_one(
        state={
            "ticket": {"message": "I was charged twice. Please refund one charge."},
            "account": {"matching_charges": "two", "authenticated": "yes"},
        },
        questions={
            "refund_intent": Noul(
                instructions="Does ticket.message ask to return a charge?"
            ),
            "queue": Choice(
                instructions="Which queue should own the first response?",
                criteria={
                    "billing": "Charges, invoices, payments, or refunds",
                    "technical": "Product errors or availability",
                    "other": "No listed queue clearly fits",
                },
            ),
            "frustration": Score(
                instructions="How much frustration is expressed?",
                criteria=["Neutral", "Clear dissatisfaction", "Severe anger"],
            ),
        },
    )
    print(result.nouls["refund_intent"].noul)
    print(result.choices["queue"].choice)
    print(result.request_id)

The asynchronous request changes lifecycle and awaiting, not the semantic contract:

from typesafe_sdk import AsyncTypeSafeClient, Noul

async with AsyncTypeSafeClient(model="jev-1.13.0") as client:
    result = await client.system_one(
        state="Please refund the duplicate charge.",
        questions={
            "refund_intent": Noul(instructions="Is a refund requested?")
        },
    )
Trace this example from input to result
01

Customer choice

A customer submits a billing message to a support service.

02

Request or event

A Python service builds minimal state and calls system_one with Noul, Choice, and Score questions.

03

Backend behavior

HTTPX sends the native request; the SDK handles configured transient retries and validates successful data into strict models.

04

Customer sees

The case receives a reversible route or a review fallback while credentials remain in the service.

05

Diagnostic reasoning

Separate task cancellation, per-operation timeout, retry admission budget, HTTP status, response validation, semantic result, and downstream policy.

Customer seesApplication doesJev returns
A billing case progressesReads typed filtered views and checks account invariantsA validated native response with answers, usage, model, and request ID
A review path after malformed dataRejects the success body before policy executesA response that failed the SDK's Pydantic contract

Construct typed questions and validate responses

Noul, Choice, and Score are Pydantic-backed question objects that catch many local shape problems before transport. Raw dictionaries are also accepted, but they give up some validation and editor assistance. Regardless of input form, provide explicit instructions, at least two Choice options, and at least two Score levels. These conservative rules avoid documented contract edges where OpenAPI and individual clients differ.

The result is an immutable strict Pydantic model. result.answers contains all recognized answer types, while result.nouls, result.choices, and result.scores provide typed filtered views. JSON object keys for a Score legend and probabilities are converted to Python integers, which makes index access natural after parsing.

response validation: checking that a successful HTTP body conforms to the SDK's declared data model before application policy reads it. If a known field has the wrong type or structure, the SDK raises TypeSafeAPIResponseValidationError and includes a field_path. That is a response-contract failure, not low model confidence and not a reason to retry until one payload happens to validate.

Unknown future answer types receive a warning and are omitted from parsed answers; raw_http_response remains available for controlled diagnosis. This behavior limits breakage when the service adds a construct, but code must still verify that every answer required by its policy exists. A new optional answer type can be ignored; a missing queue answer must take the safe fallback.

Version 0.7.0 also supports system_one(..., response_model=MyPydanticModel) when an application wants to validate the full response against its own model. Use this extension for application invariants, not to redefine Jev's semantics. extra_headers and extra_body are advanced seams. extra_body performs a shallow last-write-wins merge and can override state, model, or questions, so a shared helper should not accept arbitrary user-controlled extension data.

Request IDs come from the x-typesafe-request-id header. In the inspected SDK, accessing result.request_id raises if that header is absent. Capture it for support and incident correlation, but make sure logging code cannot turn a missing diagnostic header into a second customer-visible failure after a usable decision has already been produced.

Understand Python's retry admission budget

Python defaults to a 10-second per-operation HTTP timeout and a RetryPolicy with two retries, which means up to three attempts. Retryable defaults include HTTP 408, 429, all 5xx responses, connection errors, and timeouts. Backoff starts at 0.5 seconds, doubles to a five-second cap, and subtracts up to 25 percent jitter. The policy honors retry-after-ms and numeric or date-form Retry-After.

Python differs from the JavaScript SDK in one important way: its retry policy has a default 30-second total admission budget. That budget determines whether another attempt may begin. It does not replace the HTTP timeout for an active attempt or define the application's end-to-end deadline. A retry whose delay would reach or exceed the budget does not start.

from typesafe_sdk import RetryPolicy, TypeSafeClient

policy = RetryPolicy(
    max_retries=1,
    backoff_initial=0.5,
    backoff_max=2.0,
    timeout=6.0,
)

with TypeSafeClient(timeout=3.0, retry=policy) as client:
    result = client.system_one(state=state, questions=questions)

Here the three-second client timeout governs an active request and the six-second retry budget decides whether the second attempt can begin. These values are illustrative rather than production defaults. A per-call retry= replaces the client's policy for that call. Put the complete operation inside the caller's deadline and reserve time to store a fallback result.

Python has no JavaScript AbortSignal. Cancel an asynchronous task and rely on HTTPX timeout and cancellation behavior, or enforce a synchronous deadline at the worker or process boundary. Test cancellation while the request is active and while retry backoff is pending. An API call that stops correctly can still leave a queue message eligible for redelivery, so idempotency belongs in the surrounding workflow.

Applied diagnosis

Retry-After exceeds the remaining worker budget

429 · Retry-After 20s · retry budget 6s · queue deadline 8s

Do not sleep for 20 seconds and let the queue kill the worker. The Python retry policy should decline an attempt that cannot begin within its budget. Record rate limiting, preserve the request ID and ticket, and move to the configured review or delayed-queue path. Reduce concurrency before increasing retries, because more attempts can prolong throttling.

Diagnose Python errors without confusing semantics

Python exposes TypeSafe-prefixed exception classes. TypeSafeError covers general SDK configuration and local problems. TypeSafeAPIError is the non-2xx base. Status-specific subclasses include TypeSafeBadRequestError, TypeSafeAuthenticationError, TypeSafePermissionDeniedError, TypeSafeNotFoundError, TypeSafeUnprocessableEntityError, TypeSafeRateLimitError, and TypeSafeInternalServerError. Connection and timeout failures use TypeSafeAPIConnectionError and TypeSafeAPITimeoutError.

The rate-limit error exposes retry_after_ms. Response-shape defects use TypeSafeAPIResponseValidationError. Correct 400, 401, 403, 404, and 422 causes rather than retrying the same request. Retry transient errors only when the remaining application deadline and consequence justify it. A structurally valid answer that a reviewer labels wrong is a semantic evaluation case and should not enter transport retry logic.

Debug logging can include request and response bodies even though known secret headers are redacted. Keep debug body logging off for customer state unless an approved redaction and retention plan exists. Use model, question version, safe state hash, usage, request ID, attempts, policy, and final action for ordinary diagnosis.

Dig deeperCoordinate async cancellation with queue delivery

Canceling an async task releases local work, but the event broker may deliver the same ticket again. Carry a logical decision ID and ticket version through retries, then compare current state before writing the route. If a reply arrived during the canceled request, discard the stale answer. If redelivery starts a fresh evaluation, the idempotency record should prevent two downstream writes even when both API calls eventually finish.

Saved locally

Design a Python client lifecycle

Your answers stay in this browser. Write enough that another engineer could continue the investigation.

Knowledge check

Check your understanding

Choose the correct Python client, explain strict response parsing, and distinguish per-operation timeout, retry admission, task cancellation, and queue redelivery.
Module quiz

0/4 answered

01What is a useful Python response guarantee?
02How does Python's default retry budget differ from JavaScript's?
03Why use the client as a context manager?
04What provides cancellation for AsyncTypeSafeClient?
Sources and verification notes 3
Native Python SDK 0.7.0 sourcecurrent

Sync/async clients, Pydantic validation, 10s HTTP timeout and 30s retry admission budget at inspected version.

HTTP APIpublic-contract

POST /v1/systemone and authenticated GET /v1/models, request/response fields and errors. Prose and schema differ on omitted instructions, null state and one-level Score; course uses conservative valid requests.

Models, limits and pricingpublic-contract

Native jev-latest and jev-preview documented as jev-1.13.0; 64k total and 32k state plus longest question; 250k tokens/second and 1,200 requests/minute; $0.042/million input tokens. Recheck before rollout.

Further learning

Optional references

These resources provide public documentation and examples for readers who want them.

TypeSafe docsPython SDKSourcePython SDK source