Skip to main content

gemini_genai/
errors.rs

1//! Typed errors for `gemini_genai`, mirroring the Python SDK's `errors.py`.
2
3use std::collections::HashMap;
4
5use serde_json::Value;
6
7/// Convenience alias for `Result<T, Error>`.
8pub type Result<T> = core::result::Result<T, Error>;
9
10/// Top-level error type returned by every fallible `gemini_genai` call.
11#[derive(Debug, thiserror::Error)]
12pub enum Error {
13    /// A non-2xx response from the Gemini API. Corresponds to Python's
14    /// `APIError` / `ClientError` / `ServerError`. Boxed: `ApiError` is
15    /// large (a `String` message plus `Vec`/`HashMap` detail fields), and
16    /// `clippy::result_large_err` flags an unboxed variant that size on
17    /// every one of this crate's (numerous) `Result<T, Error>` returns.
18    #[error("{0}")]
19    Api(#[from] Box<ApiError>),
20
21    /// A transport-level failure (connection, TLS, timeout).
22    #[error("HTTP transport error: {0}")]
23    Http(#[from] reqwest::Error),
24
25    /// A JSON (de)serialization failure. Corresponds to Python's
26    /// `UnknownApiResponseError`.
27    #[error("JSON error: {0}")]
28    Json(#[from] serde_json::Error),
29
30    /// A local filesystem I/O failure (e.g. reading a file to upload).
31    #[error("I/O error: {0}")]
32    Io(#[from] std::io::Error),
33
34    /// A request failed client-side validation before being sent.
35    /// Corresponds to Python's `ValueError`.
36    #[error("validation error: {0}")]
37    Validation(String),
38
39    /// A field was set that only the Vertex AI backend supports; this
40    /// client is configured for the Gemini Developer API.
41    /// Corresponds to Python's `ValueError('... only supported in ...')`.
42    ///
43    /// The message reproduces the Python SDK's
44    /// `'<field> parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'`.
45    #[error(
46        "{field} parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
47    )]
48    UnsupportedByBackend {
49        /// The unsupported field's Python name (`snake_case`).
50        field: &'static str,
51        /// The backend the field requires.
52        backend: Backend,
53    },
54
55    /// A whole method that only the Vertex AI backend supports was called on
56    /// a Gemini Developer API client. Corresponds to Python's
57    /// `ValueError('This method is only supported in Gemini Enterprise Agent Platform mode, ...')`.
58    #[error(
59        "`{0}`: this method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
60    )]
61    UnsupportedMethod(&'static str),
62
63    /// The client was configured to use a backend that is not yet
64    /// implemented by this crate.
65    #[error("backend `{0}` is not supported by this client yet")]
66    UnsupportedBackend(&'static str),
67
68    /// An automatic-function-calling failure. Corresponds to Python's
69    /// `UnknownFunctionCallArgumentError` / `UnsupportedFunctionError` /
70    /// `FunctionInvocationError`.
71    #[error("function call error: {0}")]
72    FunctionCall(#[from] FunctionCallError),
73
74    /// A WebSocket (Live API) transport failure.
75    #[cfg(feature = "live")]
76    #[error("WebSocket error: {0}")]
77    WebSocket(#[from] Box<tokio_tungstenite::tungstenite::Error>),
78
79    /// A streamed response (SSE or WebSocket) ended abnormally.
80    #[error("stream error: {0}")]
81    Stream(String),
82
83    /// A resumable file upload failed.
84    #[error("upload error: {0}")]
85    Upload(String),
86
87    /// [`Pager::next_page`](crate::Pager::next_page) was called with no
88    /// further pages available. Corresponds to Python's `IndexError`.
89    #[error("no more pages")]
90    NoMorePages,
91
92    /// A blocking client method was called from within an active Tokio
93    /// runtime, which would deadlock.
94    #[error("blocking call made from inside an async runtime")]
95    BlockingInsideRuntime,
96}
97
98/// The backend a `gemini_genai` [`Client`](crate::Client) talks to.
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub enum Backend {
101    /// The Gemini Developer API (`generativelanguage.googleapis.com`).
102    GeminiApi,
103    /// Vertex AI. Not yet implemented by this crate.
104    VertexAi,
105}
106
107impl std::fmt::Display for Backend {
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        let name = match self {
110            Backend::GeminiApi => "Gemini Developer API",
111            Backend::VertexAi => "Vertex AI",
112        };
113        f.write_str(name)
114    }
115}
116
117/// An error response from the Gemini API, mirroring Python's `APIError`.
118#[derive(Debug, Clone)]
119pub struct ApiError {
120    /// The HTTP status code of the response.
121    pub code: u16,
122    /// The API-reported status string (e.g. `INVALID_ARGUMENT`), if present.
123    pub status: Option<String>,
124    /// A human-readable error message.
125    pub message: String,
126    /// Additional structured error details, if present.
127    pub details: Vec<Value>,
128    /// Response headers, for diagnostics.
129    pub response_headers: HashMap<String, String>,
130}
131
132impl ApiError {
133    /// Builds an [`ApiError`] from an HTTP status code and a (possibly
134    /// non-JSON) response body, following the Gemini API's
135    /// `{"error": {"code", "message", "status", "details"}}` envelope.
136    #[must_use]
137    pub fn from_response(
138        status_code: u16,
139        reason_phrase: &str,
140        response_headers: HashMap<String, String>,
141        body: &[u8],
142    ) -> Self {
143        // Python unwraps a one-element list body (`[{"error": ...}]`).
144        let parsed: Option<Value> =
145            serde_json::from_slice(body)
146                .ok()
147                .map(|value: Value| match value {
148                    Value::Array(mut items) if items.len() == 1 => items.remove(0),
149                    other => other,
150                });
151        let error_obj = parsed.as_ref().and_then(|v| v.get("error"));
152        // Python reads `message`/`status` from the top level first and only
153        // then from the nested `error` object.
154        let field = |key: &str| {
155            parsed
156                .as_ref()
157                .and_then(|v| v.get(key))
158                .or_else(|| error_obj.and_then(|e| e.get(key)))
159                .and_then(Value::as_str)
160        };
161
162        let message = field("message")
163            .map_or_else(|| String::from_utf8_lossy(body).into_owned(), str::to_owned);
164
165        // The HTTP reason phrase only stands in for the status when the body
166        // is not JSON at all (Python: the JSON-decode-error branch); a JSON
167        // body without a `status` has none.
168        let status = field("status")
169            .map(str::to_owned)
170            .or_else(|| parsed.is_none().then(|| reason_phrase.to_owned()));
171
172        let details = error_obj
173            .and_then(|e| e.get("details"))
174            .and_then(Value::as_array)
175            .cloned()
176            .unwrap_or_default();
177
178        Self {
179            code: status_code,
180            status,
181            message,
182            details,
183            response_headers,
184        }
185    }
186
187    /// Whether this is a 4xx client error.
188    #[must_use]
189    pub fn is_client_error(&self) -> bool {
190        (400..500).contains(&self.code)
191    }
192
193    /// Whether this is a 5xx server error.
194    #[must_use]
195    pub fn is_server_error(&self) -> bool {
196        (500..600).contains(&self.code)
197    }
198}
199
200impl std::fmt::Display for ApiError {
201    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202        let status = self.status.as_deref().unwrap_or("UNKNOWN");
203        write!(f, "{} {status}. {}", self.code, self.message)
204    }
205}
206
207impl std::error::Error for ApiError {}
208
209/// Errors raised while resolving or invoking an automatic function-calling
210/// tool. Corresponds to Python's `UnknownFunctionCallArgumentError` /
211/// `UnsupportedFunctionError` / `FunctionInvocationError`.
212#[derive(Debug, thiserror::Error)]
213pub enum FunctionCallError {
214    /// The model requested a function that was not registered as a tool.
215    #[error("unsupported function call: `{0}`")]
216    UnsupportedFunction(String),
217
218    /// The model's function-call arguments did not match the tool's schema.
219    #[error("unknown function call argument for `{function}`: {message}")]
220    UnknownArgument {
221        /// The function name.
222        function: String,
223        /// A description of the mismatch.
224        message: String,
225    },
226
227    /// The tool's callable returned an error while executing.
228    #[error("function `{function}` invocation failed: {message}")]
229    Invocation {
230        /// The function name.
231        function: String,
232        /// The underlying error message.
233        message: String,
234    },
235}
236
237#[cfg(test)]
238mod tests {
239    use super::{ApiError, Backend, Error};
240
241    #[test]
242    fn api_error_display_matches_python_format() {
243        let err = ApiError {
244            code: 400,
245            status: Some("INVALID_ARGUMENT".to_owned()),
246            message: "bad request".to_owned(),
247            details: vec![],
248            response_headers: std::collections::HashMap::new(),
249        };
250        assert_eq!(err.to_string(), "400 INVALID_ARGUMENT. bad request");
251    }
252
253    #[test]
254    fn api_error_from_json_body_extracts_status_and_message() {
255        let body = br#"{"error":{"code":429,"message":"rate limited","status":"RESOURCE_EXHAUSTED","details":[{"reason":"x"}]}}"#;
256        let err = ApiError::from_response(
257            429,
258            "Too Many Requests",
259            std::collections::HashMap::new(),
260            body,
261        );
262        assert_eq!(err.status.as_deref(), Some("RESOURCE_EXHAUSTED"));
263        assert_eq!(err.message, "rate limited");
264        assert_eq!(err.details.len(), 1);
265        assert!(err.is_client_error());
266        assert!(!err.is_server_error());
267    }
268
269    #[test]
270    fn api_error_from_non_json_body_uses_raw_text_and_reason_phrase() {
271        let err = ApiError::from_response(
272            503,
273            "Service Unavailable",
274            std::collections::HashMap::new(),
275            b"upstream down",
276        );
277        assert_eq!(err.status.as_deref(), Some("Service Unavailable"));
278        assert_eq!(err.message, "upstream down");
279        assert!(err.is_server_error());
280    }
281
282    #[test]
283    fn unsupported_by_backend_error_names_field_and_backend() {
284        let err = Error::UnsupportedByBackend {
285            field: "labels",
286            backend: Backend::VertexAi,
287        };
288        assert_eq!(
289            err.to_string(),
290            "labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
291        );
292    }
293}