probabilities |
|||||
|---|---|---|---|---|---|
| State | score |
confidence |
Level 0 | Level 1 | Level 2 |
| The export button is misaligned by a few pixels on the settings page. | 0.0 | 1.0 | 1.0 | 0.0 | 0.0 |
| The PDF export button does nothing when clicked. I can still export to CSV and convert it myself, but that takes ages. | 1.0 | 1.0 | 0.0 | 1.0 | 0.0 |
| Export to PDF fails with a spinner that never finishes. Some of our team say CSV export still works for them, others say it fails too. | 1.12 | 0.81 | 0.0 | 0.88 | 0.12 |
| The export button crashes the settings page in Safari. It works in Chrome, but a few of our customers only use Safari. | 1.3 | 0.54 | 0.0 | 0.7 | 0.3 |
| Nobody on our team can log in since this morning. We get a 500 error on every attempt. | 2.0 | 1.0 | 0.0 | 0.0 | 1.0 |
(request, options?): APIPromise>; ``` Answer named questions about text or structured state. #### Type Parameters ##### Q `Q` *extends* [`Questions`](/sdk/javascript/api/interfaces/Questions) #### Parameters ##### request [`SystemOneRequest`](/sdk/javascript/api/interfaces/SystemOneRequest)\<`Q`> State, questions, and an optional model override. ##### options? [`RequestOptions`](/sdk/javascript/api/interfaces/RequestOptions) = `{}` Per-call timeout, retry, headers, and cancellation settings. #### Returns [`APIPromise`](/sdk/javascript/api/classes/APIPromise)\<[`SystemOneResult`](/sdk/javascript/api/interfaces/SystemOneResult)\<`Q`>> Answers typed by question name and criteria, with model and token usage. #### Throws Questions or score criteria are empty, or score keys are invalid. #### Throws The server returns a non-2xx response after retries. #### Throws The request cannot connect or times out after retries. #### Throws The caller aborts the request. #### Example ```ts theme={null} const { answers } = await client.systemOne({ state: "I was charged twice. Please help.", questions: { billing: noul("Is this about billing?") }, }); console.log(answers.billing.noul); ``` # Class: TypeSafeError Source: https://docs.typesafe.ai/sdk/javascript/api/classes/TypeSafeError Base class for SDK errors. ## Extends * `Error` ## Extended by * [`APIConnectionError`](/sdk/javascript/api/classes/APIConnectionError) * [`APIError`](/sdk/javascript/api/classes/APIError) * [`APIUserAbortError`](/sdk/javascript/api/classes/APIUserAbortError) ## Constructors ### Constructor ```ts theme={null} new TypeSafeError(message, options?): TypeSafeError; ``` #### Parameters ##### message `string` ##### options? `ErrorOptions` #### Returns `TypeSafeError` #### Overrides ```ts theme={null} Error.constructor ``` # Class: UnprocessableEntityError Source: https://docs.typesafe.ai/sdk/javascript/api/classes/UnprocessableEntityError HTTP 422: request validation failed. ## Extends * [`APIError`](/sdk/javascript/api/classes/APIError) ## Constructors ### Constructor ```ts theme={null} new UnprocessableEntityError( status, body, headers, message? ): UnprocessableEntityError; ``` #### Parameters ##### status `number` ##### body `unknown` ##### headers `Headers` ##### message? `string` #### Returns `UnprocessableEntityError` #### Inherited from [`APIError`](/sdk/javascript/api/classes/APIError).[`constructor`](/sdk/javascript/api/classes/APIError#sdk-constructor) ## Properties ### body ```ts theme={null} readonly body: unknown; ``` Parsed JSON, response text, or `undefined` for an empty body. #### Inherited from [`APIError`](/sdk/javascript/api/classes/APIError).[`body`](/sdk/javascript/api/classes/APIError#sdk-body) *** ### headers ```ts theme={null} readonly headers: Headers; ``` HTTP response headers. #### Inherited from [`APIError`](/sdk/javascript/api/classes/APIError).[`headers`](/sdk/javascript/api/classes/APIError#sdk-headers) *** ### requestId ```ts theme={null} readonly requestId: string | undefined; ``` Request ID from `x-typesafe-request-id`, or `undefined` when absent. #### Inherited from [`APIError`](/sdk/javascript/api/classes/APIError).[`requestId`](/sdk/javascript/api/classes/APIError#sdk-requestid) *** ### status ```ts theme={null} readonly status: number; ``` HTTP response status code. #### Inherited from [`APIError`](/sdk/javascript/api/classes/APIError).[`status`](/sdk/javascript/api/classes/APIError#sdk-status) ## Methods ### fromResponse() ```ts theme={null} static fromResponse( status, body, headers ): APIError; ``` Create the error subclass for an HTTP status code. #### Parameters ##### status `number` ##### body `unknown` ##### headers `Headers` #### Returns [`APIError`](/sdk/javascript/api/classes/APIError) #### Inherited from [`APIError`](/sdk/javascript/api/classes/APIError).[`fromResponse`](/sdk/javascript/api/classes/APIError#sdk-fromresponse) # Function: choice() Source: https://docs.typesafe.ai/sdk/javascript/api/functions/choice ```ts theme={null} function choice (instructions, criteria): ChoiceQuestion ; ``` Create a question that selects between named alternatives. ## Type Parameters ### T `T` *extends* [`ChoiceCriteria`](/sdk/javascript/api/type-aliases/ChoiceCriteria) ## Parameters ### instructions [`EntryType`](/sdk/javascript/api/type-aliases/EntryType) The question as text, a JSON object or array, or `null`. ### criteria `T` Labels mapped to descriptions, or `null` for undescribed labels. ## Returns [`ChoiceQuestion`](/sdk/javascript/api/interfaces/ChoiceQuestion)\<`T`> # Function: noul() Source: https://docs.typesafe.ai/sdk/javascript/api/functions/noul ```ts theme={null} function noul(instructions?, criteria?): NoulQuestion; ``` Create a yes/no question with optional descriptions for either outcome. ## Parameters ### instructions? [`EntryType`](/sdk/javascript/api/type-aliases/EntryType) = `null` The question as text, a JSON object or array; defaults to `null`. ### criteria? \| \{ `false?`: [`EntryType`](/sdk/javascript/api/type-aliases/EntryType); `true?`: [`EntryType`](/sdk/javascript/api/type-aliases/EntryType); } \| `null` Optional descriptions of the yes and no outcomes. #### Type Literal \{ `false?`: [`EntryType`](/sdk/javascript/api/type-aliases/EntryType); `true?`: [`EntryType`](/sdk/javascript/api/type-aliases/EntryType); } Optional descriptions of the yes and no outcomes. ##### false? [`EntryType`](/sdk/javascript/api/type-aliases/EntryType) Description of the no outcome. ##### true? [`EntryType`](/sdk/javascript/api/type-aliases/EntryType) Description of the yes outcome. *** `null` ## Returns [`NoulQuestion`](/sdk/javascript/api/interfaces/NoulQuestion) # Function: score() Source: https://docs.typesafe.ai/sdk/javascript/api/functions/score ```ts theme={null} function score (instructions, criteria): ScoreQuestion ; ``` Create a score question using an ordered rubric. ## Type Parameters ### T `T` *extends* [`ScoreCriteria`](/sdk/javascript/api/type-aliases/ScoreCriteria) ## Parameters ### instructions [`EntryType`](/sdk/javascript/api/type-aliases/EntryType) The question as text, a JSON object or array, or `null`. ### criteria `T` A nonempty array or map indexed from zero with no gaps; descriptions may be `null`. ## Returns [`ScoreQuestion`](/sdk/javascript/api/interfaces/ScoreQuestion)\<`T`> # Interface: ChoiceQuestion Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/ChoiceQuestion A question that selects between named alternatives. ## Type Parameters ### T `T` *extends* [`ChoiceCriteria`](/sdk/javascript/api/type-aliases/ChoiceCriteria) = [`ChoiceCriteria`](/sdk/javascript/api/type-aliases/ChoiceCriteria) ## Properties ### criteria ```ts theme={null} criteria: T; ``` Descriptions of the available outcomes. *** ### instructions? ```ts theme={null} optional instructions?: EntryType; ``` The question as text, a JSON object, or an array; optional or `null`. *** ### type ```ts theme={null} type: "choice"; ``` # Interface: ChoiceResponse Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/ChoiceResponse A selected label and its probabilities. ## Type Parameters ### T `T` *extends* [`ChoiceCriteria`](/sdk/javascript/api/type-aliases/ChoiceCriteria) = [`ChoiceCriteria`](/sdk/javascript/api/type-aliases/ChoiceCriteria) ## Properties ### choice ```ts theme={null} readonly choice: keyof T & string; ``` The selected label. *** ### confidence ```ts theme={null} readonly confidence: number; ``` Reported confidence in the selected label. *** ### probabilities ```ts theme={null} readonly probabilities: { readonly [label in string | number | symbol]: number }; ``` Probabilities keyed by label. *** ### type ```ts theme={null} readonly type: "choice"; ``` # Interface: Logger Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/Logger Log methods accepting a message and structured values; compatible with `console`. ## Methods ### debug() ```ts theme={null} debug(message, ...args): void; ``` #### Parameters ##### message `string` ##### args ...`unknown`\[] #### Returns `void` *** ### error() ```ts theme={null} error(message, ...args): void; ``` #### Parameters ##### message `string` ##### args ...`unknown`\[] #### Returns `void` *** ### info() ```ts theme={null} info(message, ...args): void; ``` #### Parameters ##### message `string` ##### args ...`unknown`\[] #### Returns `void` *** ### warn() ```ts theme={null} warn(message, ...args): void; ``` #### Parameters ##### message `string` ##### args ...`unknown`\[] #### Returns `void` # Interface: ModelCard Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/ModelCard Metadata for an available model. ## Properties ### description ```ts theme={null} readonly description: string; ``` *** ### name ```ts theme={null} readonly name: string; ``` *** ### release\_date ```ts theme={null} readonly release_date: string; ``` # Interface: Models Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/Models Access to the Models API resource. ## Methods ### list() ```ts theme={null} list(options?): APIPromise ; ``` List the models available to the account. #### Parameters ##### options? [`RequestOptions`](/sdk/javascript/api/interfaces/RequestOptions) = `{}` #### Returns [`APIPromise`](/sdk/javascript/api/classes/APIPromise)\<[`ModelCard`](/sdk/javascript/api/interfaces/ModelCard)\[]> # Interface: NoulQuestion Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/NoulQuestion A yes/no question with optional descriptions for either outcome. ## Properties ### criteria? ```ts theme={null} optional criteria?: | { false?: EntryType; true?: EntryType; } | null; ``` Optional descriptions of the yes and no outcomes. #### Union Members ##### Type Literal ```ts theme={null} { false?: EntryType; true?: EntryType; } ``` ##### false? ```ts theme={null} optional false?: EntryType; ``` Description of the no outcome. ##### true? ```ts theme={null} optional true?: EntryType; ``` Description of the yes outcome. *** `null` *** ### instructions? ```ts theme={null} optional instructions?: EntryType; ``` The question as text, a JSON object, or an array; optional or `null`. *** ### type ```ts theme={null} type: "noul"; ``` # Interface: NoulResponse Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/NoulResponse A yes/no answer. ## Properties ### noul ```ts theme={null} readonly noul: number; ``` Probability of a yes answer, from zero to one. *** ### type ```ts theme={null} readonly type: "noul"; ``` # Interface: Questions Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/Questions Questions keyed by the names used to identify their answers. ## Indexable ```ts theme={null} [name: string]: Question ``` # Interface: RequestOptions Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/RequestOptions Per-call options that override client settings. ## Properties ### headers? ```ts theme={null} optional headers?: Record ; ``` Additional headers, merged over `defaultHeaders`. *** ### retry? ```ts theme={null} optional retry?: Partial ; ``` Retry overrides for this call; omitted fields inherit client settings. *** ### signal? ```ts theme={null} optional signal?: AbortSignal; ``` Cancellation signal for the request and pending retries. *** ### timeout? ```ts theme={null} optional timeout?: number; ``` Timeout per attempt in milliseconds; there is no total retry budget. # Interface: RetryPolicy Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/RetryPolicy Retry configuration. Partial overrides inherit unset fields from the client or SDK defaults. ## Properties ### apiConnectionError ```ts theme={null} readonly apiConnectionError: boolean; ``` Retry connection failures, including interrupted response bodies (`APIConnectionError`). Default: true. *** ### apiTimeoutError ```ts theme={null} readonly apiTimeoutError: boolean; ``` Whether to retry `APITimeoutError`. Default: true. *** ### backoffInitialMs ```ts theme={null} readonly backoffInitialMs: number; ``` First backoff delay in milliseconds, doubled up to `backoffMaxMs`. Default: 500. *** ### backoffJitter ```ts theme={null} readonly backoffJitter: number; ``` Fraction of each backoff delay randomly subtracted, from 0 to 1. Default: 0.25. *** ### backoffMaxMs ```ts theme={null} readonly backoffMaxMs: number; ``` Maximum backoff delay in milliseconds. Default: 5000. *** ### httpStatuses ```ts theme={null} readonly httpStatuses: ReadonlySet ; ``` HTTP status codes to retry. Default: 408, 429, and 500–599. *** ### maxRetries ```ts theme={null} readonly maxRetries: number; ``` Maximum retries after the initial attempt; `0` disables retries. Default: 2. *** ### maxRetryAfterMs ```ts theme={null} readonly maxRetryAfterMs: number; ``` Maximum server retry delay in milliseconds; longer delays use backoff. Default: 60000. *** ### respectRetryAfter ```ts theme={null} readonly respectRetryAfter: boolean; ``` Honor `Retry-After` and `retry-after-ms` up to `maxRetryAfterMs`. Default: true. # Interface: ScoreQuestion Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/ScoreQuestion A question that assigns a score using an ordered rubric. ## Type Parameters ### T `T` *extends* [`ScoreCriteria`](/sdk/javascript/api/type-aliases/ScoreCriteria) = [`ScoreCriteria`](/sdk/javascript/api/type-aliases/ScoreCriteria) ## Properties ### criteria ```ts theme={null} criteria: T; ``` Descriptions of the available outcomes. *** ### instructions? ```ts theme={null} optional instructions?: EntryType; ``` The question as text, a JSON object, or an array; optional or `null`. *** ### type ```ts theme={null} type: "score"; ``` # Interface: ScoreResponse Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/ScoreResponse An expected score with its rubric and probabilities. ## Type Parameters ### T `T` *extends* [`ScoreCriteria`](/sdk/javascript/api/type-aliases/ScoreCriteria) = [`ScoreCriteria`](/sdk/javascript/api/type-aliases/ScoreCriteria) ## Properties ### confidence ```ts theme={null} readonly confidence: number; ``` Reported confidence in the score. *** ### legend ```ts theme={null} readonly legend: ScoreLegend ; ``` Rubric descriptions keyed by score. *** ### probabilities ```ts theme={null} readonly probabilities: { readonly [score in number]: number }; ``` Probabilities keyed by score. *** ### score ```ts theme={null} readonly score: number; ``` Expected score, which may fall between integer rubric levels. *** ### type ```ts theme={null} readonly type: "score"; ``` # Interface: SystemOneRequest Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/SystemOneRequest State and named questions for `systemOne`. Additional properties on a request variable are forwarded, including `null` values. Score maps are converted to arrays before sending. ## Extended by * [`SystemOneRequestPayload`](/sdk/javascript/api/interfaces/SystemOneRequestPayload) ## Type Parameters ### Q `Q` *extends* [`Questions`](/sdk/javascript/api/interfaces/Questions) = [`Questions`](/sdk/javascript/api/interfaces/Questions) ## Properties ### model? ```ts theme={null} optional model?: string; ``` Model override; omitted values inherit `defaultModel`. *** ### questions ```ts theme={null} questions: Q; ``` Nonempty questions keyed by the names used to identify their answers. *** ### state ```ts theme={null} state: EntryType; ``` Text, a JSON object or array, or `null` to evaluate. # Interface: SystemOneRequestPayload Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/SystemOneRequestPayload Request body for `POST /v1/systemone`, with the model resolved. ## Extends * [`SystemOneRequest`](/sdk/javascript/api/interfaces/SystemOneRequest) ## Properties ### model ```ts theme={null} model: string; ``` Model override; omitted values inherit `defaultModel`. #### Overrides [`SystemOneRequest`](/sdk/javascript/api/interfaces/SystemOneRequest).[`model`](/sdk/javascript/api/interfaces/SystemOneRequest#sdk-model) *** ### questions ```ts theme={null} questions: Questions; ``` Nonempty questions keyed by the names used to identify their answers. #### Inherited from [`SystemOneRequest`](/sdk/javascript/api/interfaces/SystemOneRequest).[`questions`](/sdk/javascript/api/interfaces/SystemOneRequest#sdk-questions) *** ### state ```ts theme={null} state: EntryType; ``` Text, a JSON object or array, or `null` to evaluate. #### Inherited from [`SystemOneRequest`](/sdk/javascript/api/interfaces/SystemOneRequest).[`state`](/sdk/javascript/api/interfaces/SystemOneRequest#sdk-state) # Interface: SystemOneResultSource: https://docs.typesafe.ai/sdk/javascript/api/interfaces/SystemOneResult Answers keyed by question name, with model and usage metadata. ## Type Parameters ### Q `Q` *extends* [`Questions`](/sdk/javascript/api/interfaces/Questions) ## Properties ### answers ```ts theme={null} readonly answers: { readonly [K in string | number | symbol]: ResultFor}; ``` Answers with types inferred from the supplied questions. *** ### model ```ts theme={null} readonly model: string; ``` The model used to answer the request. *** ### usage ```ts theme={null} readonly usage: Usage; ``` Token usage for the request. # Interface: TypeSafeClientConfig Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/TypeSafeClientConfig Client options. Explicit values take precedence over environment variables, then SDK defaults. ## Properties ### apiKey? ```ts theme={null} optional apiKey?: string; ``` Required API key; falls back to `TYPESAFE_API_KEY`. *** ### baseURL? ```ts theme={null} optional baseURL?: string; ``` API root; falls back to `TYPESAFE_BASE_URL`, then `https://api.typesafe.ai`. *** ### dangerouslyAllowBrowser? ```ts theme={null} optional dangerouslyAllowBrowser?: boolean; ``` Allow browser use, exposing the API key to page users. Default: false. *** ### defaultHeaders? ```ts theme={null} optional defaultHeaders?: Record; ``` Additional request headers; per-call headers take precedence. *** ### defaultModel? ```ts theme={null} optional defaultModel?: string; ``` Default model; falls back to `TYPESAFE_DEFAULT_MODEL`, then `jev-latest`. *** ### fetch? ```ts theme={null} optional fetch?: Fetch; ``` Custom HTTP fetch implementation for transport configuration or tests. Default: global `fetch`. *** ### logger? ```ts theme={null} optional logger?: Logger; ``` Logger filtered to `logLevel` and above. Default: prefixed `console`. *** ### logLevel? ```ts theme={null} optional logLevel?: LogLevel; ``` Log level; falls back to `TYPESAFE_LOG_LEVEL`, then `warn`. `info` logs request summaries; `debug` adds headers and bodies. Known credential headers are redacted; bodies are not. *** ### retry? ```ts theme={null} optional retry?: Partial ; ``` Retry overrides; omitted fields use the defaults in `RetryPolicy`. *** ### timeout? ```ts theme={null} optional timeout?: number; ``` Timeout per attempt in milliseconds, without a total retry budget. Default: 10000. # Interface: Usage Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/Usage Token usage for a request. ## Properties ### input\_tokens ```ts theme={null} readonly input_tokens: number; ``` Number of input tokens used. *** ### output\_tokens ```ts theme={null} readonly output_tokens: number; ``` Number of output tokens used. # Interface: WithResponse Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/WithResponse Parsed data with its HTTP response and request ID. ## Type Parameters ### T `T` ## Properties ### data ```ts theme={null} data: T; ``` The parsed response body. *** ### requestId ```ts theme={null} requestId: string | undefined; ``` Request ID from `x-typesafe-request-id`, or `undefined` when absent. *** ### response ```ts theme={null} response: Response; ``` The HTTP response, with its body consumed by parsing. # Type Alias: ChoiceCriteria Source: https://docs.typesafe.ai/sdk/javascript/api/type-aliases/ChoiceCriteria ```ts theme={null} type ChoiceCriteria = object; ``` Labels mapped to descriptions, or `null` for undescribed labels. ## Index Signature ```ts theme={null} [label: string]: EntryType ``` # Type Alias: Description Source: https://docs.typesafe.ai/sdk/javascript/api/type-aliases/Description ```ts theme={null} type Description = EntryType; ``` A criterion description; `null` leaves the label undescribed. # Type Alias: EntryType Source: https://docs.typesafe.ai/sdk/javascript/api/type-aliases/EntryType ```ts theme={null} type EntryType = | string | { [key: string]: JsonValue; } | JsonValue[] | null; ``` Text, a JSON object or array, or `null` for state, instructions, and criteria. # Type Alias: EnvVar Source: https://docs.typesafe.ai/sdk/javascript/api/type-aliases/EnvVar ```ts theme={null} type EnvVar = typeof ENV[keyof typeof ENV]; ``` # Type Alias: Fetch Source: https://docs.typesafe.ai/sdk/javascript/api/type-aliases/Fetch ```ts theme={null} type Fetch = (input, init?) => Promise ; ``` HTTP fetch implementation compatible with the global `fetch`. ## Parameters ### input `string` ### init? `RequestInit` ## Returns `Promise`\<`Response`> # Type Alias: JsonValue Source: https://docs.typesafe.ai/sdk/javascript/api/type-aliases/JsonValue ```ts theme={null} type JsonValue = | string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue; }; ``` A JSON-compatible value. # Type Alias: LogLevel Source: https://docs.typesafe.ai/sdk/javascript/api/type-aliases/LogLevel ```ts theme={null} type LogLevel = "debug" | "info" | "warn" | "error" | "off"; ``` Log verbosity; `off` disables logging. # Type Alias: Question Source: https://docs.typesafe.ai/sdk/javascript/api/type-aliases/Question ```ts theme={null} type Question = | NoulQuestion | ScoreQuestion | ChoiceQuestion; ``` A question identified by its `type` field. # Type Alias: ResultFor Source: https://docs.typesafe.ai/sdk/javascript/api/type-aliases/ResultFor ```ts theme={null} type ResultFor = T extends NoulQuestion ? NoulResponse : T extends ScoreQuestion ? ScoreResponse : T extends ChoiceQuestion? ChoiceResponse : never; ``` The answer type for a question, preserving its criteria keys. ## Type Parameters ### T `T` *extends* [`Question`](/sdk/javascript/api/type-aliases/Question) # Type Alias: ScoreCriteria Source: https://docs.typesafe.ai/sdk/javascript/api/type-aliases/ScoreCriteria ```ts theme={null} type ScoreCriteria = ScoreList | ScoreMap; ``` An ordered rubric expressed as an array or score map. # Type Alias: ScoreLegend Source: https://docs.typesafe.ai/sdk/javascript/api/type-aliases/ScoreLegend ```ts theme={null} type ScoreLegend = { readonly [score in ScoreOf ]: T[score] }; ``` Rubric descriptions keyed by score. ## Type Parameters ### T `T` *extends* [`ScoreCriteria`](/sdk/javascript/api/type-aliases/ScoreCriteria) # Type Alias: ScoreList Source: https://docs.typesafe.ai/sdk/javascript/api/type-aliases/ScoreList ```ts theme={null} type ScoreList = readonly [EntryType, ...EntryType[]]; ``` A nonempty array indexed by score from zero; `null` leaves a score undescribed. # Type Alias: ScoreMap Source: https://docs.typesafe.ai/sdk/javascript/api/type-aliases/ScoreMap ```ts theme={null} type ScoreMap = object; ``` Score descriptions keyed from zero with no gaps; `null` leaves a score undescribed. ## Index Signature ```ts theme={null} [score: number]: EntryType ``` # Type Alias: ScoreOf Source: https://docs.typesafe.ai/sdk/javascript/api/type-aliases/ScoreOf ```ts theme={null} type ScoreOf = T extends readonly unknown[] ? number extends T["length"] ? number : Extract : Extract ; ``` Score keys inferred from the rubric; tuple keys are numeric strings, map keys are numbers. ## Type Parameters ### T `T` *extends* [`ScoreCriteria`](/sdk/javascript/api/type-aliases/ScoreCriteria) # Variable: ENV Source: https://docs.typesafe.ai/sdk/javascript/api/variables/ENV ```ts theme={null} const ENV: object; ``` Environment variable names for client configuration. Explicit options take precedence. ## Type Declaration ### apiKey ```ts theme={null} readonly apiKey: "TYPESAFE_API_KEY" = "TYPESAFE_API_KEY"; ``` Required API key; used when `apiKey` is omitted. ### baseURL ```ts theme={null} readonly baseURL: "TYPESAFE_BASE_URL" = "TYPESAFE_BASE_URL"; ``` API root; defaults to `https://api.typesafe.ai`. ### defaultModel ```ts theme={null} readonly defaultModel: "TYPESAFE_DEFAULT_MODEL" = "TYPESAFE_DEFAULT_MODEL"; ``` Default model name; defaults to `jev-latest`. ### logLevel ```ts theme={null} readonly logLevel: "TYPESAFE_LOG_LEVEL" = "TYPESAFE_LOG_LEVEL"; ``` Log level; defaults to `warn`. # Variable: LOG_LEVELS Source: https://docs.typesafe.ai/sdk/javascript/api/variables/LOG_LEVELS ```ts theme={null} const LOG_LEVELS: readonly LogLevel[]; ``` Supported log levels, from most to least verbose. # Variable: VERSION Source: https://docs.typesafe.ai/sdk/javascript/api/variables/VERSION ```ts theme={null} const VERSION: "0.5.7" = "0.5.7"; ``` # Changelog Source: https://docs.typesafe.ai/sdk/javascript/changelog ## v0.5.7 (2026-09-11) This is the initial public release of TypeSafe JavaScript and TypeScript SDK. Learn more in the [documentation](https://docs.typesafe.ai/sdk/javascript). # TypeSafe Python SDK Source: https://docs.typesafe.ai/sdk/python Install the TypeSafe Python SDK and get started with asynchronous or synchronous API calls. Asynchronous and synchronous Python clients for the [TypeSafe](https://typesafe.ai) API. Learn how to use TypeSafe [here](https://docs.typesafe.ai/). ## Quickstart 1. Install the SDK: 2. Set `TYPESAFE_API_KEY` in your environment (create it [here](https://console.typesafe.ai/)) 3. Call the System One API: ```sh theme={null} uv add typesafe-sdk ``` ```sh theme={null} pip install typesafe-sdk ``` ## Usage Learn more in the [Usage guide](/sdk/python/usage). # API reference Source: https://docs.typesafe.ai/sdk/python/api Python clients for the TypeSafe AI API * Sync client: [Client](/sdk/python/api/clients/sync/client) · [Models](/sdk/python/api/clients/sync/models) * Async client: [Client](/sdk/python/api/clients/async/client) · [Models](/sdk/python/api/clients/async/models) * Types: [Common](/sdk/python/api/types/common) · [Questions](/sdk/python/api/types/questions) · [Responses](/sdk/python/api/types/responses) * [Retries](/sdk/python/api/retries) * [Exceptions](/sdk/python/api/exceptions) * [Constants](/sdk/python/api/constants) # Asynchronous client Source: https://docs.typesafe.ai/sdk/python/api/clients/async/client Use AsyncTypeSafeClient to ask questions, list models, and configure asynchronous TypeSafe API requests. ## typesafe\_sdk.AsyncTypeSafeClient Create an asynchronous HTTP client for [TypeSafe AI API](https://typesafe.ai). Explicit options take precedence over environment variables; empty or whitespace-only environment values are ignored. With [AsyncTypeSafeClient](/sdk/python/api/clients/async/client): ```python theme={null} from typesafe_sdk import AsyncTypeSafeClient, Choice, Noul, Score async def main() -> None: async with AsyncTypeSafeClient() as client: response = await client.system_one( state={"document": "I was charged twice. Please fix this ASAP."}, questions={ "billing": Noul(instructions="Is this ticket about billing?"), "tone": Choice( instructions="What is the customer's tone?", criteria={"calm": None, "frustrated": None, "angry": None}, ), "urgency": Score( instructions="How urgent is this ticket?", criteria=["can wait", "this week", "today"], ), }, ) print(response.nouls["billing"].noul) print(response.choices["tone"].choice) print(response.scores["urgency"].score) ``` With [TypeSafeClient](/sdk/python/api/clients/sync/client): ```python theme={null} from typesafe_sdk import Choice, Noul, Score, TypeSafeClient with TypeSafeClient() as client: response = client.system_one( state={"document": "I was charged twice. Please fix this ASAP."}, questions={ "billing": Noul(instructions="Is this ticket about billing?"), "tone": Choice( instructions="What is the customer's tone?", criteria={"calm": None, "frustrated": None, "angry": None}, ), "urgency": Score( instructions="How urgent is this ticket?", criteria=["can wait", "this week", "today"], ), }, ) print(response.nouls["billing"].noul) print(response.choices["tone"].choice) print(response.scores["urgency"].score) ``` **Logging setup** The SDK logs to the `typesafe_sdk` logger; configure it through standard logging, or set `TYPESAFE_LOG_LEVEL` (`debug`, `info`, ...) for a quick default. Secret headers are redacted from log output; request and response bodies are not. Parameters: * **`api_key`** (str | None, default: `None` ) – Required API key; may be set via the `TYPESAFE_API_KEY` environment variable. * **`model`** (str | None, default: `None` ) – Model name; may be set via the `TYPESAFE_DEFAULT_MODEL` environment variable. * **`retry`** (RetryPolicy | None, default: `None` ) – A `RetryPolicy` controlling retry behavior; see `RetryPolicy` for the available options and their defaults. Pass `RetryPolicy(max_retries=0)` to disable retries. * **`timeout`** (float | httpx2.Timeout | None, default: `None` ) – Timeout for HTTP operations. Inherits `http_client.timeout` when supplied, otherwise the SDK default. * **`headers`** (Mapping\[str, str] | None, default: `None` ) – Additional request headers to set. * **`transport`** (`httpx2.AsyncBaseTransport | None`, default: `None` ) – Optional custom HTTP transport, closed when this SDK client closes. * **`http_client`** (httpx2.AsyncClient | None, default: `None` ) – Optional `httpx2.AsyncClient`; mutually exclusive with `transport`. Closed when this SDK client closes. * **`base_url`** (str | None, default: `None` ) – API root; may be set via the `TYPESAFE_BASE_URL` environment variable. Raises: *TypeSafeError– The API key is missing or the timeout is invalid. *ValueError– Both `transport` and `http_client` are supplied. Examples: ```python theme={null} import asyncio from typesafe_sdk import AsyncTypeSafeClient, Choice, Noul async def main() -> None: async with AsyncTypeSafeClient() as client: result = await client.system_one( state="I was charged twice. Please help.", questions={ "billing": Noul(instructions="Is this about billing?"), "tone": Choice( instructions="What is the tone?", criteria={"calm": None, "angry": None}, ), }, ) assert 0 <= result.nouls["billing"].noul <= 1 assert result.choices["tone"].choice in {"calm", "angry"} asyncio.run(main()) ``` ### models `cached` `property` An accessor for the Models API resource. Examples: ```python theme={null} async def main() -> None: async with AsyncTypeSafeClient() as client: models = await client.models.list() ``` ### system\_one `async` Answer named questions about text or structured state. See [System One](https://docs.typesafe.ai/concepts/system-one) for details. Parameters: * **`state`** (JSONContent) – Text, a JSON object, or an array to evaluate. See [state](https://docs.typesafe.ai/concepts/state) for details. * **`questions`** (Mapping\[str, Question]) – Nonempty mapping of names to question objects or raw dictionaries. * **`model`** (str | None, default: `None` ) – Model override; `None` inherits the client default. * **`retry`** (RetryPolicy | None, default: `None` ) – An optional retry policy to override the client-level value for this call only. * **`timeout`** (float | httpx2.Timeout | None, default: `None` ) – An optional timeout for http operations to override the client-level value for this call only, in seconds. * **`extra_headers`** (Mapping\[str, str] | None, default: `None` ) – Additional request headers to set. * **`extra_body`** (Mapping\[str, JSONValue | None] | None, default: `None` ) – Additional top-level request-body fields, shallow-merged over the body after `state`, `model`, and `questions` are set. Merging is last-write-wins: a key that collides with `state`, `model`, or `questions` overrides it, and object values are replaced rather than deep-merged. Returns: *SystemOneResponse– Answers keyed by question name, with model and token usage details. Raises: *TypeSafeError– Questions are empty or a score question's criteria list is empty. *TypeSafeAPIError– The server returns an unsuccessful HTTP response after any retries. *TypeSafeAPIConnectionError– The request cannot connect or times out after any retries. Examples: Create questions with named arguments: ```python theme={null} async def main() -> None: async with AsyncTypeSafeClient() as client: result = await client.system_one( state="I was charged twice. Please help.", questions={ "billing": Noul(instructions="Is this about billing?"), "tone": Choice( instructions="What is the tone?", criteria={"calm": None, "angry": None}, ), }, ) assert 0 <= result.nouls["billing"].noul <= 1 assert result.choices["tone"].choice in {"calm", "angry"} ``` Pass questions as dictionaries: ```python theme={null} async def main() -> None: async with AsyncTypeSafeClient() as client: result = await client.system_one( state={"message": "I was charged twice. Please help."}, questions={ "billing": {"type": "noul", "instructions": "Is this about billing?"}, "tone": { "type": "choice", "instructions": "What is the tone?", "criteria": {"calm": None, "angry": None}, }, }, ) assert 0 <= result.nouls["billing"].noul <= 1 assert result.choices["tone"].choice in {"calm", "angry"} ``` ### aclose `async` ```python theme={null} aclose() -> None ``` Release network resources and close the underlying HTTP client, including a supplied one. # Models resource Source: https://docs.typesafe.ai/sdk/python/api/clients/async/models List the models available to your account through the asynchronous client's Models resource. Reached through [`AsyncTypeSafeClient.models`](/sdk/python/api/clients/async/client). ## typesafe\_sdk.AsyncModels Access to the models available to the account, reached through `AsyncTypeSafeClient.models`. ### list `async` List the models available to the account. Parameters: * **`retry`** (RetryPolicy | None, default: `None` ) – An optional retry policy to override the client-level value for this call only. * **`timeout`** (float | httpx2.Timeout | None, default: `None` ) – Per-operation timeout override; `None` inherits the client setting. * **`extra_headers`** (Mapping\[str, str] | None, default: `None` ) – Overrides for additional request headers; authentication, SDK identification, and `Accept` remain protected. Returns: *ListModelsResponse– A `ListModelsResponse` whose `models` holds each model's name, description, *ListModelsResponse– and release date. Raises: *TypeSafeAPIError– The server returns an unsuccessful HTTP response after any retries. *TypeSafeAPIConnectionError– The request cannot connect or times out after any retries. Examples: ```python theme={null} from typesafe_sdk import AsyncTypeSafeClient async def main() -> None: async with AsyncTypeSafeClient() as client: models = await client.models.list() ``` # Synchronous client Source: https://docs.typesafe.ai/sdk/python/api/clients/sync/client Use TypeSafeClient to ask questions, list models, and configure synchronous TypeSafe API requests. ## typesafe\_sdk.TypeSafeClient Create an HTTP client for [TypeSafe AI API](https://typesafe.ai). Explicit options take precedence over environment variables; empty or whitespace-only environment values are ignored.**Logging setup** The SDK logs to the `typesafe_sdk` logger; configure it through standard logging, or set `TYPESAFE_LOG_LEVEL` (`debug`, `info`, ...) for a quick default. Secret headers are redacted from log output; request and response bodies are not. Parameters: * **`api_key`** (str | None, default: `None` ) – Required API key; may be set via the `TYPESAFE_API_KEY` environment variable. * **`model`** (str | None, default: `None` ) – Model name; may be set via the `TYPESAFE_DEFAULT_MODEL` environment variable. * **`retry`** (RetryPolicy | None, default: `None` ) – A `RetryPolicy` controlling retry behavior; see `RetryPolicy` for the available options and their defaults. Pass `RetryPolicy(max_retries=0)` to disable retries. * **`timeout`** (float | httpx2.Timeout | None, default: `None` ) – Timeout for HTTP operations. Inherits `http_client.timeout` when supplied, otherwise the SDK default. * **`headers`** (Mapping\[str, str] | None, default: `None` ) – Additional request headers to set. * **`transport`** (`httpx2.BaseTransport | None`, default: `None` ) – Optional custom HTTP transport, closed when this SDK client closes. * **`http_client`** (httpx2.Client | None, default: `None` ) – Optional `httpx2.Client`; mutually exclusive with `transport`. Closed when this SDK client closes. * **`base_url`** (str | None, default: `None` ) – API root; may be set via the `TYPESAFE_BASE_URL` environment variable. Raises: *TypeSafeError– The API key is missing or the timeout is invalid. *ValueError– Both `transport` and `http_client` are supplied. Examples: ```python theme={null} from typesafe_sdk import Choice, Noul, TypeSafeClient with TypeSafeClient() as client: result = client.system_one( state="I was charged twice. Please help.", questions={ "billing": Noul(instructions="Is this about billing?"), "tone": Choice( instructions="What is the tone?", criteria={"calm": None, "angry": None}, ), }, ) assert 0 <= result.nouls["billing"].noul <= 1 assert result.choices["tone"].choice in {"calm", "angry"} ``` ### models `cached` `property` An accessor for the Models API resource. Examples: ```python theme={null} with TypeSafeClient() as client: models = client.models.list() ``` ### system\_one Answer named questions about text or structured state. See [System One](https://docs.typesafe.ai/concepts/system-one) for details. Parameters: * **`state`** (JSONContent) – Text, a JSON object, or an array to evaluate. See [state](https://docs.typesafe.ai/concepts/state) for details. * **`questions`** (Mapping\[str, Question]) – Nonempty mapping of names to question objects or raw dictionaries. * **`model`** (str | None, default: `None` ) – Model override; `None` inherits the client default. * **`retry`** (RetryPolicy | None, default: `None` ) – An optional retry policy to override the client-level value for this call only. * **`timeout`** (float | httpx2.Timeout | None, default: `None` ) – An optional timeout for http operations to override the client-level value for this call only, in seconds. * **`extra_headers`** (Mapping\[str, str] | None, default: `None` ) – Additional request headers to set. * **`extra_body`** (Mapping\[str, JSONValue | None] | None, default: `None` ) – Additional top-level request-body fields, shallow-merged over the body after `state`, `model`, and `questions` are set. Merging is last-write-wins: a key that collides with `state`, `model`, or `questions` overrides it, and object values are replaced rather than deep-merged. Returns: *SystemOneResponse– Answers keyed by question name, with model and token usage details. Raises: *TypeSafeError– Questions are empty or a score question's criteria list is empty. *TypeSafeAPIError– The server returns an unsuccessful HTTP response after any retries. *TypeSafeAPIConnectionError– The request cannot connect or times out after any retries. Examples: Create questions with named arguments: ```python theme={null} with TypeSafeClient() as client: result = client.system_one( state="I was charged twice. Please help.", questions={ "billing": Noul(instructions="Is this about billing?"), "tone": Choice( instructions="What is the tone?", criteria={"calm": None, "angry": None}, ), }, ) assert 0 <= result.nouls["billing"].noul <= 1 assert result.choices["tone"].choice in {"calm", "angry"} ``` Pass questions as dictionaries: ```python theme={null} with TypeSafeClient() as client: result = client.system_one( state={"message": "I was charged twice. Please help."}, questions={ "billing": {"type": "noul", "instructions": "Is this about billing?"}, "tone": { "type": "choice", "instructions": "What is the tone?", "criteria": {"calm": None, "angry": None}, }, }, ) assert 0 <= result.nouls["billing"].noul <= 1 assert result.choices["tone"].choice in {"calm", "angry"} ``` ### close ```python theme={null} close() -> None ``` Release network resources and close the underlying HTTP client, including a supplied one. # Models resource Source: https://docs.typesafe.ai/sdk/python/api/clients/sync/models List the models available to your account through the synchronous client's Models resource. Reached through [`TypeSafeClient.models`](/sdk/python/api/clients/sync/client). ## typesafe\_sdk.Models Access to the models available to the account, reached through `TypeSafeClient.models`. ### list List the models available to the account. Parameters: * **`retry`** (RetryPolicy | None, default: `None` ) – An optional retry policy to override the client-level value for this call only. * **`timeout`** (float | httpx2.Timeout | None, default: `None` ) – Per-operation timeout override; `None` inherits the client setting. * **`extra_headers`** (Mapping\[str, str] | None, default: `None` ) – Overrides for additional request headers; authentication, SDK identification, and `Accept` remain protected. Returns: *ListModelsResponse– A `ListModelsResponse` whose `models` holds each model's name, description, *ListModelsResponse– and release date. Raises: *TypeSafeAPIError– The server returns an unsuccessful HTTP response after any retries. *TypeSafeAPIConnectionError– The request cannot connect or times out after any retries. Examples: ```python theme={null} from typesafe_sdk import TypeSafeClient with TypeSafeClient() as client: models = client.models.list() ``` # Constants Source: https://docs.typesafe.ai/sdk/python/api/constants Default settings and environment variable names for the TypeSafe Python SDK. ## typesafe\_sdk.constants Public environment-variable names and client defaults. ### API\_KEY\_ENV `module-attribute` ```python theme={null} API_KEY_ENV = 'TYPESAFE_API_KEY' ``` Environment variable for the API key. ### BASE\_URL\_ENV `module-attribute` ```python theme={null} BASE_URL_ENV = 'TYPESAFE_BASE_URL' ``` Environment variable for the API base URL. ### DEFAULT\_MODEL\_ENV `module-attribute` ```python theme={null} DEFAULT_MODEL_ENV = 'TYPESAFE_DEFAULT_MODEL' ``` Environment variable for the default model. ### LOG\_LEVEL\_ENV `module-attribute` ```python theme={null} LOG_LEVEL_ENV = 'TYPESAFE_LOG_LEVEL' ``` Environment variable for the logging level. ### DEFAULT\_BASE\_URL `module-attribute` ```python theme={null} DEFAULT_BASE_URL = 'https://api.typesafe.ai' ``` Default API base URL. ### DEFAULT\_MODEL `module-attribute` ```python theme={null} DEFAULT_MODEL = 'jev-latest' ``` Default model name. ### DEFAULT\_TIMEOUT `module-attribute` ```python theme={null} DEFAULT_TIMEOUT = 10.0 ``` Default timeout in seconds for each HTTP operation. # Exceptions Source: https://docs.typesafe.ai/sdk/python/api/exceptions Handle TypeSafe API errors, rate limits, connection failures, and timeouts. ## Base exception ## typesafe\_sdk.TypeSafeError Bases:ExceptionBase exception for SDK failures. ## HTTP errors ## typesafe\_sdk.TypeSafeAPIError Bases:TypeSafeErrorAn unsuccessful HTTP response with its body and request metadata. ### status `instance-attribute` ```python theme={null} status = status ``` HTTP response status code. ### body `instance-attribute` ```python theme={null} body = body ``` The server's JSON error body, plain response text, or `None` for an empty body. ### headers `instance-attribute` ```python theme={null} headers = headers ``` HTTP response headers. ### endpoint `instance-attribute` ```python theme={null} endpoint = endpoint ``` The request method and URL, without credentials, query parameters, or fragment, when available. ### request\_id `property` The `x-typesafe-request-id` response header, or `None` if absent. ## typesafe\_sdk.TypeSafeBadRequestError Bases:TypeSafeAPIErrorThe request was invalid (400). ## typesafe\_sdk.TypeSafeAuthenticationError Bases:TypeSafeAPIErrorAuthentication failed (401). ## typesafe\_sdk.TypeSafePermissionDeniedError Bases:TypeSafeAPIErrorAccess was denied (403). ## typesafe\_sdk.TypeSafeNotFoundError Bases:TypeSafeAPIErrorThe resource was not found (404). ## typesafe\_sdk.TypeSafeUnprocessableEntityError Bases:TypeSafeAPIErrorThe request failed server validation (422). ## typesafe\_sdk.TypeSafeRateLimitError Bases:TypeSafeAPIErrorThe rate limit was exceeded (429). ### retry\_after\_ms `instance-attribute` ```python theme={null} retry_after_ms = parse_retry_after(headers) ``` The server's requested wait in milliseconds, or `None` if unavailable. ## typesafe\_sdk.TypeSafeInternalServerError Bases:TypeSafeAPIErrorThe server failed to process the request (5xx). ## Connection errors ## typesafe\_sdk.TypeSafeAPIConnectionError Bases:TypeSafeError,ConnectionErrorA request failed without an HTTP response. ## typesafe\_sdk.TypeSafeAPITimeoutError Bases:TypeSafeAPIConnectionError,TimeoutErrorA request exceeded its configured timeout. ### timeout `instance-attribute` ```python theme={null} timeout = timeout ``` The timeout setting used for the request, in seconds or as an `httpx2.Timeout`. ## Response validation ## typesafe\_sdk.TypeSafeAPIResponseValidationError Bases:TypeSafeAPIErrorA successful HTTP response whose body was missing or structurally invalid required data. ### field\_path `instance-attribute` ```python theme={null} field_path = field_path ``` Dotted path to the offending field, such as `answers.tone.confidence`. ### args `instance-attribute` ```python theme={null} args = ( status, body, headers, field_path, endpoint, ) ``` # Retries Source: https://docs.typesafe.ai/sdk/python/api/retries Configure retries with RetryPolicy — attempt count, retryable statuses, backoff, and retry headers handling. ## typesafe\_sdk.RetryPolicy `dataclass` Configuration for SDK retry behavior. Examples: ```python theme={null} from typesafe_sdk import RetryPolicy, TypeSafeClient client = TypeSafeClient( retry=RetryPolicy( max_retries=3, timeout=10.0, http_statuses={429, 500, 502, 503, 504} ) ) ``` ### max\_retries `class-attribute` `instance-attribute` Maximum retries after the initial attempt; `0` disables retries. ### backoff\_initial `class-attribute` `instance-attribute` First backoff delay in seconds, doubled each attempt up to `backoff_max`; zero disables backoff. ### backoff\_max `class-attribute` `instance-attribute` Maximum backoff delay in seconds; zero disables backoff. ### backoff\_jitter `class-attribute` `instance-attribute` Fraction of each backoff delay randomly subtracted, between 0 and 1. ### http\_statuses `class-attribute` `instance-attribute` HTTP status codes that are retried. ### respect\_retry\_after `class-attribute` `instance-attribute` Whether to honor `Retry-After` and `retry-after-ms` response headers. ### api\_connection\_error `class-attribute` `instance-attribute` Whether to retry `TypeSafeAPIConnectionError`, raised when the request cannot reach or read from the server. ### api\_timeout\_error `class-attribute` `instance-attribute` Whether to retry `TypeSafeAPITimeoutError`, raised when the request exceeds its timeout. ### exceptions `class-attribute` `instance-attribute` Additional exception types that trigger a retry, on top of the built-in rules. ### predicate `class-attribute` `instance-attribute` An optional predicate called with the raised exception; returning `True` triggers a retry in addition to the other rules. ### timeout `class-attribute` `instance-attribute` Total retry budget in seconds per SDK call, including the initial attempt and delays; `None` disables the limit. Stops before a retry whose delay would reach or exceed the budget, re-raising the last error. # Common types Source: https://docs.typesafe.ai/sdk/python/api/types/common Common types for TypeSafe API SDK. ## typesafe\_sdk.JSONValue `module-attribute` A JSON-like value. May be nested and contain `None`. ## typesafe\_sdk.JSONContent `module-attribute` Either a plain string or a mapping/sequence of [`JSONValue`](/sdk/python/api/types/common#typesafe_sdk.JSONValue) entries. # Questions Source: https://docs.typesafe.ai/sdk/python/api/types/questions Provide state and ask yes/no, choice, and score questions using objects or dictionaries. ## State `state` is the text or JSON object you want to ask questions about. It cannot be `None`, but values inside an object may be `None`. ## Question objects Use `Noul`, `Choice`, and `Score` to define questions with named arguments. ## typesafe\_sdk.NoulCriteria Bases:TypedDictOptional descriptions of the yes and no outcomes. See the [noul primitive](https://docs.typesafe.ai/primitives/noul) for details. ### true `instance-attribute` Description of the yes outcome as text, a JSON object, or an array; `None` leaves it undescribed. ### false `instance-attribute` Description of the no outcome as text, a JSON object, or an array; `None` leaves it undescribed. ## typesafe\_sdk.Noul Bases: `wire.NoulQuestion` A yes/no question with optional descriptions for either outcome. See the [noul primitive](https://docs.typesafe.ai/primitives/noul) for details. ### instructions `class-attribute` `instance-attribute` The question to ask, expressed as text, a JSON object, or an array; optional. ### criteria `class-attribute` `instance-attribute` Optional descriptions of the yes and no outcomes. ## typesafe\_sdk.Choice Bases: `wire.ChoiceQuestion` A question that selects between named alternatives. See the [choice primitive](https://docs.typesafe.ai/primitives/choice) for details. ### criteria `instance-attribute` Labels mapped to text, object, or array descriptions, or `None` for undescribed labels. ### instructions `class-attribute` `instance-attribute` The question to ask, expressed as text, a JSON object, or an array; optional. ## typesafe\_sdk.Score Bases: `wire.ScoreQuestion` A question that assigns a score using an ordered rubric. See the [score primitive](https://docs.typesafe.ai/primitives/score) for details. ### criteria `instance-attribute` A nonempty, ordered list of text, object, or array descriptions, one per score from zero. ### instructions `class-attribute` `instance-attribute` The question to ask, expressed as text, a JSON object, or an array; optional. ## typesafe\_sdk.Question `module-attribute` A question object or question dictionary. ## typesafe\_sdk.Questions `module-attribute` Question inputs keyed by the names used to identify their answers. ## Question dictionaries Question dictionaries include a `type` key: `"noul"`, `"choice"`, or `"score"`. You can mix dictionaries and question objects in the same request. ## typesafe\_sdk.NoulModel Bases:TypedDictA yes/no question dictionary with `type="noul"`, allowing extra JSON fields. See the [noul primitive](https://docs.typesafe.ai/primitives/noul) for details. ### type `instance-attribute` ### instructions `instance-attribute` The question to ask, expressed as text, a JSON object, or an array; optional. ### criteria `instance-attribute` Optional descriptions of the yes and no outcomes. ## typesafe\_sdk.ChoiceModel Bases:TypedDictA choice question dictionary with `type="choice"`, allowing extra JSON fields. See the [choice primitive](https://docs.typesafe.ai/primitives/choice) for details. ### type `instance-attribute` ### instructions `instance-attribute` The question to ask, expressed as text, a JSON object, or an array; optional. ### criteria `instance-attribute` Labels mapped to text, object, or array descriptions, or `None` for undescribed labels. ## typesafe\_sdk.ScoreModel Bases:TypedDictA score question dictionary with `type="score"`, allowing extra JSON fields. See the [score primitive](https://docs.typesafe.ai/primitives/score) for details. ### type `instance-attribute` ### instructions `instance-attribute` The question to ask, expressed as text, a JSON object, or an array; optional. ### criteria `instance-attribute` A nonempty, ordered list of text, object, or array descriptions, one per score from zero. ## typesafe\_sdk.QuestionModel `module-attribute` A question dictionary identified by its `type` key. # Answers and responses Source: https://docs.typesafe.ai/sdk/python/api/types/responses Read answers, confidence scores, token usage, and available models returned by the TypeSafe API. ## Response ## typesafe\_sdk.SystemOneResponse Bases: `Response` Answers grouped by question type with model and usage metadata. See [System One](https://docs.typesafe.ai/concepts/system-one) for details. ### request\_id `cached` `property` The `x-typesafe-request-id` response header. ### raw\_http\_response `property` ```python theme={null} raw_http_response: httpx2.Response ``` The underlying `httpx2.Response`, exposing status, headers, and body. ### model `instance-attribute` The model used to answer the request. ### usage `instance-attribute` Token usage for the request. ### answers `class-attribute` `instance-attribute` All answer objects keyed by question name. ### nouls `cached` `property` Yes/no answers keyed by question name. ### choices `cached` `property` Choice answers keyed by question name. ### scores `cached` `property` Score answers keyed by question name. ## typesafe\_sdk.Usage Bases:msgspec.StructToken counts for a request, when reported by the API. ### input\_tokens `class-attribute` `instance-attribute` Number of input tokens used, or `None` when the API did not report it. ### output\_tokens `class-attribute` `instance-attribute` Number of output tokens used, or `None` when the API did not report it. ## Answers ## typesafe\_sdk.NoulAnswer Bases: `wire.NoulAnswer` A yes/no answer. See the [noul primitive](https://docs.typesafe.ai/primitives/noul) for details. ### noul `instance-attribute` Probability of a yes answer, from zero to one. ## typesafe\_sdk.ChoiceAnswer Bases: `wire.ChoiceAnswer` A selected label and its probabilities. See the [choice primitive](https://docs.typesafe.ai/primitives/choice) for details. ### choice `instance-attribute` The selected label. ### confidence `instance-attribute` Reported confidence in the selected label. ### probabilities `instance-attribute` Probabilities keyed by label. ## typesafe\_sdk.ScoreAnswer Bases: `wire.ScoreAnswer` An expected score with its rubric and probabilities. See the [score primitive](https://docs.typesafe.ai/primitives/score) for details. ### score `instance-attribute` Expected score, which may fall between the integer rubric levels. ### confidence `instance-attribute` Reported confidence in the score. ### legend `instance-attribute` Rubric descriptions keyed by integer score. ### probabilities `instance-attribute` Probabilities keyed by integer score. ## typesafe\_sdk.Answer `module-attribute` An answer to a single question, identified by its `type`. ## Available models ## typesafe\_sdk.ListModelsResponse Bases: `Response` The models available to the account. ### request\_id `cached` `property` The `x-typesafe-request-id` response header. ### raw\_http\_response `property` ```python theme={null} raw_http_response: httpx2.Response ``` The underlying `httpx2.Response`, exposing status, headers, and body. ### models `instance-attribute` The available models. ## typesafe\_sdk.ModelMetadata Bases:Struct### name `instance-attribute` ### description `instance-attribute` ### release\_date `instance-attribute` # Changelog Source: https://docs.typesafe.ai/sdk/python/changelog Python clients for the TypeSafe AI API ## v0.6.0 (2026-09-15) ### Breaking Changes * accept `Score.criteria` as an ordered sequence instead of a dictionary keyed by integers ### Features * improve type annotations on SDK inputs to accept abstract types like `Mapping` and `Sequence` * improve error messages to include http details and metadata ### Bug fixes * handle invalid values in `RetryPolicy` * make exceptions and responses picklable ### Documentation * link more concepts from main [docs](https://docs.typesafe.ai/) ## v0.5.7 (2026-09-14) This is the initial public release of TypeSafe Python SDK. Learn more in the [documentation](https://docs.typesafe.ai/sdk/python). # Usage Source: https://docs.typesafe.ai/sdk/python/usage Guides and patterns for working with the TypeSafe Python SDK. ## Calling the System One API## Choosing a model Inspect the available models: ```python theme={null} from typesafe_sdk import TypeSafeClient print(TypeSafeClient().models.list()) ``` Select the model when constructing a client: ```python theme={null} client = TypeSafeClient(model="jev") ``` See the [Models resource reference](/sdk/python/api/clients/sync/models) for details. ## Retries Pass a custom [`RetryPolicy`](/sdk/python/api/retries) as `retry` on the client or per call. ```python theme={null} import asyncio from typesafe_sdk import AsyncTypeSafeClient, Choice, Noul, Score async def main() -> None: async with AsyncTypeSafeClient() as client: result = await client.system_one( "I was charged twice. Please help ASAP.", { "billing": Noul(instructions="Is this about billing?"), "tone": Choice( instructions="What is the tone?", criteria={"calm": None, "angry": None}, ), "urgency": Score( instructions="How urgent is this?", criteria=["low", "medium", "high"], ), }, ) print( result.nouls["billing"].noul, result.choices["tone"].choice, result.scores["urgency"].score, ) asyncio.run(main()) ``` ```python theme={null} from typesafe_sdk import Choice, Noul, Score, TypeSafeClient client = TypeSafeClient() state = "I was charged twice. Please help ASAP." questions = { "billing": Noul(instructions="Is this about billing?"), "tone": Choice( instructions="What is the tone?", criteria={"calm": None, "angry": None} ), "urgency": Score( instructions="How urgent is this?", criteria=["low", "medium", "high"] ), } result = client.system_one(state, questions) print( result.nouls["billing"].noul, result.choices["tone"].choice, result.scores["urgency"].score, ) ``` ## Error handling Handle [exceptions](/sdk/python/api/exceptions) raised by the SDK: ```python theme={null} from typesafe_sdk import TypeSafeAPIError try: client.system_one(state, questions) except TypeSafeAPIError as error: print(error.status, error.request_id) ``` ## Logging The SDK logs to the `typesafe_sdk` logger. Configure it according to [standard logging](https://docs.python.org/3/library/logging.html) guide: ```python theme={null} import logging logging.getLogger("typesafe_sdk").setLevel(logging.DEBUG) ``` Or set `TYPESAFE_LOG_LEVEL` to one of `debug`, `info`, `warning`, `error`, or `off` before importing the SDK. `info` logs one summary line per request; `debug` also logs request and response headers and bodies. Secret headers — authorization, API keys, cookies, and any header whose name contains `token` or `secret` — are redacted from log output. Request and response bodies are **not** redacted. ## Environment variables The SDK reads and uses the following environment variables: | Variable | Configures | Default | | ------------------------ | --------------------------------------------------- | ------------------------- | | `TYPESAFE_API_KEY` | API key (required) | — | | `TYPESAFE_BASE_URL` | API root URL | `https://api.typesafe.ai` | | `TYPESAFE_DEFAULT_MODEL` | Default model | `jev-latest` | | `TYPESAFE_LOG_LEVEL` | `typesafe_sdk` logger level, applied once at import | unset | See the [constants reference](/sdk/python/api/constants) for SDK defaults. ## Forward compatibility The SDK keeps working as the TypeSafe API evolves, so you can adopt new API features before an SDK release adds first-class support for them. ### Extra request fields Send request fields this SDK version predates with [`extra_body`](/sdk/python/api/clients/sync/client): ```python theme={null} from typesafe_sdk import Noul, TypeSafeClient with TypeSafeClient() as client: client.system_one( "I was charged twice.", {"billing": Noul(instructions="About billing?")}, extra_body={"beam_width": 4}, ) ``` ### Raw question dictionaries Pass a question as a plain dictionary to include fields this SDK version does not model yet: ```python theme={null} from typesafe_sdk import TypeSafeClient with TypeSafeClient() as client: client.system_one( "I was charged twice.", {"billing": {"type": "noul", "instructions": "About billing?", "weight": 2}}, ) ``` ### Unknown answer kinds The SDK logs a warning and skips unrecognized answer kinds. Use `raw_http_response` to inspect the complete API response, including those answers: ```python theme={null} raw_answers = result.raw_http_response.json()["answers"] ``` ### Unknown response fields Unknown extra fields on recognized responses are ignored. ```python theme={null} from typesafe_sdk import RetryPolicy, TypeSafeClient client = TypeSafeClient(retry=RetryPolicy(max_retries=3, backoff_max=0.2, timeout=1.0)) ``` ```python theme={null} from typesafe_sdk import RetryPolicy client.system_one( state, questions, retry=RetryPolicy(max_retries=3, backoff_max=0.2, timeout=1.0) ) ```