AiError.ts
AiError.ts overview
Section titled “AiError.ts overview”Defines shared errors for AI operations.
AiError records where a failure happened and stores the detailed reason in a
reason field. Those reasons cover transport problems, provider responses,
rate limits, authentication, content policy failures, invalid requests,
invalid output, unsupported schemas, tool failures, invalid user input, and
unknown failures. This module also includes metadata schemas, guards,
constructors, and helpers for converting HTTP response information into AI
error reasons.
Since v4.0.0
Exports Grouped by Category
Section titled “Exports Grouped by Category”- configuration
- AuthenticationErrorMetadata (interface)
- ContentPolicyErrorMetadata (interface)
- InternalProviderErrorMetadata (interface)
- InvalidOutputErrorMetadata (interface)
- InvalidRequestErrorMetadata (interface)
- QuotaExhaustedErrorMetadata (interface)
- RateLimitErrorMetadata (interface)
- StructuredOutputErrorMetadata (interface)
- UnknownErrorMetadata (interface)
- UnsupportedSchemaErrorMetadata (interface)
- constructors
- guards
- models
- reason
- AuthenticationError (class)
- ContentPolicyError (class)
- InternalProviderError (class)
- InvalidOutputError (class)
- InvalidRequestError (class)
- InvalidToolResultError (class)
- InvalidUserInputError (class)
- NetworkError (class)
- QuotaExhaustedError (class)
- RateLimitError (class)
- StructuredOutputError (class)
- ToolConfigurationError (class)
- ToolNotFoundError (class)
- ToolParameterValidationError (class)
- ToolResultEncodingError (class)
- ToolkitRequiredError (class)
- UnknownError (class)
- UnsupportedSchemaError (class)
- schemas
configuration
Section titled “configuration”AuthenticationErrorMetadata (interface)
Section titled “AuthenticationErrorMetadata (interface)”Provider-specific metadata attached to AuthenticationError.
Signature
export interface AuthenticationErrorMetadata extends ProviderMetadata {}Since v4.0.0
ContentPolicyErrorMetadata (interface)
Section titled “ContentPolicyErrorMetadata (interface)”Provider-specific metadata attached to ContentPolicyError.
Signature
export interface ContentPolicyErrorMetadata extends ProviderMetadata {}Since v4.0.0
InternalProviderErrorMetadata (interface)
Section titled “InternalProviderErrorMetadata (interface)”Provider-specific metadata attached to InternalProviderError.
Signature
export interface InternalProviderErrorMetadata extends ProviderMetadata {}Since v4.0.0
InvalidOutputErrorMetadata (interface)
Section titled “InvalidOutputErrorMetadata (interface)”Provider-specific metadata attached to InvalidOutputError.
Signature
export interface InvalidOutputErrorMetadata extends ProviderMetadata {}Since v4.0.0
InvalidRequestErrorMetadata (interface)
Section titled “InvalidRequestErrorMetadata (interface)”Provider-specific metadata attached to InvalidRequestError.
Signature
export interface InvalidRequestErrorMetadata extends ProviderMetadata {}Since v4.0.0
QuotaExhaustedErrorMetadata (interface)
Section titled “QuotaExhaustedErrorMetadata (interface)”Provider-specific metadata attached to QuotaExhaustedError.
Signature
export interface QuotaExhaustedErrorMetadata extends ProviderMetadata {}Since v4.0.0
RateLimitErrorMetadata (interface)
Section titled “RateLimitErrorMetadata (interface)”Provider-specific metadata attached to RateLimitError.
Signature
export interface RateLimitErrorMetadata extends ProviderMetadata {}Since v4.0.0
StructuredOutputErrorMetadata (interface)
Section titled “StructuredOutputErrorMetadata (interface)”Provider-specific metadata attached to StructuredOutputError.
Signature
export interface StructuredOutputErrorMetadata extends ProviderMetadata {}Since v4.0.0
UnknownErrorMetadata (interface)
Section titled “UnknownErrorMetadata (interface)”Provider-specific metadata attached to UnknownError.
Signature
export interface UnknownErrorMetadata extends ProviderMetadata {}Since v4.0.0
UnsupportedSchemaErrorMetadata (interface)
Section titled “UnsupportedSchemaErrorMetadata (interface)”Provider-specific metadata attached to UnsupportedSchemaError.
Signature
export interface UnsupportedSchemaErrorMetadata extends ProviderMetadata {}Since v4.0.0
constructors
Section titled “constructors”Creates an AiError with the given reason.
Example (Creating an AI error)
import { Duration } from "effect"import { AiError } from "effect/unstable/ai"
const error = AiError.make({ module: "OpenAI", method: "completion", reason: new AiError.RateLimitError({ retryAfter: Duration.seconds(60) })})
console.log(error.message)// "OpenAI.completion: Rate limit exceeded. Retry after 1 minute"Signature
declare const make: (params: { readonly module: string readonly method: string readonly reason: AiErrorReason}) => AiErrorSince v4.0.0
reasonFromHttpStatus
Section titled “reasonFromHttpStatus”Maps HTTP status codes to semantic error reasons.
When to use
Use as the base mapping when provider packages translate HTTP status codes into provider-specific error reasons.
Example (Mapping an HTTP status to a reason)
import { AiError } from "effect/unstable/ai"
const reason = AiError.reasonFromHttpStatus({ status: 429, body: { error: "Rate limit exceeded" }})
console.log(reason._tag) // "RateLimitError"Signature
declare const reasonFromHttpStatus: (params: { readonly status: number readonly body?: unknown readonly http?: typeof HttpContext.Type readonly metadata?: typeof ProviderMetadata.Type readonly description?: string | undefined}) => AiErrorReasonSince v4.0.0
guards
Section titled “guards”isAiError
Section titled “isAiError”Type guard to check if a value is an AiError.
Example (Checking for an AI error)
import { AiError } from "effect/unstable/ai"
const someError = new Error("generic error")const aiError = AiError.make({ module: "Test", method: "example", reason: new AiError.RateLimitError({})})
console.log(AiError.isAiError(someError)) // falseconsole.log(AiError.isAiError(aiError)) // trueSignature
declare const isAiError: (u: unknown) => u is AiErrorSince v4.0.0
isAiErrorReason
Section titled “isAiErrorReason”Type guard to check if a value is an AiErrorReason.
Example (Checking for an AI error reason)
import { AiError } from "effect/unstable/ai"
const rateLimitError = new AiError.RateLimitError({})const genericError = new Error("generic error")
console.log(AiError.isAiErrorReason(rateLimitError)) // trueconsole.log(AiError.isAiErrorReason(genericError)) // falseSignature
declare const isAiErrorReason: (u: unknown) => u is AiErrorReasonSince v4.0.0
models
Section titled “models”AiErrorReason (type alias)
Section titled “AiErrorReason (type alias)”Union type of all semantic error reasons that can occur during AI operations.
Details
Every reason carries a semantic _tag, a human-readable message, and an
isRetryable getter. Provider-facing reasons may also include retry timing,
provider metadata, usage information, or HTTP context.
Signature
type AiErrorReason = | RateLimitError | QuotaExhaustedError | AuthenticationError | ContentPolicyError | InvalidRequestError | InternalProviderError | NetworkError | InvalidOutputError | StructuredOutputError | UnsupportedSchemaError | UnknownError | ToolNotFoundError | ToolParameterValidationError | InvalidToolResultError | ToolResultEncodingError | ToolConfigurationError | ToolkitRequiredError | InvalidUserInputErrorSince v4.0.0
ProviderMetadata (type alias)
Section titled “ProviderMetadata (type alias)”Type of provider-specific metadata attached to AI error reasons.
Details
Metadata is keyed by provider name, and each provider value is either mutable
JSON metadata or null.
Signature
type ProviderMetadata = typeof ProviderMetadata.TypeSince v4.0.0
reason
Section titled “reason”AuthenticationError (class)
Section titled “AuthenticationError (class)”Error indicating authentication or authorization failure.
Details
Authentication errors are never retryable without credential changes.
Example (Creating an authentication error)
import { AiError } from "effect/unstable/ai"
const authError = new AiError.AuthenticationError({ kind: "InvalidKey"})
console.log(authError.isRetryable) // falseconsole.log(authError.message)// "InvalidKey: Verify your API key is correct"Signature
declare class AuthenticationErrorSince v4.0.0
[ReasonTypeId] (property)
Section titled “[ReasonTypeId] (property)”Marks AuthenticationError as a semantic AI error reason for runtime guards.
Signature
readonly [ReasonTypeId]: "~effect/unstable/ai/AiError/Reason"Since v4.0.0
ContentPolicyError (class)
Section titled “ContentPolicyError (class)”Error indicating content policy violation.
Details
Content policy errors are never retryable without content changes.
Example (Creating a content policy error)
import { AiError } from "effect/unstable/ai"
const policyError = new AiError.ContentPolicyError({ description: "Input contains prohibited content"})
console.log(policyError.isRetryable) // falseconsole.log(policyError.message)// "Content policy violation: Input contains prohibited content"Signature
declare class ContentPolicyErrorSince v4.0.0
[ReasonTypeId] (property)
Section titled “[ReasonTypeId] (property)”Marks ContentPolicyError as a semantic AI error reason for runtime guards.
Signature
readonly [ReasonTypeId]: "~effect/unstable/ai/AiError/Reason"Since v4.0.0
InternalProviderError (class)
Section titled “InternalProviderError (class)”Error indicating the AI provider experienced an internal error.
Details
Internal provider errors are typically transient and are retryable.
Example (Creating an internal provider error)
import { AiError } from "effect/unstable/ai"
const providerError = new AiError.InternalProviderError({ description: "Server encountered an unexpected error"})
console.log(providerError.isRetryable) // trueconsole.log(providerError.message)// "Internal provider error: Server encountered an unexpected error"Signature
declare class InternalProviderErrorSince v4.0.0
[ReasonTypeId] (property)
Section titled “[ReasonTypeId] (property)”Marks InternalProviderError as a semantic AI error reason for runtime guards.
Signature
readonly [ReasonTypeId]: "~effect/unstable/ai/AiError/Reason"Since v4.0.0
InvalidOutputError (class)
Section titled “InvalidOutputError (class)”Error indicating failure to parse or validate LLM output.
Details
Invalid output errors are retryable since LLM outputs are non-deterministic.
Example (Creating an invalid output error)
import { AiError } from "effect/unstable/ai"
const parseError = new AiError.InvalidOutputError({ description: "Expected a string but received a number"})
console.log(parseError.isRetryable) // trueconsole.log(parseError.message)// "Invalid output: Expected a string but received a number"Signature
declare class InvalidOutputErrorSince v4.0.0
fromSchemaError (static method)
Section titled “fromSchemaError (static method)”Creates an InvalidOutputError from a Schema error.
Example (Creating an invalid output error from a schema error)
import { Schema } from "effect"import { AiError } from "effect/unstable/ai"
declare const schemaError: Schema.SchemaError
const parseError = AiError.InvalidOutputError.fromSchemaError(schemaError)Signature
declare const fromSchemaError: (error: Schema.SchemaError) => InvalidOutputErrorSince v4.0.0
[ReasonTypeId] (property)
Section titled “[ReasonTypeId] (property)”Marks InvalidOutputError as a semantic AI error reason for runtime guards.
Signature
readonly [ReasonTypeId]: "~effect/unstable/ai/AiError/Reason"Since v4.0.0
InvalidRequestError (class)
Section titled “InvalidRequestError (class)”Error indicating the request had invalid or malformed parameters.
Details
Invalid request errors require fixing the request and are not retryable.
Example (Creating an invalid request error)
import { AiError } from "effect/unstable/ai"
const invalidRequestError = new AiError.InvalidRequestError({ parameter: "temperature", constraint: "must be between 0 and 2", description: "Temperature value 5 is out of range"})
console.log(invalidRequestError.isRetryable) // falseconsole.log(invalidRequestError.message)// "Invalid request: parameter 'temperature' must be between 0 and 2. Temperature value 5 is out of range"Signature
declare class InvalidRequestErrorSince v4.0.0
[ReasonTypeId] (property)
Section titled “[ReasonTypeId] (property)”Marks InvalidRequestError as a semantic AI error reason for runtime guards.
Signature
readonly [ReasonTypeId]: "~effect/unstable/ai/AiError/Reason"Since v4.0.0
InvalidToolResultError (class)
Section titled “InvalidToolResultError (class)”Error indicating the tool handler returned an invalid result that does not match the tool’s schema.
Details
This error is not retryable because invalid results indicate a bug in the tool handler implementation.
Example (Creating an invalid tool result error)
import { AiError } from "effect/unstable/ai"
const error = new AiError.InvalidToolResultError({ toolName: "GetWeather", description: "Tool handler returned invalid result: missing 'temperature' field"})
console.log(error.isRetryable) // falseconsole.log(error.message)// "Tool 'GetWeather' returned invalid result: missing 'temperature' field"Signature
declare class InvalidToolResultErrorSince v4.0.0
[ReasonTypeId] (property)
Section titled “[ReasonTypeId] (property)”Marks InvalidToolResultError as a semantic AI error reason for runtime guards.
Signature
readonly [ReasonTypeId]: "~effect/unstable/ai/AiError/Reason"Since v4.0.0
InvalidUserInputError (class)
Section titled “InvalidUserInputError (class)”Error indicating the user provided invalid input in their prompt.
Details
This error is raised when the prompt contains content that is structurally valid but not supported by the provider (e.g., unsupported media types, unsupported file formats, etc.).
Example (Creating an invalid user input error)
import { AiError } from "effect/unstable/ai"
const error = new AiError.InvalidUserInputError({ description: "Unsupported media type 'video/mp4'. Supported types include images, application/pdf, text/plain"})
console.log(error.isRetryable) // falseconsole.log(error.message)// "Invalid user input: Unsupported media type 'video/mp4'. Supported types include images, application/pdf, text/plain"Signature
declare class InvalidUserInputErrorSince v4.0.0
[ReasonTypeId] (property)
Section titled “[ReasonTypeId] (property)”Marks InvalidUserInputError as a semantic AI error reason for runtime guards.
Signature
readonly [ReasonTypeId]: "~effect/unstable/ai/AiError/Reason"Since v4.0.0
NetworkError (class)
Section titled “NetworkError (class)”Error indicating a network-level failure before receiving a response.
Details
This error is raised when issues arise before receiving an HTTP response, such as network connectivity problems, request encoding issues, or invalid URLs.
Example (Creating a network error)
import { AiError } from "effect/unstable/ai"
const error = new AiError.NetworkError({ reason: "TransportError", request: { method: "POST", url: "https://api.openai.com/v1/completions", urlParams: [], hash: undefined, headers: { "Content-Type": "application/json" } }, description: "Connection timeout after 30 seconds"})
console.log(error.isRetryable) // trueconsole.log(error.message)// "Transport: Connection timeout after 30 seconds (POST https://api.openai.com/v1/completions)"Signature
declare class NetworkErrorSince v4.0.0
fromRequestError (static method)
Section titled “fromRequestError (static method)”Creates a NetworkError from a platform HttpClientError.RequestError.
Example (Creating a network error from a request error)
import { AiError } from "effect/unstable/ai"import type { HttpClientError } from "effect/unstable/http"
declare const platformError: HttpClientError.RequestError
const aiError = AiError.NetworkError.fromRequestError(platformError)Signature
declare const fromRequestError: (error: HttpClientError.RequestError) => NetworkErrorSince v4.0.0
[ReasonTypeId] (property)
Section titled “[ReasonTypeId] (property)”Marks NetworkError as a semantic AI error reason for runtime guards.
Signature
readonly [ReasonTypeId]: "~effect/unstable/ai/AiError/Reason"Since v4.0.0
QuotaExhaustedError (class)
Section titled “QuotaExhaustedError (class)”Error indicating account or billing limits have been reached.
Details
Quota exhausted errors are not retryable without user action.
Example (Creating a quota exhausted error)
import { AiError } from "effect/unstable/ai"
const quotaError = new AiError.QuotaExhaustedError({})
console.log(quotaError.isRetryable) // falseconsole.log(quotaError.message)// "Quota exhausted. Check your account billing and usage limits."Signature
declare class QuotaExhaustedErrorSince v4.0.0
[ReasonTypeId] (property)
Section titled “[ReasonTypeId] (property)”Marks QuotaExhaustedError as a semantic AI error reason for runtime guards.
Signature
readonly [ReasonTypeId]: "~effect/unstable/ai/AiError/Reason"Since v4.0.0
RateLimitError (class)
Section titled “RateLimitError (class)”Error indicating the request was rate limited.
Details
Rate limit errors are always retryable. When retryAfter is provided,
callers should wait that duration before retrying.
Example (Creating a rate limit error)
import { Duration } from "effect"import { AiError } from "effect/unstable/ai"
const rateLimitError = new AiError.RateLimitError({ retryAfter: Duration.seconds(60)})
console.log(rateLimitError.isRetryable) // trueconsole.log(rateLimitError.message) // "Rate limit exceeded. Retry after 1 minute"Signature
declare class RateLimitErrorSince v4.0.0
[ReasonTypeId] (property)
Section titled “[ReasonTypeId] (property)”Marks RateLimitError as a semantic AI error reason for runtime guards.
Signature
readonly [ReasonTypeId]: "~effect/unstable/ai/AiError/Reason"Since v4.0.0
StructuredOutputError (class)
Section titled “StructuredOutputError (class)”Error indicating the LLM generated text that does not conform to the requested structured output schema.
Details
Structured output errors are retryable since LLM outputs are non-deterministic.
Example (Creating a structured output error)
import { AiError } from "effect/unstable/ai"
const error = new AiError.StructuredOutputError({ description: "Expected a valid JSON object", responseText: '{"foo":}'})
console.log(error.isRetryable) // trueconsole.log(error.message)// "Structured output validation failed: Expected a valid JSON object"Signature
declare class StructuredOutputErrorSince v4.0.0
fromSchemaError (static method)
Section titled “fromSchemaError (static method)”Creates a StructuredOutputError from a Schema error.
Example (Creating a structured output error from a schema error)
import { Schema } from "effect"import { AiError } from "effect/unstable/ai"
declare const schemaError: Schema.SchemaErrordeclare const rawText: string
const parseError = AiError.StructuredOutputError.fromSchemaError(schemaError, rawText)Signature
declare const fromSchemaError: (error: Schema.SchemaError, responseText: string) => StructuredOutputErrorSince v4.0.0
[ReasonTypeId] (property)
Section titled “[ReasonTypeId] (property)”Marks StructuredOutputError as a semantic AI error reason for runtime guards.
Signature
readonly [ReasonTypeId]: "~effect/unstable/ai/AiError/Reason"Since v4.0.0
ToolConfigurationError (class)
Section titled “ToolConfigurationError (class)”Error indicating a provider-defined tool was configured with invalid arguments.
Details
This error is not retryable because it indicates a programming error in the tool configuration that must be fixed in code.
Example (Creating a tool configuration error)
import { AiError } from "effect/unstable/ai"
const error = new AiError.ToolConfigurationError({ toolName: "OpenAiCodeInterpreter", description: "Invalid container ID format"})
console.log(error.isRetryable) // falseconsole.log(error.message)// "Invalid configuration for tool 'OpenAiCodeInterpreter': Invalid container ID format"Signature
declare class ToolConfigurationErrorSince v4.0.0
[ReasonTypeId] (property)
Section titled “[ReasonTypeId] (property)”Marks ToolConfigurationError as a semantic AI error reason for runtime guards.
Signature
readonly [ReasonTypeId]: "~effect/unstable/ai/AiError/Reason"Since v4.0.0
ToolNotFoundError (class)
Section titled “ToolNotFoundError (class)”Error indicating the model requested a tool that doesn’t exist in the toolkit.
Details
This error is retryable because the model may self-correct when provided with the list of available tools.
Example (Creating a tool not found error)
import { AiError } from "effect/unstable/ai"
const error = new AiError.ToolNotFoundError({ toolName: "unknownTool", availableTools: ["GetWeather", "GetTime"]})
console.log(error.isRetryable) // trueconsole.log(error.message)// "Tool 'unknownTool' not found. Available tools: GetWeather, GetTime"Signature
declare class ToolNotFoundErrorSince v4.0.0
[ReasonTypeId] (property)
Section titled “[ReasonTypeId] (property)”Marks ToolNotFoundError as a semantic AI error reason for runtime guards.
Signature
readonly [ReasonTypeId]: "~effect/unstable/ai/AiError/Reason"Since v4.0.0
ToolParameterValidationError (class)
Section titled “ToolParameterValidationError (class)”Error indicating the model’s tool call parameters failed schema validation.
Details
This error is retryable because the model may correct its parameters on subsequent attempts.
Example (Creating a tool parameter validation error)
import { AiError } from "effect/unstable/ai"
const error = new AiError.ToolParameterValidationError({ toolName: "GetWeather", toolParams: { location: 123 }, description: "Expected string, got number"})
console.log(error.isRetryable) // trueconsole.log(error.message)// "Invalid parameters for tool 'GetWeather': Expected string, got number"Signature
declare class ToolParameterValidationErrorSince v4.0.0
[ReasonTypeId] (property)
Section titled “[ReasonTypeId] (property)”Marks ToolParameterValidationError as a semantic AI error reason for runtime guards.
Signature
readonly [ReasonTypeId]: "~effect/unstable/ai/AiError/Reason"Since v4.0.0
ToolResultEncodingError (class)
Section titled “ToolResultEncodingError (class)”Error indicating the tool result cannot be encoded for sending back to the model.
Details
This error is not retryable because encoding failures indicate a bug in the tool schema definitions.
Example (Creating a tool result encoding error)
import { AiError } from "effect/unstable/ai"
const error = new AiError.ToolResultEncodingError({ toolName: "GetWeather", toolResult: { temperature: 72n }, description: "Cannot encode bigint values as JSON"})
console.log(error.isRetryable) // falseconsole.log(error.message)// "Failed to encode result for tool 'GetWeather': Cannot encode bigint values as JSON"Signature
declare class ToolResultEncodingErrorSince v4.0.0
[ReasonTypeId] (property)
Section titled “[ReasonTypeId] (property)”Marks ToolResultEncodingError as a semantic AI error reason for runtime guards.
Signature
readonly [ReasonTypeId]: "~effect/unstable/ai/AiError/Reason"Since v4.0.0
ToolkitRequiredError (class)
Section titled “ToolkitRequiredError (class)”Error indicating an operation requires a toolkit but none was provided.
Details
This error occurs when tool approval responses are present in the prompt but no toolkit was provided to resolve them.
Example (Creating a toolkit required error)
import { AiError } from "effect/unstable/ai"
const error = new AiError.ToolkitRequiredError({ pendingApprovals: ["GetWeather", "SendEmail"]})
console.log(error.isRetryable) // falseconsole.log(error.message)// "Toolkit required to resolve pending tool approvals: GetWeather, SendEmail"Signature
declare class ToolkitRequiredErrorSince v4.0.0
[ReasonTypeId] (property)
Section titled “[ReasonTypeId] (property)”Marks ToolkitRequiredError as a semantic AI error reason for runtime guards.
Signature
readonly [ReasonTypeId]: "~effect/unstable/ai/AiError/Reason"Since v4.0.0
UnknownError (class)
Section titled “UnknownError (class)”Error data for unknown or unexpected AI failures.
Details
Unknown errors are not retryable by default since the cause is unknown.
Example (Creating an unknown error)
import { AiError } from "effect/unstable/ai"
const unknownError = new AiError.UnknownError({ description: "An unexpected error occurred"})
console.log(unknownError.isRetryable) // falseconsole.log(unknownError.message)// "An unexpected error occurred"Signature
declare class UnknownErrorSince v4.0.0
[ReasonTypeId] (property)
Section titled “[ReasonTypeId] (property)”Marks UnknownError as a semantic AI error reason for runtime guards.
Signature
readonly [ReasonTypeId]: "~effect/unstable/ai/AiError/Reason"Since v4.0.0
UnsupportedSchemaError (class)
Section titled “UnsupportedSchemaError (class)”Error indicating a codec transformer rejected a schema because it contains unsupported constructs.
Details
Unsupported schema errors are not retryable because they indicate a programmer error where the schema is incompatible with the provider.
Example (Creating an unsupported schema error)
import { AiError } from "effect/unstable/ai"
const error = new AiError.UnsupportedSchemaError({ description: "Unions are not supported in Anthropic structured output"})
console.log(error.isRetryable) // falseconsole.log(error.message)// "Unsupported schema: Unions are not supported in Anthropic structured output"Signature
declare class UnsupportedSchemaErrorSince v4.0.0
[ReasonTypeId] (property)
Section titled “[ReasonTypeId] (property)”Marks UnsupportedSchemaError as a semantic AI error reason for runtime guards.
Signature
readonly [ReasonTypeId]: "~effect/unstable/ai/AiError/Reason"Since v4.0.0
schemas
Section titled “schemas”AiError (class)
Section titled “AiError (class)”Schema for the top-level AI error wrapper using the reason pattern.
When to use
Use when you need AI errors that can be handled by semantic reason with
Effect.catchReason.
Details
This error stores module and method context, the semantic reason, and
delegates isRetryable and retryAfter to the underlying reason.
Example (Handling an AI error by tag)
import { Effect } from "effect"import { AiError } from "effect/unstable/ai"
declare const aiOperation: Effect.Effect<string, AiError.AiError>
// Handle specific reason typesconst handled = aiOperation.pipe( Effect.catchTag("AiError", (error) => { if (error.reason._tag === "RateLimitError") { return Effect.succeed(`Retry after ${error.retryAfter}`) } return Effect.fail(error) }))Signature
declare class AiErrorSince v4.0.0
[TypeId] (property)
Section titled “[TypeId] (property)”Signature
readonly [TypeId]: "~effect/unstable/ai/AiError/AiError"cause (property)
Section titled “cause (property)”Signature
readonly cause: RateLimitError | QuotaExhaustedError | AuthenticationError | ContentPolicyError | InvalidRequestError | InternalProviderError | NetworkError | InvalidOutputError | StructuredOutputError | UnsupportedSchemaError | UnknownError | ToolNotFoundError | ToolParameterValidationError | InvalidToolResultError | ToolResultEncodingError | ToolConfigurationError | ToolkitRequiredError | InvalidUserInputErrorAiErrorEncoded (type alias)
Section titled “AiErrorEncoded (type alias)”The encoded (serialized) form of an AiError.
Signature
type AiErrorEncoded = (typeof AiError)["Encoded"]Since v4.0.0
AiErrorReason
Section titled “AiErrorReason”Schema for validating and parsing AI error reasons.
When to use
Use when decoding or validating unknown AI error reason values with Schema.
Details
This runtime schema is the union of the concrete AI error reason classes.
See
isAiErrorReasonfor checking an existing value without Schema decoding
Signature
declare const AiErrorReason: Schema.Union< [ typeof RateLimitError, typeof QuotaExhaustedError, typeof AuthenticationError, typeof ContentPolicyError, typeof InvalidRequestError, typeof InternalProviderError, typeof NetworkError, typeof InvalidOutputError, typeof StructuredOutputError, typeof UnsupportedSchemaError, typeof UnknownError, typeof ToolNotFoundError, typeof ToolParameterValidationError, typeof InvalidToolResultError, typeof ToolResultEncodingError, typeof ToolConfigurationError, typeof ToolkitRequiredError, typeof InvalidUserInputError ]>Since v4.0.0
HttpContext
Section titled “HttpContext”Schema for the combined HTTP context used in error reporting.
When to use
Use to attach request details, optional response details, and optional body text to AI provider errors.
Details
Includes the required request details plus optional response details and raw response body.
See
HttpRequestDetailsfor captured request detailsHttpResponseDetailsfor captured response details
Signature
declare const HttpContext: Schema.Struct<{ readonly request: Schema.Struct<{ readonly method: Schema.Literals<readonly ["GET", "POST", "PATCH", "PUT", "DELETE", "HEAD", "OPTIONS", "TRACE"]> readonly url: Schema.String readonly urlParams: Schema.$Array<Schema.Tuple<readonly [Schema.String, Schema.String]>> readonly hash: Schema.UndefinedOr<Schema.String> readonly headers: Schema.$Record< Schema.String, Schema.Union<readonly [Schema.String, Schema.Redacted<Schema.String>]> > }> readonly response: Schema.optional< Schema.Struct<{ readonly status: Schema.Number readonly headers: Schema.$Record< Schema.String, Schema.Union<readonly [Schema.String, Schema.Redacted<Schema.String>]> > }> > readonly body: Schema.optional<Schema.String>}>Since v4.0.0
ProviderMetadata
Section titled “ProviderMetadata”Schema for provider-specific metadata which can be attached to error reasons.
Details
Provider-specific metadata is namespaced by provider name. Each provider
value can contain arbitrary mutable JSON metadata or null.
Example (Inspecting metadata shape)
const metadata = { openai: { errorCode: "rate_limit_exceeded", requestId: "req_123" }, anthropic: null}Signature
declare const ProviderMetadata: Schema.$Record< Schema.String, Schema.NullOr<Schema.Codec<Schema.MutableJson, Schema.MutableJson, never, never>>>Since v4.0.0
UsageInfo
Section titled “UsageInfo”Schema for token usage information from AI operations.
Details
Schema for optional provider-reported token counts for prompt tokens, completion tokens, and total tokens.
Signature
declare const UsageInfo: Schema.Struct<{ readonly promptTokens: Schema.optional<Schema.Number> readonly completionTokens: Schema.optional<Schema.Number> readonly totalTokens: Schema.optional<Schema.Number>}>Since v4.0.0