Claudex.Client (Claudex v0.6.1)

Copy Markdown View Source

Connection settings for talking to the Claude API: your API key, the base URL, and how to handle timeouts and retries.

Build one with new/1 and pass it to functions like Claudex.Messages.create/2. Clients are plain structs, so you can hold several at once (different keys, different workspaces) without any shared process state.

Summary

Functions

Builds a client.

Decides whether a failed request should be retried, and how long to wait first. This is the :retry function every Claudex client is built with.

Types

t()

@type t() :: %Claudex.Client{
  api_key: String.t(),
  base_url: String.t(),
  max_retries: non_neg_integer(),
  req: Req.Request.t()
}

Functions

new(opts \\ [])

@spec new(keyword()) :: t()

Builds a client.

Every option can also be set in application config, so an app names its connection settings once:

config :claudex,
  api_key: System.fetch_env!("ANTHROPIC_API_KEY"),
  max_retries: 3

client = Claudex.new()

An option passed here wins over application config.

Options

  • :api_key - your Anthropic API key. Falls back to application config, then to the ANTHROPIC_API_KEY environment variable. Raises if none of the three is set.
  • :base_url - defaults to "https://api.anthropic.com".
  • :max_retries - retries for transient errors (429, 5xx, timeouts), defaults to 2.
  • :receive_timeout - how long to wait for a response once connected, in milliseconds, defaults to 10 minutes.
  • :connect_timeout - how long to wait for the TCP/TLS handshake, in milliseconds, defaults to 5 seconds — a slow or unreachable host fails fast instead of hanging for the full :receive_timeout.
  • :beta - beta features to opt into, as a string or a list of them. They become one anthropic-beta header.
  • :req_options - extra options merged into the underlying Req.new/1 call, for anything not covered above (a custom :adapter for tests, a :finch pool, ...).

retry_decision(request, response)

@spec retry_decision(Req.Request.t(), Req.Response.t() | Exception.t()) ::
  boolean() | {:delay, non_neg_integer()}

Decides whether a failed request should be retried, and how long to wait first. This is the :retry function every Claudex client is built with.

Returns false to give up, true to retry on Req's exponential backoff, or {:delay, milliseconds} to wait exactly that long — the last of these when the response named a retry-after, for the statuses Req doesn't already read that header on itself.

Connection errors, rate limits and 5xx are retried. A 409 is not: the API says to resolve the conflict first, so repeating the request can only fail again or duplicate work. A 408 is, because it comes from a proxy that gave up before the request reached the model — nothing was generated and nothing was billed, so the retry costs only the round trip.