Errors
Every fallible call returns Result<_, Error>. There is one error type, and its variants fall into three groups: refusals raised before anything left the process, transport failures where no answer came back, and answers the endpoint actually sent.
#[non_exhaustive]
pub enum Error {
// Refused here, before the request left the process.
UnsupportedCapability { endpoint: Arc<str>, capability: &'static str },
InvalidRequest { endpoint: Arc<str>, message: String },
MissingApiKey { endpoint: Arc<str>, variable: Option<String> },
// The request never completed.
Http { endpoint: Arc<str>, kind: TransportError, message: String },
// The endpoint answered, and the answer was an error.
BadRequest { endpoint: Arc<str>, body: String },
Unauthorized { endpoint: Arc<str>, status: u16, body: String },
NotFound { endpoint: Arc<str>, body: String },
RateLimit { endpoint: Arc<str>, retry_after: Option<Duration>, body: String },
QuotaExceeded { endpoint: Arc<str>, status: u16, body: String },
ServerError { endpoint: Arc<str>, status: u16, body: String },
Api { endpoint: Arc<str>, status: u16, body: String },
// The endpoint answered, but the body was unusable.
InvalidResponse { endpoint: Arc<str>, message: String },
Stream { endpoint: Arc<str>, message: String },
// The endpoint answered fine; the content was not what the caller wanted.
OutputMismatch { endpoint: Arc<str>, message: String, text: String, truncated: bool },
}
Http carries the message reqwest produced, and that message contains the URL the request was sent to. Query parameter values are withheld from it when the name is one you classified with secret_query, when it is the parameter Auth::Query uses, or when the name looks like a credential. Everything else stays readable, so an api-version that is being rejected is still visible. Headers never appear in a transport error at all, and every credential header is marked sensitive, so it prints as Sensitive rather than as a value anywhere a HeaderMap is rendered.
Implements Debug, Display, and std::error::Error, so it works with ?, anyhow, thiserror, and anything else expecting a standard error.
Both Debug and Display are written by hand, and both trim the endpoint's response body. See Printing an error.
The enum is #[non_exhaustive], so a match on it needs a catch-all arm. Variants added later will not break your build.
Every variant carries the endpoint's configured name, reachable with error.endpoint(), so an error from a multi-provider application says which backend produced it. It is the endpoint rather than the dialect, so a failure against a Claude-compatible gateway reports that gateway and not "Anthropic".
Why the answers are named rather than numbered
The endpoint's error responses could have been one variant carrying a status code, and for a while they were. They are named individually because a status code is not portable: the same number means different things on different vendors, and the classification needs information a caller does not have.
The clearest case is 429. On OpenAI-shaped endpoints it means either "you are sending too fast" or "your account is out of credit", separated only by a marker in the body. The first is worth retrying; the second will never succeed no matter how long you wait. A caller branching on the number alone cannot tell them apart, and will retry a dead account forever. Freyja reads the body once and reports RateLimit or QuotaExceeded accordingly.
The Api variant remains as the fallback, so a status Freyja does not classify arrives intact rather than being forced into an approximate category.
The helpers
Five methods answer the questions a caller actually has, so the knowledge does not have to be rebuilt per vendor at every call site:
| Method | Returns |
|---|---|
is_retryable() | Whether repeating the identical request could plausibly succeed |
retry_after() | The endpoint's own Retry-After delay, when it sent one |
status() | The HTTP status, for the errors that have one |
body() | The endpoint's raw response body, up to its first 64 KiB, for the errors that have one |
endpoint() | The endpoint's configured name, on every variant |
is_retryable() returning false means the request will fail the same way every time until something outside it changes: the key, the model name, the request body, or the account balance.
Nothing retries on its own. See Handling outages.
The variants
UnsupportedCapability
The request asked for something this provider cannot express. Freyja refuses rather than silently dropping the field, because a quietly ignored tool_choice produces a plausible looking answer that is wrong in a way you cannot see.
Anthropic does not support schema-less JSON response format
Raised before any network call. Current cases:
| Provider | Capability |
|---|---|
| Anthropic | server-side conversation continuation |
| Anthropic | schema-less JSON response format |
| OpenAI Chat Completions | server-side conversation continuation |
| OpenAI Responses, Anthropic | images outside user messages |
| all except OpenAI Chat Completions | non-text content in system/developer messages |
Both rows are uneven, and neither unevenness was designed. OpenAI Chat Completions keeps system turns as ordinary messages rather than hoisting them into a text-only field, so it has nothing to refuse. The image row was once every dialect, until probing found Chat Completions takes an image on any role and Gemini takes one on a model_output step. The Anthropic entry is the last that has never been tested.
Recovery means removing the field or switching providers. Retrying is pointless.
To ask in advance, use Client::check, which runs the same conversion without sending anything and hands back this same error. There is no table of booleans to consult, deliberately: support is not always a property of the field, and a table would be a second description of the dialects to keep in sync by hand.
InvalidRequest
The request is malformed and was rejected before leaving the process.
invalid request for OpenAI: tool messages may only contain tool results
This is a bug in your code, not a provider limitation, and switching providers will not help. Current cases:
| Condition | Where |
|---|---|
Text content on a Role::Tool turn | OpenAI Responses, Gemini |
| A tool message answering more than one call | OpenAI Chat Completions |
| Tool arguments that are not a JSON object | Anthropic |
| A malformed image data URI | Anthropic |
| A tool result whose call is absent from the transcript | Gemini |
| No model on the request and none on the endpoint | all |
Distinct from BadRequest, which is the endpoint rejecting a request Freyja was willing to send. See Messages and content.
MissingApiKey
Client::from_env found no key. The variable the endpoint names is unset or empty, or the endpoint names none.
OpenAI: OPENAI_API_KEY is unset or empty
variable holds the name, or None when the endpoint has no api_key_env. Set the variable, or build the client with Client::new or Client::without_key. An endpoint whose auth is Auth::None never raises it.
Http
The request never completed, so no status was ever received. kind says why:
TransportError | Cause | Retryable |
|---|---|---|
Timeout | No reply within the inactivity timeout | Yes |
Connect | DNS failure, connection refused, or rejected TLS | No |
Body | The connection died while the body was being read | Yes |
Other | Anything the classification above does not cover | No |
OpenAI timed out: error sending request for url (...)
Connect is one variant covering three causes because reqwest reports them identically, and because they call for the same response: fix the configuration rather than try again. A wrong host name and an expired certificate do not become right on the second attempt.
Note that Timeout and Body are retryable but not idempotent. The endpoint may have accepted and billed a request whose reply never arrived, so a retry can duplicate work you have already paid for.
BadRequest
400: the endpoint rejected the request body.
OpenAI rejected the request: {"error":{"message":"Invalid schema for function 'get_weather'",...}}
Not retryable: the same bytes will be rejected again. The raw body is preserved rather than parsed, so the vendor's own message is intact. The wire reference documents the JSON Freyja sends, which is usually the fastest way to interpret one of these.
Unauthorized
401 or 403: the credential is missing, wrong, or not permitted to use this model. Both statuses land here, and status says which.
OpenAI refused the credential (HTTP 401): {"error":{"message":"Incorrect API key provided",...}}
Not retryable: the key has to change.
NotFound
404: no such model, or the base URL is wrong.
Groq has no such model or endpoint: {"error":{"message":"The model `gpt-4o` does not exist"}}
Not retryable. On a custom endpoint this most often means the base URL already contains a path segment the dialect appends again; see Custom providers.
RateLimit
429: requests are arriving faster than the endpoint will serve them.
OpenAI rate limited the request, retry after 30s: {"error":{"message":"Rate limit reached",...}}
Retryable. retry_after carries the endpoint's own Retry-After header when it sent one, and is None otherwise, in which case your own backoff applies.
Only the delay-seconds form is read, so an endpoint sending the HTTP-date form RFC 9110 also allows reads as None. The value is clamped to freyja::error::MAX_RETRY_AFTER, one day. It is a number an endpoint hands you expecting you to sleep for it, and the pattern below does exactly that, so an unclamped Retry-After: 99999999999 would park a task for three thousand years. A gateway that meant milliseconds and wrote seconds does the same thing without meaning to.
Only the delay-seconds form of the header is parsed. The HTTP-date form would need a clock and a date parser, neither of which Freyja has a dependency for, and no major vendor sends it. An unreadable header is None rather than a guess.
QuotaExceeded
The account is out of credit or past a hard quota.
OpenAI quota exhausted (HTTP 429): {"error":{"code":"insufficient_quota",...}}
Not retryable by waiting: it needs billing action. This exists because several vendors report it with the same 429 they use for throttling, so a caller treating every 429 as a rate limit retries forever against an account that cannot serve the request.
Coverage is uneven, and deliberately so. The split keys on the insufficient_quota marker that OpenAI-shaped bodies carry, which covers both OpenAI dialects and the many third-party endpoints that copy them. Gemini reports both cases as RESOURCE_EXHAUSTED and cannot be split; Anthropic has no equivalent. On those, an exhausted quota arrives as RateLimit, and a bounded retry loop is the protection.
ServerError
5xx: the endpoint failed on its own side.
Anthropic failed with HTTP 529: {"type":"error","error":{"type":"overloaded_error",...}}
Retryable. The whole 500..=599 range maps here rather than a list of familiar codes, which is what catches Anthropic's non-standard 529 overload signal.
Api
A non-success status Freyja does not classify. The fallback arm.
local returned HTTP 418: {"detail":"teapot"}
is_retryable() reports true for a 5xx here and false otherwise, which is the most that can be said without knowing what the status means.
InvalidResponse
The provider answered successfully but the body could not be parsed. The message includes the parse error and the body.
invalid OpenAI response: missing field `id`; body: {...}
This means the vendor changed something Freyja models as required. Unknown fields, unknown output types, and unknown status strings are all tolerated already, so this only fires on a genuine break. Retrying will not help. Report it as a bug.
It also carries the one case that is not a parse failure: a response body that grew past 64 MiB, abandoned rather than buffered whole. The read timeout bounds silence and not volume, so an endpoint that keeps sending forever is never late. See Size limits for the streaming equivalent.
OutputMismatch
The call succeeded and the model's answer did not match the type generate_as was asked for. Only that method raises it.
OpenAI output did not match: missing field `purpose` at line 1 column 24
Distinct from InvalidResponse, and the distinction matters. InvalidResponse is the vendor's body being unreadable, which means Freyja has a bug and you should report it. Here the vendor behaved perfectly: a well-formed response arrived whose content is the wrong shape. That is a problem with your schema, your prompt, or your token cap.
It carries two things a bare serde_json::Error does not:
text is the model's answer, kept because the parse failure destroys the only record of what actually came back. Log it, show it, or salvage what you can from it.
truncated says whether the answer was cut short, checked against ResponseStatus::Incomplete rather than guessed from the parse error. This is the most common cause and the one most easily misread, half a JSON object produces EOF while parsing an object, which reads like a schema problem and is not:
Err(Error::OutputMismatch { truncated: true, .. }) => {
// Raise max_tokens. The schema is fine.
}
Not retryable. Model output is nondeterministic, so another attempt might parse by luck, but the request that produced this will keep producing it. Match the variant directly if you want to retry regardless.
Stream
A stream that the provider accepted then failed part-way through, reported in the provider's own error frame.
OpenAI stream failed: rate limit exceeded
Only streaming produces it, and it surfaces from EventStream::next rather than from Client::stream, which returns before the first frame is read. Calling EventStream::into_response on a stream you have not drained raises it too, rather than handing back a response that looks complete and is not.
It is distinct from the status-bearing variants, which report an answer that never began, and from InvalidResponse, which reports a body that could not be parsed at all. Whatever text arrived before the failure is already yours to keep; the response as a whole is not. Retrying means re-sending the request from the start, and paying for the prompt and the discarded output again. See Handling outages.
is_retryable() reports false for it, which is a deliberate understatement: the provider's error frame is not parsed, so Freyja cannot tell a transient overload from the into_response misuse, and the safe default is not to encourage a retry it cannot justify. Overload and rate limit conditions genuinely do arrive this way once the connection is open, so read the message and decide.
A stream that simply stops, with no error frame, is not this variant. It ends normally, and the Done event carries ResponseStatus::Incomplete because no terminal frame set anything else. Check status on Done, or on the response from into_response(), before treating a short answer as a complete one. See Streaming.
Printing an error
Both renderings trim the endpoint's body to freyja::error::BODY_IN_MESSAGE bytes, which is 2048, and say how much they dropped:
OpenAI rejected the request: {"error":{"message":"Invalid value for 'messages[1].
content': expected a string, got null. Offending value: …… (5096 more bytes)
The reason is that a rejected request is usually logged rather than read, and providers routinely quote the entire offending request back in a 400. One real OpenAI rejection produced a 7144 byte body, so error.to_string() was a single 7173 character log line describing one failed call. It is now 2098.
Debug is capped for the same reason and to the same length. Capping only Display would have missed most of the problem, since tracing::error!(?error) is at least as common as "{error}". Debug also trims OutputMismatch's text, which is the model's whole answer and therefore as large as a generation is allowed to be.
Nothing past the first 64 KiB of an error body is read, so a hostile endpoint cannot make every failed call hold a large body. Up to that cap nothing is lost. The fields are public, and error.body() reaches the whole kept body without matching on the variant:
Err(error) => {
tracing::error!("{error}"); // 2 KiB, for the log
if let Some(body) = error.body() {
std::fs::write("rejection.json", body)?; // all of it, for you
}
}
One thing the cap does not do: it bounds the size of what reaches your logs, not the content. A provider quoting your user's text back puts that text in the first few hundred bytes, well inside the cap. If your prompts carry data your logs should not hold, log error.endpoint() and error.status() rather than the error itself.
Handling errors
Propagate with ? when the caller decides:
async fn ask(agent: &Agent, question: &str) -> Result<String, Error> {
Ok(agent.ask(question).await?.answer)
}
Branch on the name when you want to act on the cause:
match agent.ask("What is 20 + 22?").await {
Ok(run) => println!("{}", run.answer),
Err(Error::RateLimit { retry_after, .. }) => {
back_off(retry_after.unwrap_or(Duration::from_secs(1)));
}
Err(Error::QuotaExceeded { .. }) => {
eprintln!("out of credit, retrying will not help");
}
Err(Error::Unauthorized { .. }) => eprintln!("check the API key"),
Err(error @ Error::UnsupportedCapability { .. }) => {
eprintln!("not portable: {error}");
}
Err(error) => eprintln!("{} failed: {error}", error.endpoint()),
}
Or skip the match entirely when all you need is whether to try again:
match agent.ask("What is 20 + 22?").await {
Ok(run) => println!("{}", run.answer),
Err(error) if error.is_retryable() => {
back_off(error.retry_after().unwrap_or(Duration::from_secs(1)));
}
Err(error) => return Err(error),
}
Retries and fallbacks
Wrapping a model in Retry tries a failed call again, and Fallback hands it to a backup model. Both decide with is_retryable(). See Handling outages.
What is not an error
A non Completed ResponseStatus is not an error. A truncated answer, a refusal, or a response waiting on tool results all come back as Ok, because the call succeeded and the response is real. Check response.status for those. See Responses.