1use std::collections::HashMap;
4
5use serde_json::Value;
6
7pub type Result<T> = core::result::Result<T, Error>;
9
10#[derive(Debug, thiserror::Error)]
12pub enum Error {
13 #[error("{0}")]
19 Api(#[from] Box<ApiError>),
20
21 #[error("HTTP transport error: {0}")]
23 Http(#[from] reqwest::Error),
24
25 #[error("JSON error: {0}")]
28 Json(#[from] serde_json::Error),
29
30 #[error("I/O error: {0}")]
32 Io(#[from] std::io::Error),
33
34 #[error("validation error: {0}")]
37 Validation(String),
38
39 #[error(
46 "{field} parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode."
47 )]
48 UnsupportedByBackend {
49 field: &'static str,
51 backend: Backend,
53 },
54
55 #[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 #[error("backend `{0}` is not supported by this client yet")]
66 UnsupportedBackend(&'static str),
67
68 #[error("function call error: {0}")]
72 FunctionCall(#[from] FunctionCallError),
73
74 #[cfg(feature = "live")]
76 #[error("WebSocket error: {0}")]
77 WebSocket(#[from] Box<tokio_tungstenite::tungstenite::Error>),
78
79 #[error("stream error: {0}")]
81 Stream(String),
82
83 #[error("upload error: {0}")]
85 Upload(String),
86
87 #[error("no more pages")]
90 NoMorePages,
91
92 #[error("blocking call made from inside an async runtime")]
95 BlockingInsideRuntime,
96}
97
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub enum Backend {
101 GeminiApi,
103 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#[derive(Debug, Clone)]
119pub struct ApiError {
120 pub code: u16,
122 pub status: Option<String>,
124 pub message: String,
126 pub details: Vec<Value>,
128 pub response_headers: HashMap<String, String>,
130}
131
132impl ApiError {
133 #[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 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 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 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 #[must_use]
189 pub fn is_client_error(&self) -> bool {
190 (400..500).contains(&self.code)
191 }
192
193 #[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#[derive(Debug, thiserror::Error)]
213pub enum FunctionCallError {
214 #[error("unsupported function call: `{0}`")]
216 UnsupportedFunction(String),
217
218 #[error("unknown function call argument for `{function}`: {message}")]
220 UnknownArgument {
221 function: String,
223 message: String,
225 },
226
227 #[error("function `{function}` invocation failed: {message}")]
229 Invocation {
230 function: String,
232 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}