Skip to content

AiError

The AiError module provides comprehensive error handling for AI operations.

This module defines a hierarchy of error types that can occur when working with AI services, including HTTP request/response errors, input/output validation errors, and general runtime errors. All errors follow Effect's structured error patterns and provide detailed context for debugging.

## Error Types

- HttpRequestError: Errors occurring during HTTP request processing - HttpResponseError: Errors occurring during HTTP response processing - MalformedInput: Errors when input data doesn't match expected format - MalformedOutput: Errors when output data can't be parsed or validated - UnknownError: Catch-all for unexpected runtime errors

12 exports Added in v1.0.0 Source

Errors

Error that occurs during HTTP request processing.

This error is raised when issues arise before receiving an HTTP response, such as network connectivity problems, request encoding issues, or invalid URLs.

Signature

declare class HttpRequestError extends any {
  constructor();
  readonly "~@effect/ai/AiError": "~@effect/ai/AiError";
  message: string;
  static fromRequestError(__namedParameters: {
    readonly error: RequestError;
    readonly method: string;
    readonly module: string;
  }): HttpRequestError;
}

Example

import { AiError } from "@effect/ai"
import * as Effect from "effect/Effect"
import * as Option from "effect/Option"

const handleNetworkError = Effect.gen(function* () {
  const error = new AiError.HttpRequestError({
    module: "OpenAI",
    method: "createCompletion",
    reason: "Transport",
    request: {
      method: "POST",
      url: "https://api.openai.com/v1/completions",
      urlParams: [],
      hash: Option.none(),
      headers: { "Content-Type": "application/json" },
    },
    description: "Connection timeout after 30 seconds",
  })

  console.log(error.message)
  // "Transport: Connection timeout after 30 seconds (POST https://api.openai.com/v1/completions)"
})

Error that occurs during HTTP response processing.

This error is thrown when issues arise after receiving an HTTP response, such as unexpected status codes, response decoding failures, or empty response bodies.

Signature

declare class HttpResponseError extends any {
  constructor();
  readonly "~@effect/ai/AiError": "~@effect/ai/AiError";
  message: string;
  static fromResponseError(__namedParameters: {
    readonly error: ResponseError;
    readonly method: string;
    readonly module: string;
  }): Effect<never, HttpResponseError>;
}

Example

import { AiError } from "@effect/ai"
import { Option } from "effect"

const responseError = new AiError.HttpResponseError({
  module: "OpenAI",
  method: "createCompletion",
  reason: "StatusCode",
  request: {
    method: "POST",
    url: "https://api.openai.com/v1/completions",
    urlParams: [],
    hash: Option.none(),
    headers: { "Content-Type": "application/json" },
  },
  response: {
    status: 429,
    headers: { "X-RateLimit-Remaining": "0" },
  },
  description: "Rate limit exceeded",
})

console.log(responseError.message)
// "StatusCode: Rate limit exceeded (429 POST https://api.openai.com/v1/completions)"

Error thrown when input data doesn't match the expected format or schema.

This error occurs when the data provided to an AI operation fails validation, is missing required fields, or doesn't conform to the expected structure.

Signature

declare class MalformedInput extends any {
  constructor();
  readonly "~@effect/ai/AiError": "~@effect/ai/AiError";
}

Example

import { AiError } from "@effect/ai"
import * as Effect from "effect/Effect"

const validateInput = (data: unknown): Effect.Effect<string, AiError.MalformedInput> =>
  typeof data === "string" && data.length > 0
    ? Effect.succeed(data)
    : Effect.fail(
        new AiError.MalformedInput({
          module: "ChatBot",
          method: "processMessage",
          description: "Input must be a non-empty string",
        }),
      )

const program = validateInput("").pipe(
  Effect.catchTag("MalformedInput", (error) => {
    console.log(`Input validation failed: ${error.description}`)
    return Effect.succeed("Please provide a valid message")
  }),
)

Error thrown when output data can't be parsed or validated.

This error occurs when AI service responses don't match the expected format, contain invalid data structures, or fail schema validation during parsing.

Signature

declare class MalformedOutput extends any {
  constructor();
  readonly "~@effect/ai/AiError": "~@effect/ai/AiError";
  static fromParseError(__namedParameters: {
    readonly description?: string;
    readonly error: ParseError;
    readonly method: string;
    readonly module: string;
  }): MalformedOutput;
}

Example

import { AiError } from "@effect/ai"
import { Effect, Schema } from "effect"

const ResponseSchema = Schema.Struct({
  message: Schema.String,
  tokens: Schema.Number,
})

const parseResponse = (data: unknown) =>
  Schema.decodeUnknown(ResponseSchema)(data).pipe(
    Effect.mapError(
      (parseError) =>
        new AiError.MalformedOutput({
          module: "OpenAI",
          method: "completion",
          description: "Response doesn't match expected schema",
          cause: parseError,
        }),
    ),
  )

const program = parseResponse({ invalid: "data" }).pipe(
  Effect.catchTag("MalformedOutput", (error) => {
    console.log(`Parsing failed: ${error.description}`)
    return Effect.succeed({ message: "Error", tokens: 0 })
  }),
)

UnknownError

Added in v1.0.0 Source

Catch-all error for unexpected runtime errors in AI operations.

This error is used when an unexpected exception occurs that doesn't fit into the other specific error categories. It provides context about where the error occurred and preserves the original cause for debugging.

Signature

declare class UnknownError extends any {
  constructor();
  readonly "~@effect/ai/AiError": "~@effect/ai/AiError";
  message: string;
}

Example

import { AiError } from "@effect/ai"
import { Effect } from "effect"

const riskyOperation = () => {
  try {
    // Some operation that might throw
    throw new Error("Unexpected network issue")
  } catch (cause) {
    return Effect.fail(
      new AiError.UnknownError({
        module: "ChatService",
        method: "sendMessage",
        description: "An unexpected error occurred during message processing",
        cause,
      }),
    )
  }
}

const program = riskyOperation().pipe(
  Effect.catchTag("UnknownError", (error) => {
    console.log(error.message)
    // "ChatService.sendMessage: An unexpected error occurred during message processing"
    return Effect.succeed("Service temporarily unavailable")
  }),
)

Guards

isAiError

Added in v1.0.0 Source

Type guard to check if a value is an AI error.

Signature

declare function isAiError(u: unknown): u is AiError;

Models

AiError type

Added in v1.0.0 Source

Union type representing all possible AI operation errors.

This type encompasses all error cases that can occur during AI operations, providing a comprehensive error handling surface for applications.

Signature

type AiError =
  | HttpRequestError
  | HttpResponseError
  | MalformedInput
  | MalformedOutput
  | UnknownError;

Example

import { AiError } from "@effect/ai"
import { Effect, Match } from "effect"

const handleAnyAiError = Match.type<AiError.AiError>().pipe(
  Match.tag("HttpRequestError", (err) => `Network error: ${err.reason}`),
  Match.tag("HttpResponseError", (err) => `Server error: HTTP ${err.response.status}`),
  Match.tag(
    "MalformedInput",
    (err) => `Invalid input: ${err.description || "Data validation failed"}`,
  ),
  Match.tag(
    "MalformedOutput",
    (err) => `Invalid response: ${err.description || "Response parsing failed"}`,
  ),
  Match.orElse((err) => `Unknown error: ${err.message}`),
)

Schemas

AiError

Added in v1.0.0 Source

Schema for validating and parsing AI errors.

This schema can be used to decode unknown values into properly typed AI errors, ensuring type safety when handling errors from external sources or serialized data.

Signature

declare const AiError: Union<
  [
    typeof HttpRequestError,
    typeof HttpResponseError,
    typeof MalformedInput,
    typeof MalformedOutput,
    typeof UnknownError,
  ]
>;

Example

import { AiError } from "@effect/ai"
import { Schema, Effect } from "effect"

const parseAiError = (data: unknown) =>
  Schema.decodeUnknown(AiError.AiError)(data).pipe(
    Effect.map((error) => {
      console.log(`Parsed AI error: ${error._tag}`)
      return error
    }),
    Effect.catchAll(() =>
      Effect.succeed(
        new AiError.UnknownError({
          module: "Parser",
          method: "parseAiError",
          description: "Failed to parse error data",
        }),
      ),
    ),
  )

Schema for HTTP request details used in error reporting.

Captures comprehensive information about HTTP requests that failed, enabling detailed error analysis and debugging.

Signature

declare const HttpRequestDetails: any;

Example

import { AiError } from "@effect/ai"
import { Option } from "effect"

const requestDetails: typeof AiError.HttpRequestDetails.Type = {
  method: "POST",
  url: "https://api.openai.com/v1/completions",
  urlParams: [
    ["model", "gpt-4"],
    ["stream", "false"],
  ],
  hash: Option.some("#section1"),
  headers: { "Content-Type": "application/json" },
}

Schema for HTTP response details used in error reporting.

Captures essential information about HTTP responses that caused errors, including status codes and headers for debugging purposes.

Signature

declare const HttpResponseDetails: any;

Example

import { AiError } from "@effect/ai"

const responseDetails: typeof AiError.HttpResponseDetails.Type = {
  status: 429,
  headers: {
    "Content-Type": "application/json",
    "X-RateLimit-Remaining": "0",
    "Retry-After": "60",
  },
}

Type Ids

TypeId

Added in v1.0.0 Source

Unique identifier for AI errors.

Signature

declare const TypeId: "~@effect/ai/AiError";

TypeId type

Added in v1.0.0 Source

Type-level representation of the AI error identifier.

Signature

type TypeId = typeof TypeId;