Skip to main content

systemprompt_ai/
error.rs

1//! Typed error hierarchy for the [`systemprompt-ai`](crate) crate.
2//!
3//! Two error families live here:
4//!
5//! - [`AiError`] — the top-level public error returned by [`crate::services`].
6//!   It composes provider-level failures ([`LlmProviderError`]) and
7//!   repository-level failures ([`RepositoryError`]) via `#[from]`, plus common
8//!   transport / parsing errors ([`reqwest::Error`], [`serde_json::Error`],
9//!   [`sqlx::Error`]).
10//! - [`RepositoryError`] — the persistence-layer error returned by every
11//!   `*Repository` type in [`crate::repository`].
12//!
13//! All public service signatures use [`Result<T>`] (i.e. `Result<T, AiError>`).
14//! Provider-trait signatures continue to use the boxed
15//! [`systemprompt_models::errors::ProviderResult`] and bridge through
16//! `AiProvider for AiService` in
17//! `crate::services::core::ai_service` (the `provider_impl` submodule).
18//!
19//! Copyright (c) systemprompt.io — Business Source License 1.1.
20//! See <https://systemprompt.io> for licensing details.
21
22use std::time::Duration;
23
24use thiserror::Error;
25use uuid::Uuid;
26
27use systemprompt_database::resilience::Outcome;
28use systemprompt_identifiers::McpServerId;
29use systemprompt_provider_contracts::LlmProviderError;
30
31#[derive(Debug, Error)]
32pub enum AiError {
33    #[error("Model not specified and no default available for provider {provider}")]
34    ModelNotSpecified { provider: String },
35
36    #[error("Request metadata missing required field: {field}")]
37    MissingMetadata { field: String },
38
39    #[error("User context required for billing and audit trails")]
40    MissingUserContext,
41
42    #[error("Provider {provider} returned empty response")]
43    EmptyProviderResponse { provider: String },
44
45    #[error("Tool call schema validation failed: {reason}")]
46    InvalidToolSchema { reason: String },
47
48    #[error("Authentication required for service {service_id}")]
49    AuthenticationRequired { service_id: McpServerId },
50
51    #[error("Structured output validation failed after {retries} attempts: {details}")]
52    StructuredOutputFailed { retries: usize, details: String },
53
54    #[error("Provider {provider} error: {message}")]
55    ProviderError { provider: String, message: String },
56
57    #[error("No configured provider supports model {model}")]
58    NoProviderForModel { model: String },
59
60    #[error(transparent)]
61    Provider(#[from] LlmProviderError),
62
63    #[error("Serialization failed: {0}")]
64    SerializationError(#[from] serde_json::Error),
65
66    #[error("HTTP request failed: {0}")]
67    Http(#[from] reqwest::Error),
68
69    #[error("I/O error: {0}")]
70    Io(#[from] std::io::Error),
71
72    #[error("Message history cannot be serialized to JSON")]
73    MessageSerializationFailed,
74
75    #[error("Tool {tool_name} missing required field: {field}")]
76    MissingToolField { tool_name: String, field: String },
77
78    #[error("Tool description cannot be empty for tool: {tool_name}")]
79    EmptyToolDescription { tool_name: String },
80
81    #[error("No tool calls found in provider response")]
82    NoToolCalls,
83
84    #[error("Rate limit exceeded for provider {provider}: {details}")]
85    RateLimit { provider: String, details: String },
86
87    #[error("Provider {provider} returned HTTP {status}: {body}")]
88    HttpStatus {
89        provider: String,
90        status: u16,
91        retry_after: Option<Duration>,
92        body: String,
93    },
94
95    #[error("Provider {provider} request timed out after {after_ms}ms")]
96    Timeout { provider: String, after_ms: u64 },
97
98    #[error("Circuit breaker open for provider {provider}; failing fast")]
99    CircuitOpen { provider: String },
100
101    #[error("Provider {provider} unavailable: concurrency limit reached")]
102    DependencyUnavailable { provider: String },
103
104    #[error("Invalid API credentials for provider {provider}")]
105    AuthenticationFailed { provider: String },
106
107    #[error("Configuration error: {message}")]
108    ConfigurationError { message: String },
109
110    #[error("Database operation failed: {message}")]
111    DatabaseError { message: String },
112
113    #[error("MCP service {service_id} not found or not configured")]
114    McpServiceNotFound { service_id: McpServerId },
115
116    #[error("MCP service {service_id} requires OAuth authentication but no token available")]
117    McpAuthenticationMissing { service_id: McpServerId },
118
119    #[error("Failed to determine service authentication requirements: {details}")]
120    ServiceAuthCheckFailed { details: String },
121
122    #[error("Storage operation failed: {message}")]
123    StorageError { message: String },
124
125    #[error("Invalid input: {0}")]
126    InvalidInput(String),
127
128    #[error("Regex error: {0}")]
129    Regex(#[from] regex::Error),
130
131    #[error(transparent)]
132    ToolProvider(#[from] systemprompt_traits::ToolProviderError),
133
134    #[error(transparent)]
135    Secrets(#[from] systemprompt_config::SecretsBootstrapError),
136
137    #[error("internal: {0}")]
138    Internal(String),
139}
140
141#[derive(Debug, Error)]
142pub enum RepositoryError {
143    #[error("AI request not found: {0}")]
144    NotFound(Uuid),
145
146    #[error("Database error: {0}")]
147    Database(#[from] sqlx::Error),
148
149    #[error("Invalid data: {field} - {reason}")]
150    InvalidData { field: String, reason: String },
151
152    #[error("Database pool initialization failed: {0}")]
153    PoolInitialization(String),
154}
155
156impl AiError {
157    pub async fn from_error_response(provider: &str, response: reqwest::Response) -> Self {
158        let status = response.status().as_u16();
159        let retry_after = parse_retry_after(response.headers());
160        let body = response.text().await.unwrap_or_default();
161        Self::HttpStatus {
162            provider: provider.to_owned(),
163            status,
164            retry_after,
165            body,
166        }
167    }
168
169    #[must_use]
170    pub fn classify(&self) -> Outcome {
171        match self {
172            Self::HttpStatus {
173                status,
174                retry_after,
175                ..
176            } => {
177                if matches!(*status, 408 | 425 | 429 | 500 | 502 | 503 | 504) {
178                    Outcome::Transient {
179                        retry_after: *retry_after,
180                    }
181                } else {
182                    Outcome::Permanent
183                }
184            },
185            Self::RateLimit { .. } | Self::Timeout { .. } => {
186                Outcome::Transient { retry_after: None }
187            },
188            Self::Http(err) if err.is_timeout() || err.is_connect() => {
189                Outcome::Transient { retry_after: None }
190            },
191            _ => Outcome::Permanent,
192        }
193    }
194}
195
196fn parse_retry_after(headers: &reqwest::header::HeaderMap) -> Option<Duration> {
197    headers
198        .get(reqwest::header::RETRY_AFTER)?
199        .to_str()
200        .ok()?
201        .trim()
202        .parse::<u64>()
203        .ok()
204        .map(Duration::from_secs)
205}
206
207pub type Result<T> = std::result::Result<T, AiError>;
208
209impl From<RepositoryError> for AiError {
210    fn from(error: RepositoryError) -> Self {
211        Self::DatabaseError {
212            message: error.to_string(),
213        }
214    }
215}