use crate::router::{Hop, RouteStop};
use std::path::PathBuf;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("config error: {0}")]
Config(String),
#[error("failed to read {path}: {source}")]
Io {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("failed to parse {path}: {message}")]
Parse { path: PathBuf, message: String },
#[error("provider error: {0}")]
Provider(ProviderFailure),
#[error("session error: {0}")]
Session(String),
#[error("agent stopped after {0} iterations without a final answer")]
MaxIterations(usize),
#[error("cancelled")]
Cancelled,
#[error("stopped by a hook: {0}")]
Stopped(String),
#[error("{0}")]
Vision(String),
#[error("{}", .0.hint())]
AwaitingApproval(crate::approvals::Waiting),
#[error("the reply did not match the requested schema: {error}")]
Unparsed { error: String, reply: String },
}
impl From<rusqlite::Error> for Error {
fn from(e: rusqlite::Error) -> Self {
Error::Session(e.to_string())
}
}
impl Error {
pub fn io(path: impl Into<PathBuf>, source: std::io::Error) -> Self {
Error::Io {
path: path.into(),
source,
}
}
pub fn provider(message: impl Into<String>) -> Self {
Error::Provider(ProviderFailure::other(message))
}
pub fn provider_failure(&self) -> Option<&ProviderFailure> {
match self {
Error::Provider(f) => Some(f),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ProviderFailure {
#[error("could not reach {url}: {message}")]
Transport {
url: String,
message: String,
sent: bool,
},
#[error("unauthorized: {0}")]
Unauthorized(HttpFailure),
#[error("invalid request: {0}")]
InvalidRequest(HttpFailure),
#[error("{0}")]
Http(HttpFailure),
#[error("the reply was cut off before it finished: {message}")]
Truncated {
message: String,
streamed_chars: usize,
},
#[error("unexpected response: {message}")]
Response {
message: String,
body: Option<String>,
},
#[error("{}", describe_routed(route, trail, *stop, cause))]
Routed {
route: String,
trail: Vec<Hop>,
stop: RouteStop,
cause: Box<ProviderFailure>,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct HttpFailure {
pub status: u16,
pub body: String,
pub request_id: Option<String>,
pub retry_after_secs: Option<u64>,
pub hint: Option<String>,
}
impl std::fmt::Display for HttpFailure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "HTTP {}", self.status)?;
if !self.body.is_empty() {
write!(f, ": {}", self.body)?;
}
if let Some(id) = &self.request_id {
write!(f, " [request id {id}]")?;
}
if let Some(hint) = &self.hint {
write!(f, " — {hint}")?;
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ProviderFailureKind {
Transport,
Unauthorized,
InvalidRequest,
Http,
Truncated,
Response,
}
impl ProviderFailureKind {
pub fn as_str(self) -> &'static str {
match self {
ProviderFailureKind::Transport => "transport",
ProviderFailureKind::Unauthorized => "unauthorized",
ProviderFailureKind::InvalidRequest => "invalid_request",
ProviderFailureKind::Http => "http",
ProviderFailureKind::Truncated => "truncated",
ProviderFailureKind::Response => "response",
}
}
}
impl std::fmt::Display for ProviderFailureKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl ProviderFailure {
pub fn other(message: impl Into<String>) -> Self {
ProviderFailure::Response {
message: message.into(),
body: None,
}
}
pub fn kind(&self) -> ProviderFailureKind {
match self {
ProviderFailure::Transport { .. } => ProviderFailureKind::Transport,
ProviderFailure::Unauthorized(_) => ProviderFailureKind::Unauthorized,
ProviderFailure::InvalidRequest(_) => ProviderFailureKind::InvalidRequest,
ProviderFailure::Http(_) => ProviderFailureKind::Http,
ProviderFailure::Truncated { .. } => ProviderFailureKind::Truncated,
ProviderFailure::Response { .. } => ProviderFailureKind::Response,
ProviderFailure::Routed { cause, .. } => cause.kind(),
}
}
pub fn short_reason(&self) -> String {
match self {
ProviderFailure::Transport { message, .. } if message.contains("timed out") => {
"timeout".into()
}
ProviderFailure::Transport { message, .. }
if message.contains("could not be established") =>
{
"unreachable".into()
}
ProviderFailure::Transport { .. } => "connection error".into(),
ProviderFailure::Unauthorized(h)
| ProviderFailure::InvalidRequest(h)
| ProviderFailure::Http(h) => format!("HTTP {}", h.status),
ProviderFailure::Truncated { .. } => "stream cut".into(),
ProviderFailure::Response { .. } => "unreadable reply".into(),
ProviderFailure::Routed { cause, .. } => cause.short_reason(),
}
}
pub fn after_send(&self) -> bool {
match self {
ProviderFailure::Transport { sent, .. } => *sent,
ProviderFailure::Routed { cause, .. } => cause.after_send(),
_ => false,
}
}
pub fn is_retryable(&self) -> bool {
match self {
ProviderFailure::Transport { .. } => true,
ProviderFailure::Truncated { .. } => true,
ProviderFailure::Http(h) => is_retryable_status(h.status),
ProviderFailure::Unauthorized(_) | ProviderFailure::InvalidRequest(_) => false,
ProviderFailure::Response { .. } => false,
ProviderFailure::Routed { cause, .. } => cause.is_retryable(),
}
}
pub fn status(&self) -> Option<u16> {
match self {
ProviderFailure::Unauthorized(h)
| ProviderFailure::InvalidRequest(h)
| ProviderFailure::Http(h) => Some(h.status),
ProviderFailure::Routed { cause, .. } => cause.status(),
_ => None,
}
}
pub fn body(&self) -> Option<&str> {
match self {
ProviderFailure::Unauthorized(h)
| ProviderFailure::InvalidRequest(h)
| ProviderFailure::Http(h) => Some(&h.body),
ProviderFailure::Response { body, .. } => body.as_deref(),
ProviderFailure::Routed { cause, .. } => cause.body(),
_ => None,
}
}
pub fn request_id(&self) -> Option<&str> {
match self {
ProviderFailure::Unauthorized(h)
| ProviderFailure::InvalidRequest(h)
| ProviderFailure::Http(h) => h.request_id.as_deref(),
ProviderFailure::Routed { cause, .. } => cause.request_id(),
_ => None,
}
}
pub fn retry_after_secs(&self) -> Option<u64> {
match self {
ProviderFailure::Unauthorized(h)
| ProviderFailure::InvalidRequest(h)
| ProviderFailure::Http(h) => h.retry_after_secs,
ProviderFailure::Routed { cause, .. } => cause.retry_after_secs(),
_ => None,
}
}
pub fn hint(&self) -> Option<&str> {
match self {
ProviderFailure::Unauthorized(h)
| ProviderFailure::InvalidRequest(h)
| ProviderFailure::Http(h) => h.hint.as_deref(),
ProviderFailure::Routed { cause, .. } => cause.hint(),
_ => None,
}
}
}
fn describe_routed(route: &str, trail: &[Hop], stop: RouteStop, cause: &ProviderFailure) -> String {
let hopped = |trail: &[Hop]| {
trail
.iter()
.map(|h| format!("{}: {}", h.from, h.reason))
.collect::<Vec<_>>()
.join("; ")
};
match stop {
RouteStop::Failed if trail.is_empty() => format!("route `{route}` failed: {cause}"),
RouteStop::Failed => format!(
"route `{route}` failed: {cause} (earlier: {})",
hopped(trail)
),
RouteStop::Exhausted => format!(
"every route failed ({}; {route}: {}); the last said: {cause}",
hopped(trail),
cause.short_reason()
),
RouteStop::AfterText => format!(
"route `{route}` failed after it had started answering: {cause}. The text was \
already shown, so the turn was not replayed on the next route"
),
}
}
pub fn is_retryable_status(status: u16) -> bool {
status == 408 || status == 429 || (500..600).contains(&status)
}
impl From<&str> for ProviderFailure {
fn from(s: &str) -> Self {
ProviderFailure::other(s)
}
}
impl From<String> for ProviderFailure {
fn from(s: String) -> Self {
ProviderFailure::other(s)
}
}
impl From<ProviderFailure> for Error {
fn from(f: ProviderFailure) -> Self {
Error::Provider(f)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn http(status: u16) -> HttpFailure {
HttpFailure {
status,
body: "{\"error\":\"nope\"}".into(),
request_id: Some("req-7".into()),
retry_after_secs: None,
hint: None,
}
}
#[test]
fn the_retry_policy_is_the_servers_transient_trouble_and_nothing_else() {
assert!(is_retryable_status(408));
assert!(is_retryable_status(429));
assert!(is_retryable_status(500));
assert!(is_retryable_status(503));
assert!(is_retryable_status(599));
assert!(!is_retryable_status(400));
assert!(!is_retryable_status(401));
assert!(!is_retryable_status(404));
assert!(!is_retryable_status(422));
assert!(!is_retryable_status(200));
}
#[test]
fn each_variant_answers_the_questions_a_caller_asks() {
let transport = ProviderFailure::Transport {
url: "http://127.0.0.1:9/v1".into(),
message: "connection reset by peer".into(),
sent: true,
};
assert_eq!(transport.kind(), ProviderFailureKind::Transport);
assert_eq!(transport.kind().as_str(), "transport");
assert!(
transport.is_retryable(),
"an unanswered request is safe to repeat"
);
assert_eq!(transport.status(), None);
assert_eq!(transport.body(), None);
let auth = ProviderFailure::Unauthorized(http(401));
assert_eq!(auth.kind(), ProviderFailureKind::Unauthorized);
assert!(
!auth.is_retryable(),
"a wrong key fails the same way every time"
);
assert_eq!(auth.status(), Some(401));
assert_eq!(auth.body(), Some("{\"error\":\"nope\"}"));
assert_eq!(auth.request_id(), Some("req-7"));
let bad = ProviderFailure::InvalidRequest(http(400));
assert!(!bad.is_retryable());
assert_eq!(bad.kind(), ProviderFailureKind::InvalidRequest);
assert!(ProviderFailure::Http(http(503)).is_retryable());
assert!(ProviderFailure::Http(http(429)).is_retryable());
assert!(!ProviderFailure::Http(http(404)).is_retryable());
let cut = ProviderFailure::Truncated {
message: "stream ended".into(),
streamed_chars: 12,
};
assert!(cut.is_retryable());
assert_eq!(cut.kind(), ProviderFailureKind::Truncated);
assert_eq!(cut.status(), None);
let odd = ProviderFailure::other("no choices");
assert!(
!odd.is_retryable(),
"a reply we cannot read will read the same twice"
);
assert_eq!(odd.kind(), ProviderFailureKind::Response);
}
#[test]
fn an_http_failure_displays_the_things_worth_quoting() {
let mut f = http(500);
f.body = "upstream exploded".into();
let rendered = ProviderFailure::Http(f).to_string();
assert!(rendered.contains("HTTP 500"), "{rendered}");
assert!(rendered.contains("upstream exploded"), "{rendered}");
assert!(rendered.contains("req-7"), "{rendered}");
let hinted = ProviderFailure::InvalidRequest(HttpFailure {
status: 400,
body: "unknown field".into(),
request_id: None,
retry_after_secs: None,
hint: Some("provider.top_p is not supported by model m".into()),
})
.to_string();
assert!(hinted.contains("provider.top_p"), "{hinted}");
}
#[test]
fn a_plain_message_still_becomes_a_provider_error() {
let e = Error::provider("script exhausted");
assert_eq!(
e.to_string(),
"provider error: unexpected response: script exhausted"
);
let from_string: Error = Error::Provider("boom".to_string().into());
assert_eq!(
from_string.to_string(),
"provider error: unexpected response: boom"
);
}
}