use async_trait::async_trait;
use thiserror::Error;
use crate::{DecisionRequest, DecisionResponse, ModelId, Request, Response};
pub type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum LlmClientError {
#[error("invalid request: {message}")]
InvalidRequest {
message: String,
},
#[error("request translation failed: {0}")]
RequestTranslation(String),
#[error("outbound request encoding failed: {0}")]
RequestEncoding(String),
#[error("response translation failed: {0}")]
ResponseTranslation(String),
#[error("client configuration error: {message}")]
Configuration {
message: String,
},
#[error(
"Responses state tracking reached its limit of {limit} IDs; no existing records were removed"
)]
ResponseStateLimitExceeded {
limit: usize,
},
#[error("Responses state ID is already recorded for another model; its owner was not changed")]
ResponseStateConflict,
#[error("backend temporarily unavailable")]
TemporarilyUnavailable,
#[error("upstream transport error: {source}")]
Transport {
#[source]
source: BoxError,
},
#[error("upstream request timed out: {source}")]
Timeout {
#[source]
source: BoxError,
},
#[error("context window exceeded for model {model}: {message}")]
ContextWindowExceeded {
model: ModelId,
message: String,
},
#[error("upstream returned HTTP {status}: {body}")]
UpstreamHttp {
status: http::StatusCode,
body: String,
headers: Box<http::HeaderMap>,
},
#[error("invalid upstream response: {source}")]
InvalidResponse {
#[source]
source: BoxError,
},
#[error("host client error: {source}")]
Host {
#[source]
source: BoxError,
},
#[error("foreign function interface error: {source}")]
Ffi {
#[source]
source: BoxError,
},
#[error("{0}")]
General(String),
}
impl LlmClientError {
pub fn is_attachment_rejection(&self) -> bool {
let Self::UpstreamHttp { status, body, .. } = self else {
return false;
};
if !matches!(status.as_u16(), 400 | 422 | 500) {
return false;
}
let parsed = serde_json::from_str::<serde_json::Value>(body).ok();
let error = parsed.as_ref().and_then(|value| value.get("error"));
if error
.and_then(|error| error.get("code"))
.and_then(|code| code.as_str())
== Some("content_policy_violation")
{
return false;
}
let message = error
.and_then(|error| error.get("message"))
.and_then(|message| message.as_str())
.unwrap_or(body)
.to_ascii_lowercase();
[
"unsupported content[].type",
"image input is not supported",
"does not support image input",
"failed to load image or audio file",
"cannot make get request",
"failed to download file",
"invalid image",
"does not represent a valid image",
"unsupported image format",
"unsupported file format",
]
.iter()
.any(|pattern| message.contains(pattern))
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RoutingFallbackReason {
ContextWindow,
Unavailable,
}
impl RoutingFallbackReason {
pub const fn as_str(self) -> &'static str {
match self {
Self::ContextWindow => "context_window",
Self::Unavailable => "unavailable",
}
}
}
#[async_trait]
pub trait RoutedLlmClient: Send + Sync {
fn provider_model<'a>(&'a self, target: &'a ModelId) -> &'a ModelId {
target
}
async fn call(&self, request: Request) -> Result<Response, LlmClientError>;
}
#[async_trait]
pub trait RoutedDecisionClient: Send + Sync {
async fn call(&self, request: DecisionRequest) -> Result<DecisionResponse, LlmClientError>;
}