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(transparent)]
58    Provider(#[from] LlmProviderError),
59
60    #[error("Serialization failed: {0}")]
61    SerializationError(#[from] serde_json::Error),
62
63    #[error("HTTP request failed: {0}")]
64    Http(#[from] reqwest::Error),
65
66    #[error("I/O error: {0}")]
67    Io(#[from] std::io::Error),
68
69    #[error("Message history cannot be serialized to JSON")]
70    MessageSerializationFailed,
71
72    #[error("Tool {tool_name} missing required field: {field}")]
73    MissingToolField { tool_name: String, field: String },
74
75    #[error("Tool description cannot be empty for tool: {tool_name}")]
76    EmptyToolDescription { tool_name: String },
77
78    #[error("No tool calls found in provider response")]
79    NoToolCalls,
80
81    #[error("Rate limit exceeded for provider {provider}: {details}")]
82    RateLimit { provider: String, details: String },
83
84    #[error("Provider {provider} returned HTTP {status}: {body}")]
85    HttpStatus {
86        provider: String,
87        status: u16,
88        retry_after: Option<Duration>,
89        body: String,
90    },
91
92    #[error("Provider {provider} request timed out after {after_ms}ms")]
93    Timeout { provider: String, after_ms: u64 },
94
95    #[error("Circuit breaker open for provider {provider}; failing fast")]
96    CircuitOpen { provider: String },
97
98    #[error("Provider {provider} unavailable: concurrency limit reached")]
99    DependencyUnavailable { provider: String },
100
101    #[error("Invalid API credentials for provider {provider}")]
102    AuthenticationFailed { provider: String },
103
104    #[error("Configuration error: {message}")]
105    ConfigurationError { message: String },
106
107    #[error("Database operation failed: {message}")]
108    DatabaseError { message: String },
109
110    #[error("MCP service {service_id} not found or not configured")]
111    McpServiceNotFound { service_id: McpServerId },
112
113    #[error("MCP service {service_id} requires OAuth authentication but no token available")]
114    McpAuthenticationMissing { service_id: McpServerId },
115
116    #[error("Failed to determine service authentication requirements: {details}")]
117    ServiceAuthCheckFailed { details: String },
118
119    #[error("Storage operation failed: {message}")]
120    StorageError { message: String },
121
122    #[error("Invalid input: {0}")]
123    InvalidInput(String),
124
125    #[error("Regex error: {0}")]
126    Regex(#[from] regex::Error),
127
128    #[error(transparent)]
129    ToolProvider(#[from] systemprompt_traits::ToolProviderError),
130
131    #[error(transparent)]
132    Secrets(#[from] systemprompt_config::SecretsBootstrapError),
133
134    #[error("internal: {0}")]
135    Internal(String),
136}
137
138#[derive(Debug, Error)]
139pub enum RepositoryError {
140    #[error("AI request not found: {0}")]
141    NotFound(Uuid),
142
143    #[error("Database error: {0}")]
144    Database(#[from] sqlx::Error),
145
146    #[error("Invalid data: {field} - {reason}")]
147    InvalidData { field: String, reason: String },
148
149    #[error("Database pool initialization failed: {0}")]
150    PoolInitialization(String),
151}
152
153impl AiError {
154    pub async fn from_error_response(provider: &str, response: reqwest::Response) -> Self {
155        let status = response.status().as_u16();
156        let retry_after = parse_retry_after(response.headers());
157        let body = response.text().await.unwrap_or_default();
158        Self::HttpStatus {
159            provider: provider.to_owned(),
160            status,
161            retry_after,
162            body,
163        }
164    }
165
166    #[must_use]
167    pub fn classify(&self) -> Outcome {
168        match self {
169            Self::HttpStatus {
170                status,
171                retry_after,
172                ..
173            } => {
174                if matches!(*status, 408 | 425 | 429 | 500 | 502 | 503 | 504) {
175                    Outcome::Transient {
176                        retry_after: *retry_after,
177                    }
178                } else {
179                    Outcome::Permanent
180                }
181            },
182            Self::RateLimit { .. } | Self::Timeout { .. } => {
183                Outcome::Transient { retry_after: None }
184            },
185            Self::Http(err) if err.is_timeout() || err.is_connect() => {
186                Outcome::Transient { retry_after: None }
187            },
188            _ => Outcome::Permanent,
189        }
190    }
191}
192
193fn parse_retry_after(headers: &reqwest::header::HeaderMap) -> Option<Duration> {
194    headers
195        .get(reqwest::header::RETRY_AFTER)?
196        .to_str()
197        .ok()?
198        .trim()
199        .parse::<u64>()
200        .ok()
201        .map(Duration::from_secs)
202}
203
204pub type Result<T> = std::result::Result<T, AiError>;
205
206impl From<RepositoryError> for AiError {
207    fn from(error: RepositoryError) -> Self {
208        Self::DatabaseError {
209            message: error.to_string(),
210        }
211    }
212}