Build with Jev / Lesson 12 of 24

Call the native HTTP API

Understand every request and response field for System One and model discovery.

After this moduleYou can implement a direct server-side request and separate validation, authentication, throttling, and overload failures.

Send a complete System One request

Gateway hides provider transport behind AI SDK. The native HTTP API exposes the exact contract: POST https://api.typesafe.ai/v1/systemone with Authorization: Bearer TYPESAFE_API_KEY and JSON content. native API: TypeSafe's own HTTP contract, with Jev's Noul, Choice, and Score names differs from Gateway's normalized interface.

const controller = new AbortController();
const deadline = setTimeout(() => controller.abort(), 15_000);
let response: Response;
try {
  response = await fetch("https://api.typesafe.ai/v1/systemone", {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.TYPESAFE_API_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({
      model: "jev-1.13.0",
      state: {
        message: "My card was charged twice. Please refund one charge.",
        account: { refundEligible: true },
      },
      questions: {
        refund_intent: { type: "noul", instructions: "Is a refund requested?", criteria: { true: "Requests reversal", false: "Does not" } },
        queue: { type: "choice", instructions: "Which queue?", criteria: { billing: "Charges", technical: "Failures", other: "Neither" } },
        frustration: { type: "score", instructions: "How frustrated?", criteria: ["Calm", "Frustrated", "Very angry"] },
      },
    }), signal: controller.signal,
  });
} finally {
  clearTimeout(deadline);
}
const requestId = response.headers.get("x-typesafe-request-id");
if (!response.ok) {
  const errorBody = await response.text();
  throw new Error(`TypeSafe ${response.status} request=${requestId}: ${errorBody}`);
}
const result = await response.json();

state is required and may be a string, object, or array. model selects an alias or version. questions maps application-chosen names to typed definitions. Instructions and criteria can be structured JSON, although clear literal text is usually easier to review. Do not send top-level null state. Always provide instructions, at least two Choice options, and at least two Score levels despite permissive schema edges.

The HTTP body has three required top-level fields. state contains the evidence and accepts a string, object, or array of JSON values; the semantic input is text, so other media needs preprocessing. model selects an alias or versioned ID. questions is a nonempty map whose keys are caller-owned identifiers used to match answers. Questions share state but are evaluated independently, and one answer cannot become another question's hidden input in the same request.

Every question contains type, instructions, and primitive-specific criteria. Noul criteria may describe true and false evidence. Choice criteria map each exact label to its meaning; include other or review when the domain needs them. Score criteria are an ordered array whose zero-based positions define the levels. A valid JSON shape can still define a useless judgment, so supply clear instructions and at least two meaningful Choice options or Score levels.

Question-map keys such as refund_intent organize the response for application code; they are not the natural-language question. Keep them stable when dashboards and stored decisions depend on them. Structured instructions and criteria are accepted, but a reviewer still needs to understand the literal judgment. State object keys should preserve relationships: account.refundEligible names a trusted fact separately from the customer's message rather than blending both into prose. An array state remains one evaluated state, not a request batch.

Trace this example from input to result
01

Customer choice

A customer reports a duplicate charge.

02

Request or event

The server posts state, model, and named questions to /v1/systemone.

03

Backend behavior

TypeSafe authenticates, validates, evaluates each question, and returns answers and usage.

04

Customer sees

The support workflow routes or reviews the ticket.

05

Diagnostic reasoning

Use status, response body, request ID, returned model, and policy logs to locate the boundary.

Customer seesApplication doesJev returns
A routed caseSends evidence and applies policyModel, answers, and token usage

Interpret every response field

The top-level model records the model reported for the evaluation. answers is keyed exactly like questions. usage.input_tokens and usage.output_tokens support cost and capacity accounting; Jev currently charges input and lists output as free.

Noul returns type: "noul" and noul, without separate confidence. Choice returns type, selected choice, label probabilities, and confidence. Score returns a probability-weighted score, numeric-keyed legend, per-level probabilities, and confidence. probability-weighted score: the sum of every rubric index multiplied by its returned probability may lie between levels. It is not an exact physical measurement.

Capture x-typesafe-request-id when available. Avoid logging raw state, authorization headers, or full bodies. A state hash helps correlate a replay only if canonicalization, redaction, and access rules are documented.

The following response is synthetic. It demonstrates the documented field shapes and arithmetic; it was not returned by a live Jev request and is not performance evidence.

{
  "model": "jev-1.13.0",
  "answers": {
    "refund_intent": { "type": "noul", "noul": 0.93 },
    "queue": {
      "type": "choice",
      "choice": "billing",
      "probabilities": { "billing": 0.96, "technical": 0.02, "other": 0.02 },
      "confidence": 0.94
    },
    "frustration": {
      "type": "score",
      "score": 1.2,
      "legend": { "0": "Calm", "1": "Frustrated", "2": "Very angry" },
      "probabilities": { "0": 0.1, "1": 0.6, "2": 0.3 },
      "confidence": 0.61
    }
  },
  "usage": { "input_tokens": 312, "output_tokens": 48 }
}

model identifies what the service reports as answering the request; record it even when the request used an alias. Each key under answers matches a request question. The Noul value is the probability of yes and has no separate confidence. Choice returns the selected label, the distribution over every label, and distribution-derived confidence. Score returns its expected rubric position: in the synthetic example, 0×0.1 + 1×0.6 + 2×0.3 = 1.2. legend preserves the meaning of each level. A value between levels is an expectation across the distribution, not a newly invented rubric label.

usage.input_tokens is the billable input count. usage.output_tokens is reported even though current Jev pricing lists output as free. Store both so pricing changes and capacity can be recomputed. Never infer latency, correctness, or confidence from token counts. The response body does not contain the HTTP request ID; read x-typesafe-request-id from headers and attach it to safe incident logs.

List and select models

Authenticated GET /v1/models exposes models available to the account. Current docs list jev-1.13.0, with jev-latest and jev-preview resolving to it at verification. Aliases can move. Store requested and returned identifiers.

Current documented limits are 64,000 tokens across state and all questions, plus 32,000 across state and the longest question. The documented defaults are 250,000 tokens per second and 1,200 requests per minute, subject to account and product changes. Input is text; preprocess images, audio, video, and documents elsewhere.

Model discovery uses authenticated GET /v1/models. At course verification, documentation lists jev-1.13.0; jev-latest and jev-preview both resolve to it. That mapping can change. A controlled production policy pins the version used for threshold evaluation. An alias is useful when automatic upgrades are intentional, but replaying an old request through a moved alias is not reproduction. Preserve requested model, returned model, state and question versions, policy version, and safe state hash together.

Applied diagnosis

An old decision cannot be reproduced

logged request model=jev-latest · current alias points to a newer release

The alias is insufficient replay evidence. Find the historical returned model, question version, state hash, and policy. If the resolved version was not logged, state that limitation rather than claiming a model regression.

Handle the HTTP failure contract

The fetch example uses one outer deadline but does not implement retries. A production retry wrapper should retry only idempotent transient conditions: connection failures, 408, 429, 529, and other selected 5xx responses. It should honor Retry-After, apply jitter, and stop before the caller's deadline. A 400 or 422 requires a payload fix. A 401 or 403 requires credential or permission repair. A 404 requires endpoint or model investigation. Error bodies may be text or structured JSON, so capture them defensively and redact state.

An unauthenticated model-list request was observed returning 403 even though API prose emphasizes 401. Handle both rather than depending on one status. Native SDKs also classify connection failures and timeouts and expose the final request ID; raw fetch must recreate those distinctions.

Treat 400 and 422 as request defects; correct them rather than retry unchanged. Treat 401 and 403 as authentication or permission failures. An unauthenticated model-list call was observed returning 403 even though prose emphasizes 401, so handle both. A 404 indicates the requested resource or path was not found.

HTTP 429 means throttling. Respect Retry-After, add jitter, and remain inside a total deadline. HTTP 529 indicates overload; bounded delayed retry or degraded handling may be appropriate. Other 5xx responses and connection failures can be transient. Parse errors defensively, preserve safe request IDs, and never assume every failure body is JSON.

Saved locally

Document a direct API contract

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

Dig deeperResolve schema and prose conflicts conservatively

The live OpenAPI and SDKs permit some shapes that prose discourages: omitted instructions, one-level Score, or too few Choice options. A technically accepted payload can still define a meaningless judgment. Application validation should enforce the stronger semantic contract before the request leaves the service.

Knowledge check

Check your understanding

Trace every native request field, response field, model lookup, and status class to the code that owns its next action.
Module quiz

0/4 answered

01What does POST /v1/systemone require?
02Why record the response model field?
03What does HTTP 422 usually indicate?
04What should code do after 429?
Sources and verification notes 4
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.

Primitives overviewpublic-contract

Independent named questions and typed answers. Its approximate 32k wording differs from the model page's more specific 64k aggregate and 32k longest-question limits.

TypeSafe legal documentspublic-contract

No training on customer requests/responses, purpose-based retention, enterprise ZDR and US hosting. No fixed ordinary-account retention duration established; MCA section 2.3 includes publication and distillation restrictions.

Further learning

Optional references

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

TypeSafe docsAPI referenceTypeSafe docsModels