Create a typed native client on the server
Lesson 11 exposed the raw native contract. The official @typesafe-ai/sdk wraps that contract with TypeScript inference, retries, and request metadata. Install it with npm install @typesafe-ai/sdk and keep TYPESAFE_API_KEY in a trusted server environment. Native credentials and model names differ from Vercel AI Gateway.
typed builder: an SDK function that constructs a question while preserving its answer keys in TypeScript's inferred result type. The noul, choice, and score builders make question definitions easier to review and let question IDs flow into data.answers. Declaring a Score criteria tuple with as const also preserves its level keys.
import { choice, noul, score, TypeSafeClient } from "@typesafe-ai/sdk";
const client = new TypeSafeClient({
defaultModel: "jev-1.13.0",
timeout: 8_000,
retry: { maxRetries: 2 },
});
const request = client.systemOne(
{
state: {
ticket: { message: "I was charged twice. Please refund one charge." },
account: { matchingCharges: "two", authenticated: "yes" },
},
questions: {
refundIntent: noul("Does ticket.message ask to return a charge?"),
queue: choice("Which queue should own the first response?", {
billing: "Charges, invoices, payments, or refunds",
technical: "Product errors or availability",
other: "No listed queue clearly fits",
}),
frustration: score("How much frustration is expressed?", [
"Neutral or appreciative",
"Clear dissatisfaction",
"Severe anger or repeated demand",
] as const),
},
},
{ signal: AbortSignal.timeout(15_000) },
);
const { data, requestId, response } = await request.withResponse();
console.log(data.answers.queue.choice, requestId, response.status);
The package defaults to https://api.typesafe.ai, the jev-latest model, and a 10-second timeout per attempt. Environment overrides include TYPESAFE_BASE_URL, TYPESAFE_DEFAULT_MODEL, and TYPESAFE_LOG_LEVEL. Pinning jev-1.13.0 in this example is a release choice, not a universal recommendation. A team that intentionally accepts automatic upgrades may use an alias after evaluating that policy.
Trace this example from input to result
Customer choice
A customer submits a ticket about a duplicate charge.
Request or event
A trusted server builds minimal state and calls systemOne with three typed questions.
Backend behavior
The SDK authenticates, validates local question shapes, performs bounded transient retries, parses the response, and exposes request metadata.
Customer sees
The ticket is tagged and routed for billing review without exposing the TypeSafe key or moving money.
Diagnostic reasoning
Separate local question validation, connection and timeout behavior, HTTP status, returned answer shape, semantic quality, and downstream policy.
| Customer sees | Application does | Jev returns |
|---|---|---|
| A ticket enters billing review | Reads inferred answer fields, verifies account records, and maps the route | Native Noul, Choice, and Score answers plus usage and model |
| A safe review fallback | Stops at the outer deadline and records the operational reason | An error or no answer; the SDK does not choose fallback policy |
Use inferred types without trusting the network blindly
client.systemOne(...) returns an APIPromise. Awaiting it yields parsed data. Calling .withResponse() returns { data, response, requestId }, which is useful when application policy needs the answers and operations needs the final HTTP status or request identifier. Calling .asResponse() returns the raw buffered Response; choose that path deliberately rather than consuming the body and expecting it to remain available through parsed data later.
Question names and Choice labels appear in the inferred result. That assistance prevents many local mistakes, such as reading data.answers.routing when the question is named queue, or comparing the returned label with a value that is absent from the criteria. It does not make an external response correct.
runtime validation: checking external data while the program is executing instead of relying only on compile-time declarations. In the inspected JavaScript SDK 0.6.0, successful JSON is parsed leniently and cast to the expected TypeScript type; every response field is not validated at runtime. A safety-sensitive service can add a narrow schema before policy executes. Check that required answer IDs exist, probabilities are finite and inside the expected range, Choice labels belong to the declared set, and model and usage metadata have usable shapes.
Do not convert a response-contract failure into a low-confidence answer. Missing answers.queue, a non-finite probability, or an unknown label is an operational contract incident. Send the ticket to the declared fallback, retain safe evidence, and investigate transport or provider changes. Semantic disagreement is different: the response is structurally valid but the label does not match the reviewed meaning.
Logging requires the same boundary. data.model, safe usage fields, question and policy versions, and requestId support diagnosis. The SDK's default log level is warn; info records request summaries, while debug can record headers and request or response bodies. Known credential headers and cookies are redacted, but ticket bodies are not. Do not enable body logging around customer state unless an explicit safe transform and retention policy cover it.
Bound attempts, backoff, and cancellation
The SDK's timeout applies to each attempt and includes receiving the complete response body. The default maxRetries: 2 means one initial attempt plus as many as two retries. Defaults treat HTTP 408, 429, every 5xx response, connection errors, and timeouts as retryable. Backoff begins at 500 milliseconds, doubles to a five-second cap, and applies subtractive jitter of up to 25 percent.
Server guidance can replace local backoff. retry-after-ms takes precedence over Retry-After, whose value can be seconds or an HTTP date. The JavaScript SDK accepts server-directed delays up to 60 seconds; a larger value falls back to local backoff. Retry attempts carry X-TypeSafe-Retry-Count, which can help correlate an incident.
These controls do not create a total deadline. Three attempts can each approach the per-attempt timeout and include two waits. Pass an outer AbortSignal based on the workflow's remaining budget. Cancellation also stops pending retry sleep and raises APIUserAbortError. A queue, serverless platform, or caller may have its own timeout, so reserve enough time to record the fallback before the process is terminated.
An eight-second timeout still produces a late ticket
three attempts · timeout configured per attempt · two backoff waitsReconstruct the attempt timeline before calling the model slow. The configured eight seconds bounded each attempt rather than the logical operation. Add or shorten the outer deadline, decide whether this reversible route needs two retries, and log physical attempts beside the logical ticket ID. If a server requested a delay longer than the remaining customer budget, take the fallback instead of waiting.
Map SDK errors to fixes and safe runtime boundaries
The error hierarchy preserves where a request failed. TypeSafeError covers configuration or local validation. APIError represents a non-2xx response and exposes status, headers, response body, and an optional request ID. Named subclasses include BadRequestError for 400, AuthenticationError for 401, PermissionDeniedError for 403, NotFoundError for 404, UnprocessableEntityError for 422, RateLimitError for 429, and InternalServerError for all 5xx responses, including 529 overload.
APIConnectionError covers DNS, TLS, connection, and response-body delivery failures. APITimeoutError is its timeout specialization. APIUserAbortError means the caller canceled the operation. Authentication, permission, and validation errors require a key, configuration, or payload fix. Rate limiting, overload, connection failure, and timeout may be retried only within the shared workflow budget. A valid but unwanted semantic answer must never be retried until another label appears.
The SDK rejects browser execution by default because a browser bundle and outgoing request would expose the API key. dangerouslyAllowBrowser: true bypasses the guard but cannot make the credential secret. Call Jev from a server route that authenticates the application user, limits state size, applies rate limits, redacts logs, and checks authorization before any side effect. Node 20 or newer is the package's declared runtime even though the SDK identifies several runtimes in its request metadata.
Dig deeperValidate successful responses at the policy boundary+
Runtime validation should be smaller than a second SDK. Validate only the fields whose corruption could change the action, retain the raw safe diagnostic reference, and fail to review when the contract is violated. Version the validator with the question pack so a deliberate label addition does not look like an incident. This boundary also helps during rolling upgrades, when the server and deployed application can temporarily disagree about a newly introduced answer type.
Plan a native TypeScript integration
Your answers stay in this browser. Write enough that another engineer could continue the investigation.