Docs Learn
Errors, retries and timeouts
Failures are raised in F as subtypes of AnthropicError. Each failure mode is its own
class, so handling one is a pattern match.
You will learn
- How to recover from rate limits, API errors and timeouts
- Which failures are retried for you, and which are not
- Where to change the retry and timeout defaults
Typed errors#
Recover with an ordinary pattern match. An API error carries its HTTP status, the error type and message, and the request id to quote in a support ticket:
client.messages.create(request).recover {
case e: AnthropicError.RateLimited => s"retry in ${e.retryAfter}"
case e: AnthropicError.Api => s"${e.status} ${e.errorType}: ${e.errorMessage} (${e.requestId})"
case _: AnthropicError.Timeout => "timed out"
}
The Errors example asks for a model that does not exist on purpose, and matches the more specific
NotFound before the general Api case:
/** Typed errors: each failure mode is its own class, so handling is a pattern match. */
object Errors extends IOApp.Simple {
def run: IO[Unit] =
Anthropic4s.fromEnv[IO].use { client =>
val request = MessageRequest(Model.of("claude-does-not-exist"), 1024, MessageParam.user("Hi"))
client.messages
.create(request)
.map(_.text)
.recover {
case e: AnthropicError.NotFound => s"No such model (request ${e.requestId.getOrElse("?")})"
case e: AnthropicError.RateLimited =>
s"Slow down; retry in ${e.retryAfter.fold("a while")(_.toString)}"
case e: AnthropicError.Api => s"The API said ${e.status} ${e.errorType}: ${e.errorMessage}"
case _: AnthropicError.Timeout => "Timed out"
}
.flatMap(IO.println)
}
}
Retries#
Connection errors, timeouts, 408, 409, 429 and 5xx are retried twice with exponential backoff, honouring the
server's retry-after and x-should-retry headers. A request is never retried once a
response has started.
Changing the defaults#
Change the retry and timeout defaults for every call on AnthropicConfig, or for one call with
RequestOptions. RequestOptions is also where beta flags go
(RequestOptions.withBetas), as the WeatherAgent
does.
Recap
- Every failure is an
AnthropicError:RateLimited,NotFound,Api,Timeout,OutputParse, … - Two retries with backoff by default, never after a response has started.
AnthropicConfigfor the client,RequestOptionsfor one call.
Every snippet on this page is copied, character for character, from the
anthropic4s repository: its README, docs/play.md or examples/,
which compiles with the build.