### Install @typesafe-ai/sdk with npm Source: https://docs.typesafe.ai/sdk/javascript Install the SDK using npm. Requires Node.js 20 or newer. ```sh npm install @typesafe-ai/sdk ``` -------------------------------- ### Example: Using client.systemOne Source: https://docs.typesafe.ai/sdk/javascript/api/classes/TypeSafeClient Calls systemOne with a state string and a questions object, then logs the answer. The `noul` function is used to define a question. ```typescript const { answers } = await client.systemOne({ state: "I was charged twice. Please help.", questions: { billing: noul("Is this about billing?") }, }); console.log(answers.billing.noul); ``` -------------------------------- ### Create TypeSafeClient and call systemOne Source: https://docs.typesafe.ai/sdk/javascript Set TYPESAFE_API_KEY in your environment, then create a client and call systemOne with a state and questions object. The answer type is inferred from the questions. ```ts import { choice, TypeSafeClient } from "@typesafe-ai/sdk"; const client = new TypeSafeClient(); const response = await client.systemOne({ state: { document: "I was charged twice. Please fix this ASAP." }, questions: { category: choice("What is this ticket about?", { billing: null, technical: null, other: null, }), }, }); console.log(response.answers.category.choice); ``` -------------------------------- ### Constructor signature: new TypeSafeClient(config?) Source: https://docs.typesafe.ai/sdk/javascript/api/classes/TypeSafeClient Creates a client for the TypeSafe AI API. Explicit options take precedence over environment variables, then SDK defaults. Empty or whitespace-only environment values are ignored. Throws if the API key is missing, configuration is invalid, or the runtime is unsupported. ```typescript new TypeSafeClient(config?): TypeSafeClient; ``` -------------------------------- ### TypeSafeClient Source: https://docs.typesafe.ai/sdk/javascript/api/classes/TypeSafeClient Documentation for the TypeSafeClient class, including constructor, properties, and methods. ```APIDOC ## Constructor ### Description Creates a new TypeSafeClient instance for the TypeSafe AI API. ### Method Constructor ### Endpoint new TypeSafeClient(config?) ### Parameters - **config** (TypeSafeClientConfig) - Optional - Configuration options. Explicit options take precedence over environment variables, then SDK defaults. Empty or whitespace-only environment values are ignored. ### Returns TypeSafeClient ### Throws The API key is missing, configuration is invalid, or the runtime is unsupported. ## Property: baseURL ### Description API root with trailing slashes removed. ### Type string ## Property: defaultHeaders ### Description Additional headers sent with each request. ### Type Readonly> ## Property: defaultModel ### Description Model used when a request omits `model`. ### Type string ## Property: fetch ### Description HTTP fetch implementation. ### Type Fetch ## Property: logger ### Description The configured logger, filtered to `logLevel`. ### Type Logger ## Property: logLevel ### Description Configured log verbosity. ### Type LogLevel ## Property: models ### Description The models available to the account. ### Type Models ## Property: retry ### Description Retry settings with constructor overrides applied. ### Type RetryPolicy ## Property: timeout ### Description Timeout per attempt in milliseconds. ### Type number ## Method: systemOne() ### Description Answer named questions about text or structured state. ### Method systemOne ### Endpoint systemOne(request, options?) ### Parameters - **request** (SystemOneRequest) - Required - State, questions, and an optional model override. - **options** (RequestOptions) - Optional - Per-call timeout, retry, headers, and cancellation settings. ### Returns APIPromise> - Answers typed by question name and criteria, with model and token usage. ### Throws Questions are empty, or score criteria are not a list of at least two entries. The server returns a non-2xx response after retries. The request cannot connect or times out after retries. The caller aborts the request. ### Example ```ts const { answers } = await client.systemOne({ state: "I was charged twice. Please help.", questions: { billing: noul("Is this about billing?") }, }); console.log(answers.billing.noul); ``` ``` -------------------------------- ### list() Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/Models Lists the models available to the account. ```APIDOC ## list() ### Description Lists the models available to the account. ### Method list ### Signature ```ts list(options?): APIPromise; ``` ### Parameters - **options** (`RequestOptions`) - Optional - Request options for the API call. ### Returns - **APIPromise** - A promise that resolves to an array of ModelCard objects. ``` -------------------------------- ### Method signature: systemOne(request, options?) Source: https://docs.typesafe.ai/sdk/javascript/api/classes/TypeSafeClient Answer named questions about text or structured state. Throws if questions are empty, score criteria are not a list of at least two entries, the server returns a non-2xx response after retries, the request cannot connect or times out after retries, or the caller aborts the request. ```typescript systemOne(request, options?): APIPromise>; ``` -------------------------------- ### choice() Source: https://docs.typesafe.ai/sdk/javascript/api/functions/choice Creates a question that selects between named alternatives. ```APIDOC ## choice() ### Description Creates a question that selects between named alternatives. ### Signature ```ts function choice(instructions, criteria): ChoiceQuestion; ``` ### Type Parameters - **T** extends `ChoiceCriteria` ### Parameters - **instructions** (`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` ``` -------------------------------- ### then(onfulfilled?, onrejected?) Source: https://docs.typesafe.ai/sdk/javascript/api/classes/APIPromise Attaches callbacks for the resolution and/or rejection of the Promise. ```APIDOC ## Method: then(onfulfilled?, onrejected?) ### Description Attaches callbacks for the resolution and/or rejection of the Promise. ### Type Parameters - **TResult1** (`TResult1 = T`) - The type of the value returned by the onfulfilled callback. - **TResult2** (`TResult2 = never`) - The type of the value returned by the onrejected callback. ### Parameters - **onfulfilled?** (`((value) => TResult1 | PromiseLike) | null`) - The callback to execute when the Promise is resolved. - **onrejected?** (`((reason) => TResult2 | PromiseLike) | null`) - The callback to execute when the Promise is rejected. ### Returns `Promise` - A Promise for the completion of which ever callback is executed. ``` -------------------------------- ### score() Source: https://docs.typesafe.ai/sdk/javascript/api/functions/score Creates a score question using an ordered rubric. Takes instructions and criteria, returns a ScoreQuestion. ```APIDOC ## score() ### Description Creates a score question using an ordered rubric. ### Signature ```ts function score(instructions, criteria): ScoreQuestion; ``` ### Type Parameters - **T** - extends `ScoreCriteria` ### Parameters - **instructions** (`EntryType`) - The question as text, a JSON object or array, or `null`. - **criteria** (`T`) - At least two descriptions indexed by score from zero; entries may be `null`. ### Returns - **ScoreQuestion** - A score question object. ``` -------------------------------- ### withResponse() Source: https://docs.typesafe.ai/sdk/javascript/api/classes/APIPromise Return the parsed result, HTTP response, and request ID. ```APIDOC ## Method: withResponse() ### Description Return the parsed result, HTTP response, and request ID. ### Returns `Promise>` - A promise that resolves to an object containing the parsed result, HTTP response, and request ID. ``` -------------------------------- ### new APIPromise(responsePromise, parseResponse) Source: https://docs.typesafe.ai/sdk/javascript/api/classes/APIPromise Creates a new APIPromise instance with a response promise and a parse function. ```APIDOC ## Constructor ### new APIPromise(responsePromise, parseResponse) #### Parameters - **responsePromise** (`Promise`) - The promise that resolves to the HTTP response. - **parseResponse** (`(response) => Promise`) - A function that parses the response body into type T. #### Returns `APIPromise` - A new APIPromise instance. #### Description Creates a new APIPromise instance. The responsePromise is the underlying HTTP response promise, and parseResponse is used to parse the response body into the desired type. ``` -------------------------------- ### InternalServerError Class Source: https://docs.typesafe.ai/sdk/javascript/api/classes/InternalServerError Documentation for the InternalServerError class, including its constructor, properties, and static method. ```APIDOC ## Constructor ### new InternalServerError(status, body, headers, message?) Creates a new InternalServerError instance. #### Parameters - **status** (`number`) - HTTP status code. - **body** (`unknown`) - Response body. - **headers** (`Headers`) - HTTP response headers. - **message?** (`string`) - Optional error message. #### Returns - `InternalServerError` ## Properties ### body - **Type**: `unknown` - **Description**: Parsed JSON, response text, or `undefined` for an empty body. ### headers - **Type**: `Headers` - **Description**: HTTP response headers. ### requestId - **Type**: `string | undefined` - **Description**: Request ID from `x-typesafe-request-id`, or `undefined` when absent. ### status - **Type**: `number` - **Description**: HTTP response status code. ## Methods ### fromResponse(status, body, headers) - **Static**: Yes - **Description**: Create the error subclass for an HTTP status code. - **Parameters**: - **status** (`number`) - HTTP status code. - **body** (`unknown`) - Response body. - **headers** (`Headers`) - HTTP response headers. - **Returns**: `APIError` ``` -------------------------------- ### info(message, ...args): void Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/Logger Logs an info-level message with optional structured values. ```APIDOC ## info(message, ...args): void ### Description Logs an info-level message with optional structured values. ### Method `info` ### Signature `info(message: string, ...args: unknown[]): void` ### Parameters - `message` (string) - Required - The message to log. - `args` (...unknown[]) - Optional - Additional structured values to log. ### Returns `void` ``` -------------------------------- ### Questions Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/Questions Indexable interface that maps question names to Question objects. ```APIDOC ## Questions ### Description An indexable interface that maps string keys (question names) to Question objects. ### Type Signature ```ts [name: string]: Question ``` ### Index Signature - **key** (`string`) - The name used to identify the answer. - **value** (`Question`) - The question object associated with the key. ### Usage This interface is used to store and access questions by their answer identifiers. ``` -------------------------------- ### warn(message, ...args): void Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/Logger Logs a warning-level message with optional structured values. ```APIDOC ## warn(message, ...args): void ### Description Logs a warning-level message with optional structured values. ### Method `warn` ### Signature `warn(message: string, ...args: unknown[]): void` ### Parameters - `message` (string) - Required - The message to log. - `args` (...unknown[]) - Optional - Additional structured values to log. ### Returns `void` ``` -------------------------------- ### TypeSafeClient Source: https://docs.typesafe.ai/sdk/javascript/api The main client class for interacting with the TypeSafe AI API. Provides methods for creating questions and managing requests. ```APIDOC ## TypeSafeClient ### Description The main client class for interacting with the TypeSafe AI API. Provides methods for creating questions and managing requests. ### Constructor `new TypeSafeClient(config: TypeSafeClientConfig)` ### Parameters - **config** (TypeSafeClientConfig) - Required - Configuration object including API key, base URL, and retry policy. ### Methods - **choice(options: ChoiceQuestion): Promise** - Creates a choice-based question. - **noul(options: NoulQuestion): Promise** - Creates a noul-based question. - **score(options: ScoreQuestion): Promise** - Creates a scoring-based question. ### Example ```javascript const client = new TypeSafeClient({ apiKey: "your-api-key" }); const response = await client.choice({ prompt: "Which option is best?", choices: ["Option A", "Option B"] }); ``` ``` -------------------------------- ### TypeSafeClientConfig Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/TypeSafeClientConfig Configuration options for the TypeSafe AI SDK client. This interface allows users to customize the client behavior, including API key, base URL, logging, retry, and timeout settings. ```APIDOC ## TypeSafeClientConfig ### Description Client options for the TypeSafe AI SDK. Explicit values take precedence over environment variables, then SDK defaults. ### Properties #### apiKey? - **Type**: `string` - **Optional**: Yes - **Description**: Required API key; falls back to `TYPESAFE_API_KEY`. #### baseURL? - **Type**: `string` - **Optional**: Yes - **Description**: API root; falls back to `TYPESAFE_BASE_URL`, then `https://api.typesafe.ai`. #### dangerouslyAllowBrowser? - **Type**: `boolean` - **Optional**: Yes - **Description**: Allow browser use, exposing the API key to page users. Default: false. #### defaultHeaders? - **Type**: `Record` - **Optional**: Yes - **Description**: Additional request headers; per-call headers take precedence. #### defaultModel? - **Type**: `string` - **Optional**: Yes - **Description**: Default model; falls back to `TYPESAFE_DEFAULT_MODEL`, then `jev-latest`. #### fetch? - **Type**: `Fetch` - **Optional**: Yes - **Description**: Custom HTTP fetch implementation for transport configuration or tests. Default: global `fetch`. #### logger? - **Type**: `Logger` - **Optional**: Yes - **Description**: Logger filtered to `logLevel` and above. Default: prefixed `console`. #### logLevel? - **Type**: `LogLevel` - **Optional**: Yes - **Description**: 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? - **Type**: `Partial` - **Optional**: Yes - **Description**: Retry overrides; omitted fields use the defaults in `RetryPolicy`. #### timeout? - **Type**: `number` - **Optional**: Yes - **Description**: Timeout per attempt in milliseconds, without a total retry budget. Default: 10000. ``` -------------------------------- ### EntryType Source: https://docs.typesafe.ai/sdk/javascript/api/type-aliases/EntryType Type alias defining the allowed types for state, instructions, and criteria values. ```APIDOC ## Type Alias: EntryType ### Description Defines the type for values used as state, instructions, or criteria. Can be a string, a JSON object, an array of JSON values, or null. ### Definition ```ts type EntryType = | string | { [key: string]: JsonValue; } | JsonValue[] | null; ``` ### Allowed Types - **string** - A plain text value. - **object** - A JSON object with string keys and `JsonValue` values. - **array** - An array of `JsonValue` elements. - **null** - Represents an absent or null value. ### Usage Used wherever state, instructions, or criteria are expected in the SDK. ``` -------------------------------- ### Property: models Source: https://docs.typesafe.ai/sdk/javascript/api/classes/TypeSafeClient The models available to the account. ```typescript readonly models: Models; ``` -------------------------------- ### fromResponse() Source: https://docs.typesafe.ai/sdk/javascript/api/classes/AuthenticationError Static method to create the appropriate error subclass based on an HTTP status code. ```APIDOC ## Method: fromResponse() ### Description Create the error subclass for an HTTP status code. ### Signature ```ts static fromResponse( status, body, headers ): APIError; ``` ### Parameters - **status** (`number`) - Required - HTTP status code. - **body** (`unknown`) - Required - Response body. - **headers** (`Headers`) - Required - HTTP response headers. ### Returns [`APIError`](/sdk/javascript/api/classes/APIError) ### Inherited from [`APIError`](/sdk/javascript/api/classes/APIError).[`fromResponse`](/sdk/javascript/api/classes/APIError#sdk-fromresponse) ``` -------------------------------- ### Property: logLevel Source: https://docs.typesafe.ai/sdk/javascript/api/classes/TypeSafeClient Configured log verbosity. ```typescript readonly logLevel: LogLevel; ``` -------------------------------- ### choice Source: https://docs.typesafe.ai/sdk/javascript/api Creates a choice-based question for the TypeSafe AI system. Use this function to generate a question with predefined options and criteria. ```APIDOC ## choice ### Description Creates a choice-based question for the TypeSafe AI system. Use this function to generate a question with predefined options and criteria. ### Method Function ### Signature `choice(options: ChoiceQuestion): Promise` ### Parameters - **options** (ChoiceQuestion) - Required - The question configuration including prompt, choices, and criteria. ### Returns - **Promise** - The response containing the selected choice and usage information. ### Example ```javascript const response = await choice({ prompt: "Which option is best?", choices: ["Option A", "Option B"], criteria: "Select the most efficient option." }); ``` ``` -------------------------------- ### new NotFoundError(status, body, headers, message?) Source: https://docs.typesafe.ai/sdk/javascript/api/classes/NotFoundError Creates a new NotFoundError instance with the given HTTP status, body, headers, and optional message. ```APIDOC ## new NotFoundError(status, body, headers, message?) ### Description Creates a new NotFoundError instance representing an HTTP 404 error. ### Constructor ```ts theme={null} new NotFoundError( status, body, headers, message? ): NotFoundError; ``` ### Parameters - **status** (`number`) - Required - HTTP status code. - **body** (`unknown`) - Required - Response body. - **headers** (`Headers`) - Required - HTTP response headers. - **message?** (`string`) - Optional - Error message. ### Returns `NotFoundError` ``` -------------------------------- ### noul() Source: https://docs.typesafe.ai/sdk/javascript/api/functions/noul Documentation for the noul() function, which creates a yes/no question with optional descriptions for either outcome. ```APIDOC ## noul() ### Description Creates a yes/no question with optional descriptions for either outcome. ### Signature ```ts function noul(instructions?, criteria?): NoulQuestion; ``` ### Parameters - **instructions** (`EntryType`, optional, default `null`) - The question as text, a JSON object or array. - **criteria** (`object | null`, optional) - Optional descriptions of the yes and no outcomes. - `false?` (`EntryType`) - Description of the no outcome. - `true?` (`EntryType`) - Description of the yes outcome. ### Returns - **NoulQuestion** - The created yes/no question object. ``` -------------------------------- ### APIPromise.asResponse() Source: https://docs.typesafe.ai/sdk/javascript/api/classes/APIPromise Resolves to the raw Response without parsing the body. SDK requests buffer the full body under the request timeout before handoff; reading it afterwards is caller-owned. The caller owns the body; don't also await the parsed result on the same promise. ```ts asResponse(): Promise; ``` -------------------------------- ### Constructor Definition Source: https://docs.typesafe.ai/sdk/javascript/api/classes/RateLimitError Constructor signature for creating a new RateLimitError instance with status, body, headers, and optional message. Inherits from APIError. ```TypeScript new RateLimitError( status, body, headers, message? ): RateLimitError; ``` -------------------------------- ### Property: fetch Source: https://docs.typesafe.ai/sdk/javascript/api/classes/TypeSafeClient HTTP fetch implementation. ```typescript readonly fetch: Fetch; ``` -------------------------------- ### new APITimeoutError(timeoutMs, options?) Source: https://docs.typesafe.ai/sdk/javascript/api/classes/APITimeoutError Creates a new APITimeoutError instance with the specified timeout in milliseconds and optional error options. ```APIDOC ## new APITimeoutError(timeoutMs, options?) ### Description Creates a new APITimeoutError instance indicating that the full response did not arrive within the configured timeout. ### Constructor ```ts new APITimeoutError(timeoutMs, options?): APITimeoutError; ``` ### Parameters - **timeoutMs** (`number`) - Required - The timeout duration in milliseconds. - **options?** (`ErrorOptions`) - Optional - Additional error options. ### Returns `APITimeoutError` ### Overrides [`APIConnectionError.constructor`](/sdk/javascript/api/classes/APIConnectionError#sdk-constructor) ### Properties #### timeoutMs ```ts readonly timeoutMs: number; ``` Configured timeout in milliseconds. ``` -------------------------------- ### type Description = EntryType; Source: https://docs.typesafe.ai/sdk/javascript/api/type-aliases/Description Defines the Description type alias as an EntryType. A null value indicates that the label is undescribed. ```APIDOC ## Type Alias: Description ### Description A criterion description; `null` leaves the label undescribed. ### Definition ```ts type Description = EntryType; ``` ### Remarks - The type alias is defined as `EntryType`. - A value of `null` indicates that the label is undescribed. ``` -------------------------------- ### new APIConnectionError(message?, options?) Source: https://docs.typesafe.ai/sdk/javascript/api/classes/APIConnectionError Creates a new APIConnectionError instance. The message parameter defaults to 'Connection error.' and options can be provided as ErrorOptions. ```APIDOC ## new APIConnectionError(message?, options?) ### Description Creates a new APIConnectionError instance. This error is thrown when the request or response-body delivery fails due to DNS, TLS, connection closed, or similar issues. ### Constructor `new APIConnectionError(message?, options?): APIConnectionError` ### Parameters - **message** (`string`) - Optional - Default: `"Connection error."` - The error message. - **options** (`ErrorOptions`) - Optional - Additional error options. ### Returns `APIConnectionError` - A new APIConnectionError instance. ### Overrides [`TypeSafeError.constructor`](/sdk/javascript/api/classes/TypeSafeError#sdk-constructor) ``` -------------------------------- ### Property: baseURL Source: https://docs.typesafe.ai/sdk/javascript/api/classes/TypeSafeClient API root with trailing slashes removed. ```typescript readonly baseURL: string; ``` -------------------------------- ### ENV.logLevel property Source: https://docs.typesafe.ai/sdk/javascript/api/variables/ENV Defines the logLevel property of ENV, mapping to the TYPESAFE_LOG_LEVEL environment variable. Defaults to warn. ```ts readonly logLevel: "TYPESAFE_LOG_LEVEL" = "TYPESAFE_LOG_LEVEL"; ``` -------------------------------- ### SystemOneResult Interface Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/SystemOneResult The SystemOneResult interface defines the structure of a result object returned by the SDK, containing answers, model, and usage properties. ```APIDOC ## Interface: SystemOneResult ### Description Answers keyed by question name, with model and usage metadata. ### Type Parameters - **Q** (extends Questions) - The type of questions used to infer answer types. ### Properties #### answers - **Type**: `{ readonly [K in string | number | symbol]: ResultFor }` - **Description**: Answers with types inferred from the supplied questions. #### model - **Type**: `string` - **Description**: The model used to answer the request. #### usage - **Type**: `Usage` - **Description**: Token usage for the request. ``` -------------------------------- ### ChoiceQuestion Interface Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/ChoiceQuestion The ChoiceQuestion interface defines a question that selects between named alternatives. It includes a criteria property for outcome descriptions, an optional instructions property for the question text, and a type discriminator. ```APIDOC ## Interface: ChoiceQuestion ### Description A question that selects between named alternatives. ### Type Parameters - **T** - extends ChoiceCriteria, defaults to ChoiceCriteria ### Properties #### criteria - **Type**: T - **Required**: Yes - **Description**: Descriptions of the available outcomes. #### instructions - **Type**: EntryType - **Required**: No (optional) - **Description**: The question as text, a JSON object, or an array; optional or `null`. #### type - **Type**: "choice" - **Required**: Yes - **Description**: Discriminator field indicating this is a choice question. ``` -------------------------------- ### Questions interface index signature Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/Questions Defines an index signature for the Questions interface, allowing access to Question objects by name. ```typescript [name: string]: Question ``` -------------------------------- ### asResponse() Source: https://docs.typesafe.ai/sdk/javascript/api/classes/APIPromise Resolves to the raw Response without parsing the body. The caller owns the body; don't also await the parsed result on the same promise. ```APIDOC ## Method: asResponse() ### Description Resolves to the raw `Response` without parsing the body. SDK requests buffer the full body under the request timeout before handoff; reading it afterwards is caller-owned. The caller owns the body; don't also `await` the parsed result on the same promise. ### Returns `Promise` - A promise that resolves to the raw HTTP response. ``` -------------------------------- ### new TypeSafeError(message, options?) Source: https://docs.typesafe.ai/sdk/javascript/api/classes/TypeSafeError Creates a new TypeSafeError instance with the given message and optional error options. ```APIDOC ## new TypeSafeError(message, options?) ### Description Creates a new TypeSafeError instance with the given message and optional error options. ### Method Constructor ### Parameters - **message** (`string`) - Required - The error message. - **options?** (`ErrorOptions`) - Optional - Additional error options. ### Returns `TypeSafeError` ### Overrides `Error.constructor` ``` -------------------------------- ### new BadRequestError(status, body, headers, message?) Source: https://docs.typesafe.ai/sdk/javascript/api/classes/BadRequestError Creates a new BadRequestError instance. The constructor is inherited from APIError and initializes the error with the given status, body, headers, and optional message. ```APIDOC ## Constructor ### Description Creates a new BadRequestError instance representing an HTTP 400 error. ### Signature ```ts new BadRequestError( status, body, headers, message? ): BadRequestError; ``` ### Parameters - **status** (`number`) - Required - HTTP status code. - **body** (`unknown`) - Required - Response body. - **headers** (`Headers`) - Required - HTTP response headers. - **message?** (`string`) - Optional - Error message. ### Returns `BadRequestError` ``` -------------------------------- ### catch(onrejected?) Source: https://docs.typesafe.ai/sdk/javascript/api/classes/APIPromise Attaches a callback for only the rejection of the Promise. ```APIDOC ## Method: catch(onrejected?) ### Description Attaches a callback for only the rejection of the Promise. ### Type Parameters - **TResult** (`TResult = never`) - The type of the value returned by the onrejected callback. ### Parameters - **onrejected?** (`((reason) => TResult | PromiseLike) | null`) - The callback to execute when the Promise is rejected. ### Returns `Promise` - A Promise for the completion of the callback. ``` -------------------------------- ### debug(message, ...args): void Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/Logger Logs a debug-level message with optional structured values. ```APIDOC ## debug(message, ...args): void ### Description Logs a debug-level message with optional structured values. ### Method `debug` ### Signature `debug(message: string, ...args: unknown[]): void` ### Parameters - `message` (string) - Required - The message to log. - `args` (...unknown[]) - Optional - Additional structured values to log. ### Returns `void` ``` -------------------------------- ### new APIError(status, body, headers, message?) Source: https://docs.typesafe.ai/sdk/javascript/api/classes/APIError Constructs a new APIError instance with the given HTTP status, response body, headers, and optional message. ```APIDOC ## Constructor: new APIError(status, body, headers, message?) ### Description Creates a new APIError instance representing an unsuccessful HTTP response. ### Parameters - **status** (`number`) - Required - HTTP response status code. - **body** (`unknown`) - Required - Parsed JSON, response text, or `undefined` for an empty body. - **headers** (`Headers`) - Required - HTTP response headers. - **message** (`string`) - Optional - Error message. ### Returns `APIError` ### Overrides [`TypeSafeError`](/sdk/javascript/api/classes/TypeSafeError).[`constructor`](/sdk/javascript/api/classes/TypeSafeError#sdk-constructor) ``` -------------------------------- ### noul Source: https://docs.typesafe.ai/sdk/javascript/api Creates a noul-based question for the TypeSafe AI system. Use this function to generate a question that expects a free-form or structured answer. ```APIDOC ## noul ### Description Creates a noul-based question for the TypeSafe AI system. Use this function to generate a question that expects a free-form or structured answer. ### Method Function ### Signature `noul(options: NoulQuestion): Promise` ### Parameters - **options** (NoulQuestion) - Required - The question configuration including prompt and expected answer format. ### Returns - **Promise** - The response containing the generated answer and usage information. ### Example ```javascript const response = await noul({ prompt: "Explain the concept of recursion.", format: "paragraph" }); ``` ``` -------------------------------- ### APIPromise.then() Source: https://docs.typesafe.ai/sdk/javascript/api/classes/APIPromise Attaches callbacks for the resolution and/or rejection of the Promise. The onfulfilled callback is executed when the Promise is resolved, and onrejected when rejected. Returns a Promise for the completion of whichever callback is executed. ```ts then(onfulfilled?, onrejected?): Promise; ``` -------------------------------- ### APIPromise constructor Source: https://docs.typesafe.ai/sdk/javascript/api/classes/APIPromise Creates an APIPromise instance. The responsePromise is a Promise for the raw HTTP Response, and parseResponse is a function that converts the Response into the parsed result type T. ```ts new APIPromise(responsePromise, parseResponse): APIPromise; ``` -------------------------------- ### fromResponse(status, body, headers) Source: https://docs.typesafe.ai/sdk/javascript/api/classes/UnprocessableEntityError Static method inherited from APIError that creates the appropriate error subclass based on the HTTP status code. For a 422 status, it returns an UnprocessableEntityError. ```APIDOC ## Method: fromResponse ### Description Creates the error subclass for an HTTP status code. This static method is inherited from APIError and is used to instantiate the correct error type based on the response status. ### Signature ```ts static fromResponse( status, body, headers ): APIError; ``` ### Parameters - **status** (`number`) - Required - HTTP response status code. - **body** (`unknown`) - Required - Parsed JSON, response text, or `undefined` for an empty body. - **headers** (`Headers`) - Required - HTTP response headers. ### Returns `APIError` - The appropriate error subclass instance. ``` -------------------------------- ### APIError.fromResponse(status, body, headers) Source: https://docs.typesafe.ai/sdk/javascript/api/classes/APIError Static method that creates the appropriate error subclass for a given HTTP status code. ```APIDOC ## Method: static fromResponse(status, body, headers) ### Description Creates the error subclass for an HTTP status code. ### Parameters - **status** (`number`) - Required - HTTP response status code. - **body** (`unknown`) - Required - Response body. - **headers** (`Headers`) - Required - HTTP response headers. ### Returns `APIError` ``` -------------------------------- ### Property: retry Source: https://docs.typesafe.ai/sdk/javascript/api/classes/TypeSafeClient Retry settings with constructor overrides applied. ```typescript readonly retry: RetryPolicy; ``` -------------------------------- ### RequestOptions Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/RequestOptions Per-call options that override client settings. This interface allows users to customize headers, retry behavior, cancellation, and timeout for individual API calls. ```APIDOC ## Interface: RequestOptions ### Description Per-call options that override client settings. ### Properties #### headers? - **Type**: `Record` - **Optional**: Yes - **Description**: Additional headers, merged over `defaultHeaders`. #### retry? - **Type**: `Partial` - **Optional**: Yes - **Description**: Retry overrides for this call; omitted fields inherit client settings. #### signal? - **Type**: `AbortSignal` - **Optional**: Yes - **Description**: Cancellation signal for the request and pending retries. #### timeout? - **Type**: `number` - **Optional**: Yes - **Description**: Timeout per attempt in milliseconds; there is no total retry budget. ``` -------------------------------- ### new AuthenticationError() Source: https://docs.typesafe.ai/sdk/javascript/api/classes/AuthenticationError Constructor for the AuthenticationError class, which represents an HTTP 401 authentication failure. ```APIDOC ## Constructor ### Description Creates a new AuthenticationError instance representing an HTTP 401 authentication failure. ### Signature ```ts new AuthenticationError( status, body, headers, message? ): AuthenticationError; ``` ### Parameters - **status** (`number`) - Required - HTTP status code. - **body** (`unknown`) - Required - Response body. - **headers** (`Headers`) - Required - HTTP response headers. - **message** (`string`) - Optional - Error message. ### Returns `AuthenticationError` ### Inherited from [`APIError`](/sdk/javascript/api/classes/APIError).[`constructor`](/sdk/javascript/api/classes/APIError#sdk-constructor) ``` -------------------------------- ### Property: defaultHeaders Source: https://docs.typesafe.ai/sdk/javascript/api/classes/TypeSafeClient Additional headers sent with each request. ```typescript readonly defaultHeaders: Readonly>; ``` -------------------------------- ### score Source: https://docs.typesafe.ai/sdk/javascript/api Creates a scoring-based question for the TypeSafe AI system. Use this function to generate a question that evaluates a response against criteria and returns a score. ```APIDOC ## score ### Description Creates a scoring-based question for the TypeSafe AI system. Use this function to generate a question that evaluates a response against criteria and returns a score. ### Method Function ### Signature `score(options: ScoreQuestion): Promise` ### Parameters - **options** (ScoreQuestion) - Required - The question configuration including prompt, criteria, and scoring legend. ### Returns - **Promise** - The response containing the score and usage information. ### Example ```javascript const response = await score({ prompt: "Rate the quality of this essay.", criteria: "Clarity, coherence, and grammar.", legend: { 1: "Poor", 2: "Fair", 3: "Good", 4: "Excellent" } }); ``` ``` -------------------------------- ### ENV.baseURL property Source: https://docs.typesafe.ai/sdk/javascript/api/variables/ENV Defines the baseURL property of ENV, mapping to the TYPESAFE_BASE_URL environment variable. Defaults to https://api.typesafe.ai. ```ts readonly baseURL: "TYPESAFE_BASE_URL" = "TYPESAFE_BASE_URL"; ``` -------------------------------- ### AuthenticationError constructor Source: https://docs.typesafe.ai/sdk/javascript/api/classes/AuthenticationError Creates a new AuthenticationError instance with status, body, headers, and optional message. Inherited from APIError. ```typescript new AuthenticationError( status, body, headers, message? ): AuthenticationError; ``` -------------------------------- ### fromResponse(status, body, headers) Source: https://docs.typesafe.ai/sdk/javascript/api/classes/PermissionDeniedError Static method inherited from APIError that creates the appropriate error subclass for an HTTP status code. For a 403 status, it returns a PermissionDeniedError instance. ```APIDOC ## Method: fromResponse(status, body, headers) ### Description Static method that creates the error subclass for an HTTP status code. For a 403 status, it returns a PermissionDeniedError instance. ### Parameters - **status** (`number`) - Required - HTTP response status code. - **body** (`unknown`) - Required - Parsed JSON, response text, or `undefined` for an empty body. - **headers** (`Headers`) - Required - HTTP response headers. ### Returns [`APIError`](/sdk/javascript/api/classes/APIError) ### Inherited from [`APIError`](/sdk/javascript/api/classes/APIError).[`fromResponse`](/sdk/javascript/api/classes/APIError#sdk-fromresponse) ``` -------------------------------- ### NotFoundError.fromResponse(status, body, headers) Source: https://docs.typesafe.ai/sdk/javascript/api/classes/NotFoundError Static method to create the appropriate error subclass for an HTTP status code, returning an APIError instance. ```APIDOC ## NotFoundError.fromResponse(status, body, headers) ### Description Creates the error subclass for an HTTP status code. Inherited from APIError. ### Method `static fromResponse(status, body, headers): APIError` ### Parameters - **status** (`number`) - Required - HTTP status code. - **body** (`unknown`) - Required - Response body. - **headers** (`Headers`) - Required - HTTP response headers. ### Returns `APIError` ``` -------------------------------- ### fromResponse static method Source: https://docs.typesafe.ai/sdk/javascript/api/classes/AuthenticationError Creates the error subclass for an HTTP status code. Inherited from APIError. ```typescript static fromResponse( status, body, headers ): APIError; ``` -------------------------------- ### ENV.apiKey property Source: https://docs.typesafe.ai/sdk/javascript/api/variables/ENV Defines the apiKey property of ENV, mapping to the TYPESAFE_API_KEY environment variable. Required when the apiKey option is omitted. ```ts readonly apiKey: "TYPESAFE_API_KEY" = "TYPESAFE_API_KEY"; ``` -------------------------------- ### Property: logger Source: https://docs.typesafe.ai/sdk/javascript/api/classes/TypeSafeClient The configured logger, filtered to `logLevel`. ```typescript readonly logger: Logger; ``` -------------------------------- ### map(fn) Source: https://docs.typesafe.ai/sdk/javascript/api/classes/APIPromise Transform the parsed result, sharing the HTTP response and a single body parse. ```APIDOC ## Method: map(fn) ### Description Transform the parsed result, sharing the HTTP response and a single body parse. ### Type Parameters - **U** (`U`) - The type of the transformed result. ### Parameters - **fn** (`(data) => U`) - A function that takes the parsed data and returns a new value. ### Returns `APIPromise` - A new APIPromise with the transformed result. ``` -------------------------------- ### RetryPolicy Interface Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/RetryPolicy Configuration object for retry behavior. All properties are optional and inherit defaults when not set. ```APIDOC ## RetryPolicy Interface ### Description Configuration for retry behavior. Partial overrides inherit unset fields from the client or SDK defaults. ### Properties #### apiConnectionError - **Type**: `boolean` - **Default**: `true` - **Description**: Retry connection failures, including interrupted response bodies (`APIConnectionError`). #### apiTimeoutError - **Type**: `boolean` - **Default**: `true` - **Description**: Whether to retry `APITimeoutError`. #### backoffInitialMs - **Type**: `number` - **Default**: `500` - **Description**: First backoff delay in milliseconds, doubled up to `backoffMaxMs`. #### backoffJitter - **Type**: `number` - **Default**: `0.25` - **Description**: Fraction of each backoff delay randomly subtracted, from 0 to 1. #### backoffMaxMs - **Type**: `number` - **Default**: `5000` - **Description**: Maximum backoff delay in milliseconds. #### httpStatuses - **Type**: `ReadonlySet` - **Default**: `408`, `429`, and `500–599` - **Description**: HTTP status codes to retry. #### maxRetries - **Type**: `number` - **Default**: `2` - **Description**: Maximum retries after the initial attempt; `0` disables retries. #### maxRetryAfterMs - **Type**: `number` - **Default**: `60000` - **Description**: Maximum server retry delay in milliseconds; longer delays use backoff. #### respectRetryAfter - **Type**: `boolean` - **Default**: `true` - **Description**: Honor `Retry-After` and `retry-after-ms` up to `maxRetryAfterMs`. ``` -------------------------------- ### new UnprocessableEntityError(status, body, headers, message?) Source: https://docs.typesafe.ai/sdk/javascript/api/classes/UnprocessableEntityError Constructor for creating an UnprocessableEntityError instance. It is typically used internally by the SDK when an HTTP 422 response is received. ```APIDOC ## Constructor ### Description Creates a new UnprocessableEntityError instance representing an HTTP 422 request validation failure. ### Signature ```ts new UnprocessableEntityError( status, body, headers, message? ): UnprocessableEntityError; ``` ### Parameters - **status** (`number`) - Required - HTTP response status code. - **body** (`unknown`) - Required - Parsed JSON, response text, or `undefined` for an empty body. - **headers** (`Headers`) - Required - HTTP response headers. - **message?** (`string`) - Optional - Error message. ### Returns `UnprocessableEntityError` ``` -------------------------------- ### SystemOneRequestPayload Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/SystemOneRequestPayload Interface representing the request payload for the POST /v1/systemone endpoint. It extends SystemOneRequest and includes a resolved model field. ```APIDOC ## Interface: SystemOneRequestPayload ### Description Request body for `POST /v1/systemone`, with the model resolved. ### Extends - [`SystemOneRequest`](/sdk/javascript/api/interfaces/SystemOneRequest) ### Properties #### model - **Type**: `string` - **Required**: Yes - **Description**: Model override; omitted values inherit `defaultModel`. - **Overrides**: [`SystemOneRequest`](/sdk/javascript/api/interfaces/SystemOneRequest).[`model`](/sdk/javascript/api/interfaces/SystemOneRequest#sdk-model) #### questions - **Type**: `Questions` - **Required**: Yes - **Description**: 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 - **Type**: `EntryType` - **Required**: Yes - **Description**: 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) ``` -------------------------------- ### ModelCard Interface Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/ModelCard The ModelCard interface represents metadata for an available model. It contains readonly properties for description, name, and release date. ```APIDOC ## Interface: ModelCard ### Description Metadata for an available model. ### Properties #### description - **Type**: `string` - **Readonly**: Yes - **Description**: A description of the model. #### name - **Type**: `string` - **Readonly**: Yes - **Description**: The name of the model. #### release_date - **Type**: `string` - **Readonly**: Yes - **Description**: The release date of the model. ``` -------------------------------- ### new APIUserAbortError(message?, options?) Source: https://docs.typesafe.ai/sdk/javascript/api/classes/APIUserAbortError Creates a new APIUserAbortError instance. The error is thrown when the caller cancels a request via an AbortSignal. ```APIDOC ## new APIUserAbortError(message?, options?) ### Description Creates a new APIUserAbortError instance. This error is thrown when the caller cancels a request through an AbortSignal. ### Constructor `new APIUserAbortError(message?, options?): APIUserAbortError` ### Parameters - **message** (`string`, optional) - Default: `"Request was aborted."` - The error message. - **options** (`ErrorOptions`, optional) - Additional error options. ### Returns `APIUserAbortError` ### Overrides [`TypeSafeError.constructor`](/sdk/javascript/api/classes/TypeSafeError#sdk-constructor) ``` -------------------------------- ### Constructor signature for InternalServerError Source: https://docs.typesafe.ai/sdk/javascript/api/classes/InternalServerError Creates a new InternalServerError instance. The constructor accepts status, body, headers, and an optional message. It is inherited from APIError. ```typescript new InternalServerError( status, body, headers, message? ): InternalServerError; ``` -------------------------------- ### new PermissionDeniedError(status, body, headers, message?) Source: https://docs.typesafe.ai/sdk/javascript/api/classes/PermissionDeniedError Creates a new PermissionDeniedError instance. This constructor is inherited from APIError and is used to represent an HTTP 403 error. ```APIDOC ## Constructor: new PermissionDeniedError(status, body, headers, message?) ### Description Creates a new PermissionDeniedError instance representing an HTTP 403 access denied error. ### Parameters - **status** (`number`) - Required - HTTP response status code. - **body** (`unknown`) - Required - Parsed JSON, response text, or `undefined` for an empty body. - **headers** (`Headers`) - Required - HTTP response headers. - **message** (`string`) - Optional - Error message. ### Returns `PermissionDeniedError` ### Inherited from [`APIError`](/sdk/javascript/api/classes/APIError).[`constructor`](/sdk/javascript/api/classes/APIError#sdk-constructor) ``` -------------------------------- ### Description type alias definition Source: https://docs.typesafe.ai/sdk/javascript/api/type-aliases/Description Defines the Description type as an alias for EntryType. A value of null leaves the label undescribed. ```typescript type Description = EntryType; ``` -------------------------------- ### LOG_LEVELS Source: https://docs.typesafe.ai/sdk/javascript/api/variables/LOG_LEVELS A readonly array of supported log levels, ordered from most to least verbose. This constant can be used to iterate over or validate log level values. ```APIDOC ## LOG_LEVELS ### Description A readonly array of supported log levels, ordered from most to least verbose. ### Type `readonly LogLevel[]` ### Values The array contains log levels in the following order (most to least verbose): - (No explicit values provided in source) ### Usage This constant can be used to iterate over all supported log levels or to validate a given log level against the supported set. ### Example ```typescript import { LOG_LEVELS } from 'typesafe_ai'; // Iterate over all log levels for (const level of LOG_LEVELS) { console.log(level); } ``` ``` -------------------------------- ### APIConnectionError constructor Source: https://docs.typesafe.ai/sdk/javascript/api/classes/APIConnectionError Creates a new APIConnectionError instance. The message parameter defaults to "Connection error." and options can be provided as ErrorOptions. ```typescript new APIConnectionError(message?, options?): APIConnectionError; ``` -------------------------------- ### BadRequestError.fromResponse(status, body, headers) Source: https://docs.typesafe.ai/sdk/javascript/api/classes/BadRequestError Static method to create the appropriate error subclass for an HTTP status code. Inherited from APIError. ```APIDOC ## Method: fromResponse ### Description Creates the error subclass for an HTTP status code. This static method is inherited from APIError. ### Signature ```ts static fromResponse( status, body, headers ): APIError; ``` ### Parameters - **status** (`number`) - Required - HTTP status code. - **body** (`unknown`) - Required - Response body. - **headers** (`Headers`) - Required - HTTP response headers. ### Returns `APIError` ``` -------------------------------- ### Property: defaultModel Source: https://docs.typesafe.ai/sdk/javascript/api/classes/TypeSafeClient Model used when a request omits `model`. ```typescript readonly defaultModel: string; ``` -------------------------------- ### WithResponse Interface Source: https://docs.typesafe.ai/sdk/javascript/api/interfaces/WithResponse The WithResponse interface exposes three properties: data (the parsed response body), requestId (the request ID from the x-typesafe-request-id header, or undefined), and response (the HTTP Response object with its body consumed). ```APIDOC ## Interface: WithResponse ### Description Represents parsed data with its HTTP response and request ID. ### Type Parameters - **T** - The type of the parsed response body. ### Properties #### data - **Type**: `T` - **Description**: The parsed response body. #### requestId - **Type**: `string | undefined` - **Description**: Request ID from `x-typesafe-request-id`, or `undefined` when absent. #### response - **Type**: `Response` - **Description**: The HTTP response, with its body consumed by parsing. ``` -------------------------------- ### Fetch Source: https://docs.typesafe.ai/sdk/javascript/api/type-aliases/Fetch The Fetch type alias defines a function signature for an HTTP fetch implementation. It accepts an input string and an optional RequestInit object, and returns a Promise that resolves to a Response. ```APIDOC ## Fetch ### Description The Fetch type alias represents an HTTP fetch implementation compatible with the global `fetch`. It takes an input string and an optional RequestInit object, and returns a Promise that resolves to a Response. ### Type Definition ```ts type Fetch = (input, init?) => Promise; ``` ### Parameters - **input** (`string`) - Required - The URL or request input. - **init** (`RequestInit`) - Optional - Additional request configuration options. ### Returns - `Promise` - A promise that resolves to a Response object. ```