Build with Jev / Lesson 13 of 24

Build with the TypeScript SDK

Use typed builders, request metadata, cancellation, retries, and safe server boundaries.

After this moduleYou can ship and troubleshoot a native TypeScript Jev client without leaking credentials.

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
01

Customer choice

A customer submits a ticket about a duplicate charge.

02

Request or event

A trusted server builds minimal state and calls systemOne with three typed questions.

03

Backend behavior

The SDK authenticates, validates local question shapes, performs bounded transient retries, parses the response, and exposes request metadata.

04

Customer sees

The ticket is tagged and routed for billing review without exposing the TypeSafe key or moving money.

05

Diagnostic reasoning

Separate local question validation, connection and timeout behavior, HTTP status, returned answer shape, semantic quality, and downstream policy.

Customer seesApplication doesJev returns
A ticket enters billing reviewReads inferred answer fields, verifies account records, and maps the routeNative Noul, Choice, and Score answers plus usage and model
A safe review fallbackStops at the outer deadline and records the operational reasonAn 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.

Applied diagnosis

An eight-second timeout still produces a late ticket

three attempts · timeout configured per attempt · two backoff waits

Reconstruct 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.

Saved locally

Plan a native TypeScript integration

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

Knowledge check

Check your understanding

Explain how TypeScript inference, runtime trust, per-attempt timeout, outer cancellation, retries, error classes, and the server boundary affect one native request.
Module quiz

0/4 answered

01Why use withResponse()?
02What is the default maximum attempt count?
03Why add an outer AbortSignal deadline?
04Why does the SDK reject browser use by default?
Sources and verification notes 3
Native JS SDK 0.6.0 sourcecurrent

10s per-attempt timeout, two retries, 500ms initial backoff, browser rejection and compile-time response casts 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 docsJavaScript SDKSourceSDK source