GitHub

ai_error

API reference for ai_error.

The errors of AI services (Effect's AiError).

Every AI operation fails with one AiError: the module and method that failed and a reason saying why (a rate limit, a bad request, an invalid tool result, ...). Recover from one kind of reason with fx.catch_reason(AiError, RateLimitError, handler); is_retryable and retry_after read the reason.

Each error is a schema: its wire form is Effect's (camelCase keys with a _tag), so errors sent to a model as tool results, or stored in a chat history, read the same in both libraries.

Values

AttributeTypeDescription
HTTP_RESPONSE_DETAILSStructSchema[HttpResponseDetails, Never, Never]
HTTP_CONTEXTStructSchema[HttpContext, Never, Never]
USAGE_INFOStructSchema[UsageInfo, Never, Never]
PROVIDER_METADATARecordSchema[str, bool | int | float | str | Sequence[bool | int | float | str | ... | Mapping[str, JsonValue] | None] | Mapping[str, bool | int | float | str | Sequence[JsonValue] | ... | None] | None, str, bool | int | float | str | Sequence[bool | int | float | str | ... | Mapping[str, JsonValue] | None] | Mapping[str, bool | int | float | str | Sequence[JsonValue] | ... | None] | None, Never, Never]

Effect's ProviderMetadata schema.

REASONStuple[type[AiErrorReason], ...]
AI_ERROR_REASONS.Bottom[AnyReason, Mapping[str, object]]

The schema of every reason (Effect's AiErrorReason schema).

Types

TypeDefinitionDescription
ProviderMetadatatype ProviderMetadata = dict[str, JsonValue]

Provider-specific details, by provider name.

AuthenticationKindtype AuthenticationKind = Literal['InvalidKey', 'ExpiredKey', 'MissingKey', 'InsufficientPermissions', 'Unknown']
AnyReasontype AnyReason = RateLimitError | QuotaExhaustedError | AuthenticationError | ContentPolicyError | InvalidRequestError | InvalidResponseError | InternalProviderError | NetworkError | InvalidOutputError | StructuredOutputError | UnsupportedSchemaError | UnknownError | ToolNotFoundError | ToolParameterValidationError | InvalidToolResultError | ToolResultEncodingError | ToolConfigurationError | ToolkitRequiredError | InvalidUserInputError

Classes

Functions

make

make(*, module, method, reason) -> AiError
ParameterTypeDescription
modulestr
methodstr
reasonAnyReason

Returns AiError

def make(*, module: str, method: str, reason: AnyReason) -> AiError:
    return AiError(module=module, method=method, reason=reason)

is_ai_error

is_ai_error(u) -> bool
ParameterTypeDescription
uobject

Returns bool

def is_ai_error(u: object) -> bool:
    return isinstance(u, AiError)

is_ai_error_reason

is_ai_error_reason(u) -> bool
ParameterTypeDescription
uobject

Returns bool

def is_ai_error_reason(u: object) -> bool:
    return isinstance(u, AiErrorReason)

reason_from_http_status

reason_from_http_status(*, status, body=None, http=None, metadata=None, description=None) -> AnyReason

The reason an HTTP status stands for (400 a bad request, 401 / 403 refused credentials, 429 a rate limit, 5xx a provider failure).

ParameterTypeDescription
statusint
bodyobject = None
httpHttpContext | None = None
metadataProviderMetadata | None = None
descriptionstr | None = None

Returns AnyReason

def reason_from_http_status(
    *,
    status: int,
    body: object = None,
    http: HttpContext | None = None,
    metadata: ProviderMetadata | None = None,
    description: str | None = None,
) -> AnyReason:
    """The reason an HTTP ``status`` stands for (400 a bad request, 401 /
    403 refused credentials, 429 a rate limit, 5xx a provider failure)."""
    meta: ProviderMetadata = metadata or {}
    desc = description or None
    match status:
        case 400:
            return InvalidRequestError(description=desc, metadata=meta, http=http)
        case 401:
            return AuthenticationError(
                kind="InvalidKey", description=desc, metadata=meta, http=http
            )
        case 403:
            return AuthenticationError(
                kind="InsufficientPermissions", description=desc, metadata=meta, http=http
            )
        case 429:
            return RateLimitError(metadata=meta, http=http)
        case _ if status >= 500:
            return InternalProviderError(
                description=desc or "Server error", metadata=meta, http=http
            )
        case _:
            return UnknownError(description=desc, metadata=meta, http=http)

build_error_description

build_error_description(*, status, message, method, url, body, error_code=None, error_type=None, request_id=None) -> str

A one-line description of a failed HTTP call (Effect's buildErrorDescription).

ParameterTypeDescription
statusint
messagestr | None
methodstr
urlstr
bodystr | None
error_codestr | int | None = None
error_typestr | None = None
request_idstr | None = None

Returns str

def build_error_description(
    *,
    status: int,
    message: str | None,
    method: str,
    url: str,
    body: str | None,
    error_code: str | int | None = None,
    error_type: str | None = None,
    request_id: str | None = None,
) -> str:
    """A one-line description of a failed HTTP call (Effect's
    ``buildErrorDescription``)."""
    parts = [message or f"HTTP {status}", f"({method} {url})"]
    if error_code:
        parts.append(f"[code: {error_code}]")
    elif error_type:
        parts.append(f"[type: {error_type}]")
    if request_id:
        parts.append(f"[requestId: {request_id}]")
    if not message and body:
        parts.append(f"Response: {body[:200] + '...' if len(body) > 200 else body}")
    return " ".join(parts)