Sycophant.Error (sycophant v0.4.2)

Copy Markdown

Root error module for Sycophant, built on Splode.

All errors returned by Sycophant implement Splode.Error and are organized into three classes:

  • :invalid - Caller mistakes that can be fixed before sending (e.g., MissingModel, MissingCredentials, InvalidParams)
  • :provider - Remote failures from the LLM API (e.g., RateLimited, ServerError, BadRequest, AuthenticationFailed)
  • :unknown - Uncategorized errors

Pattern match on the error class or specific error module:

case Sycophant.generate_text("openai:gpt-4o-mini", messages) do
  {:ok, response} -> response.text
  {:error, %Sycophant.Error.Provider.RateLimited{}} -> "Rate limited, retry later"
  {:error, %Sycophant.Error.Invalid.MissingCredentials{}} -> "Missing API key"
  {:error, error} -> Splode.Error.message(error)
end

Summary

Functions

Traverses errors, calling fun for each leaf error, and returns a nested map of results grouped by each error's path.

Raises an error if the result is an error, otherwise returns the result

Types

class()

@type class() :: %{
  :__struct__ => class_module(),
  :__exception__ => true,
  :errors => [t()],
  :class => error_class(),
  :bread_crumbs => [String.t()],
  :vars => Keyword.t(),
  :stacktrace => Splode.Stacktrace.t() | nil,
  :context => map(),
  optional(atom()) => any()
}

class_module()

@type class_module() ::
  Sycophant.Error.Unknown | Sycophant.Error.Provider | Sycophant.Error.Invalid

error_class()

@type error_class() :: :unknown | :provider | :invalid

t()

@type t() :: %{
  :__struct__ => module(),
  :__exception__ => true,
  :class => error_class(),
  :bread_crumbs => [String.t()],
  :vars => Keyword.t(),
  :stacktrace => Splode.Stacktrace.t() | nil,
  :context => map(),
  optional(atom()) => any()
}

Functions

splode_error?(arg1, splode)

traverse_errors(error_or_errors, fun)

Traverses errors, calling fun for each leaf error, and returns a nested map of results grouped by each error's path.

See Splode.traverse_errors/2 for full documentation.

Example

iex> Elixir.Sycophant.Error.traverse_errors(error, fn error ->
...>   Exception.message(error)
...> end)
%{name: ["name is required"]}

unwrap!(result, opts \\ nil)

Raises an error if the result is an error, otherwise returns the result

Alternatively, you can use the defsplode macro, which does this automatically.

Options

  • :error_opts - Options to pass to to_error/2 when converting the returned error
  • :unknown_error_opts - Options to pass to the unknown error if the function returns only :error. not necessary if your function always returns {:error, error}.

Examples

def function(arg) do

case do_something(arg) do
  :success -> :ok
  {:success, result} -> {:ok, result}
  {:error, error} -> {:error, error}
end

end

def function!(arg) do

YourErrors.unwrap!(function(arg))

end