Skip to main content

fm_rs/
error.rs

1//! Error types for `FoundationModels` operations.
2
3use std::ffi::NulError;
4use std::fmt;
5use std::sync::PoisonError as StdPoisonError;
6
7/// Result type for `FoundationModels` operations.
8pub type Result<T> = std::result::Result<T, Error>;
9
10/// Error types for `FoundationModels` operations.
11#[non_exhaustive]
12#[derive(Debug)]
13pub enum Error {
14    /// Model is not available on this device.
15    ModelNotAvailable,
16
17    /// Device is not eligible for Apple Intelligence.
18    DeviceNotEligible,
19
20    /// Apple Intelligence is not enabled in system settings.
21    AppleIntelligenceNotEnabled,
22
23    /// Model is not ready (downloading or other system reasons).
24    ModelNotReady,
25
26    /// Private Cloud Compute isn't ready to serve requests.
27    PrivateCloudComputeSystemNotReady,
28
29    /// Invalid input provided (e.g., string contains null bytes).
30    InvalidInput(String),
31
32    /// Error during generation.
33    GenerationError(String),
34
35    /// The operation was cancelled (e.g. via [`crate::CancellationHandle`]).
36    Cancelled(String),
37
38    /// Operation timed out.
39    Timeout(String),
40
41    /// The requested API requires a newer Apple platform or SDK.
42    UnsupportedPlatform(String),
43
44    /// A Private Cloud Compute request failed due to a network error.
45    NetworkFailure(String),
46
47    /// The user's Private Cloud Compute quota is exhausted until it resets.
48    QuotaLimitReached(String),
49
50    /// Private Cloud Compute is temporarily unable to serve requests.
51    ServiceUnavailable(String),
52
53    /// The request exceeded the model's context window.
54    ContextSizeExceeded(String),
55
56    /// The request was rate limited; retry later.
57    RateLimited(String),
58
59    /// The request or response was blocked by a safety guardrail.
60    GuardrailViolation(String),
61
62    /// The model declined to answer the request.
63    Refusal(String),
64
65    /// The request uses a capability this model does not support.
66    UnsupportedCapability(String),
67
68    /// The transcript contains content this model cannot process.
69    UnsupportedTranscriptContent(String),
70
71    /// The generation guide or schema is not supported by this model.
72    UnsupportedGenerationGuide(String),
73
74    /// The request language or locale is not supported by this model.
75    UnsupportedLanguageOrLocale(String),
76
77    /// The on-device model assets are unavailable (e.g. not yet downloaded).
78    AssetsUnavailable(String),
79
80    /// The session is already responding to another request.
81    ConcurrentRequests(String),
82
83    /// Error during tool invocation.
84    ToolCall(ToolCallError),
85
86    /// Internal error in the FFI layer.
87    InternalError(String),
88
89    /// A lock was poisoned.
90    PoisonError,
91
92    /// JSON serialization/deserialization error.
93    Json(String),
94}
95
96/// Error that occurred during tool invocation.
97#[derive(Debug, Clone)]
98pub struct ToolCallError {
99    /// Name of the tool that failed.
100    pub tool_name: String,
101    /// Arguments passed to the tool.
102    pub arguments: serde_json::Value,
103    /// Description of the error.
104    pub inner_error: String,
105}
106
107impl fmt::Display for Error {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        match self {
110            Error::ModelNotAvailable => {
111                write!(f, "FoundationModels is not available on this device")
112            }
113            Error::DeviceNotEligible => write!(f, "Device is not eligible for Apple Intelligence"),
114            Error::AppleIntelligenceNotEnabled => {
115                write!(f, "Apple Intelligence is not enabled in system settings")
116            }
117            Error::ModelNotReady => {
118                write!(
119                    f,
120                    "Model is not ready (downloading or other system reasons)"
121                )
122            }
123            Error::PrivateCloudComputeSystemNotReady => {
124                write!(f, "Private Cloud Compute is not ready to serve requests")
125            }
126            Error::InvalidInput(msg) => write!(f, "Invalid input: {msg}"),
127            Error::GenerationError(msg) => write!(f, "Generation error: {msg}"),
128            Error::Cancelled(msg) => write!(f, "Operation cancelled: {msg}"),
129            Error::Timeout(msg) => write!(f, "Operation timed out: {msg}"),
130            Error::UnsupportedPlatform(msg) => write!(f, "Unsupported platform: {msg}"),
131            Error::NetworkFailure(msg) => write!(f, "Network failure: {msg}"),
132            Error::QuotaLimitReached(msg) => write!(f, "Quota limit reached: {msg}"),
133            Error::ServiceUnavailable(msg) => write!(f, "Service unavailable: {msg}"),
134            Error::ContextSizeExceeded(msg) => write!(f, "Context size exceeded: {msg}"),
135            Error::RateLimited(msg) => write!(f, "Rate limited: {msg}"),
136            Error::GuardrailViolation(msg) => write!(f, "Guardrail violation: {msg}"),
137            Error::Refusal(msg) => write!(f, "Model refused the request: {msg}"),
138            Error::UnsupportedCapability(msg) => write!(f, "Unsupported capability: {msg}"),
139            Error::UnsupportedTranscriptContent(msg) => {
140                write!(f, "Unsupported transcript content: {msg}")
141            }
142            Error::UnsupportedGenerationGuide(msg) => {
143                write!(f, "Unsupported generation guide: {msg}")
144            }
145            Error::UnsupportedLanguageOrLocale(msg) => {
146                write!(f, "Unsupported language or locale: {msg}")
147            }
148            Error::AssetsUnavailable(msg) => write!(f, "Model assets unavailable: {msg}"),
149            Error::ConcurrentRequests(msg) => {
150                write!(f, "Session is already responding: {msg}")
151            }
152            Error::ToolCall(err) => {
153                write!(f, "Tool '{}' failed: {}", err.tool_name, err.inner_error)
154            }
155            Error::InternalError(msg) => write!(f, "Internal error: {msg}"),
156            Error::PoisonError => write!(f, "A lock was poisoned"),
157            Error::Json(msg) => write!(f, "JSON error: {msg}"),
158        }
159    }
160}
161
162impl std::error::Error for Error {
163    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
164        None
165    }
166}
167
168impl From<NulError> for Error {
169    fn from(_: NulError) -> Self {
170        Error::InvalidInput("String contains null byte".to_string())
171    }
172}
173
174impl<T> From<StdPoisonError<T>> for Error {
175    fn from(_: StdPoisonError<T>) -> Self {
176        Error::PoisonError
177    }
178}
179
180impl From<serde_json::Error> for Error {
181    fn from(err: serde_json::Error) -> Self {
182        Error::Json(err.to_string())
183    }
184}
185
186impl fmt::Display for ToolCallError {
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        write!(
189            f,
190            "Tool '{}' failed with arguments {}: {}",
191            self.tool_name, self.arguments, self.inner_error
192        )
193    }
194}
195
196impl std::error::Error for ToolCallError {}
197
198#[cfg(test)]
199mod tests {
200    use crate::error::Error;
201
202    #[test]
203    fn unsupported_platform_preserves_requirement() {
204        let error = Error::UnsupportedPlatform("requires macOS 27.0".to_string());
205        assert_eq!(
206            error.to_string(),
207            "Unsupported platform: requires macOS 27.0"
208        );
209    }
210
211    #[test]
212    fn pcc_errors_preserve_details() {
213        let error = Error::NetworkFailure("connection lost".to_string());
214        assert_eq!(error.to_string(), "Network failure: connection lost");
215
216        let error = Error::QuotaLimitReached("resets 2026-07-21".to_string());
217        assert_eq!(error.to_string(), "Quota limit reached: resets 2026-07-21");
218
219        let error = Error::ServiceUnavailable("try again later".to_string());
220        assert_eq!(error.to_string(), "Service unavailable: try again later");
221    }
222}