adk-anthropic 0.6.0

Dedicated Anthropic API client for ADK-Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! Error types for the adk-anthropic client.
//!
//! This module defines a comprehensive error type system for handling
//! all possible errors that can occur when interacting with the Anthropic API.

use std::error;
use std::fmt;
use std::io;
use std::str::Utf8Error;
use std::sync::Arc;

/// The main error type for the adk-anthropic client.
#[derive(Clone, Debug)]
pub enum Error {
    /// A generic API error occurred.
    Api {
        /// HTTP status code.
        status_code: u16,
        /// Error type string from the API.
        error_type: Option<String>,
        /// Human-readable error message.
        message: String,
        /// Request ID for debugging and support.
        request_id: Option<String>,
    },

    /// Authentication error.
    Authentication {
        /// Human-readable error message.
        message: String,
    },

    /// Authorization/Permission error.
    Permission {
        /// Human-readable error message.
        message: String,
    },

    /// Resource not found.
    NotFound {
        /// Human-readable error message.
        message: String,
        /// Resource type.
        resource_type: Option<String>,
        /// Resource ID.
        resource_id: Option<String>,
    },

    /// Rate limit exceeded.
    RateLimit {
        /// Human-readable error message.
        message: String,
        /// Time to wait before retrying, in seconds.
        retry_after: Option<u64>,
    },

    /// Bad request due to invalid parameters.
    BadRequest {
        /// Human-readable error message.
        message: String,
        /// Parameter that caused the error.
        param: Option<String>,
    },

    /// API timeout error.
    Timeout {
        /// Human-readable error message.
        message: String,
        /// Duration of the timeout in seconds.
        duration: Option<f64>,
    },

    /// Request was aborted by the client.
    Abort {
        /// Human-readable error message.
        message: String,
    },

    /// Connection error.
    Connection {
        /// Human-readable error message.
        message: String,
        /// Underlying cause.
        source: Option<Arc<dyn error::Error + Send + Sync>>,
    },

    /// Server returned a 500 internal error.
    InternalServer {
        /// Human-readable error message.
        message: String,
        /// Request ID for debugging and support.
        request_id: Option<String>,
    },

    /// Server is overloaded or unavailable.
    ServiceUnavailable {
        /// Human-readable error message.
        message: String,
        /// Time to wait before retrying, in seconds.
        retry_after: Option<u64>,
    },

    /// Error during JSON serialization or deserialization.
    Serialization {
        /// Human-readable error message.
        message: String,
        /// The underlying error.
        source: Option<Arc<dyn error::Error + Send + Sync>>,
    },

    /// I/O error.
    Io {
        /// Human-readable error message.
        message: String,
        /// The underlying error.
        source: Arc<io::Error>,
    },

    /// HTTP client error.
    HttpClient {
        /// Human-readable error message.
        message: String,
        /// The underlying error.
        source: Option<Arc<dyn error::Error + Send + Sync>>,
    },

    /// Error during validation of request parameters.
    Validation {
        /// Human-readable error message.
        message: String,
        /// Parameter that failed validation.
        param: Option<String>,
    },

    /// A URL parsing or manipulation error.
    Url {
        /// Human-readable error message.
        message: String,
        /// The underlying error.
        source: Option<url::ParseError>,
    },

    /// A streaming error occurred.
    Streaming {
        /// Human-readable error message.
        message: String,
        /// The underlying error.
        source: Option<Arc<dyn error::Error + Send + Sync>>,
    },

    /// Encoding/decoding error.
    Encoding {
        /// Human-readable error message.
        message: String,
        /// The underlying error.
        source: Option<Arc<dyn error::Error + Send + Sync>>,
    },

    /// Unknown error.
    Unknown {
        /// Human-readable error message.
        message: String,
    },

    /// Unimplemented functionality.
    ToDo {
        /// Human-readable error message.
        message: String,
    },
}

impl Error {
    /// Creates a new API error.
    pub fn api(
        status_code: u16,
        error_type: Option<String>,
        message: String,
        request_id: Option<String>,
    ) -> Self {
        Error::Api { status_code, error_type, message, request_id }
    }

    /// Creates a new authentication error.
    pub fn authentication(message: impl Into<String>) -> Self {
        Error::Authentication { message: message.into() }
    }

    /// Creates a new permission error.
    pub fn permission(message: impl Into<String>) -> Self {
        Error::Permission { message: message.into() }
    }

    /// Creates a new not found error.
    pub fn not_found(
        message: impl Into<String>,
        resource_type: Option<String>,
        resource_id: Option<String>,
    ) -> Self {
        Error::NotFound { message: message.into(), resource_type, resource_id }
    }

    /// Creates a new rate limit error.
    pub fn rate_limit(message: impl Into<String>, retry_after: Option<u64>) -> Self {
        Error::RateLimit { message: message.into(), retry_after }
    }

    /// Creates a new bad request error.
    pub fn bad_request(message: impl Into<String>, param: Option<String>) -> Self {
        Error::BadRequest { message: message.into(), param }
    }

    /// Creates a new timeout error.
    pub fn timeout(message: impl Into<String>, duration: Option<f64>) -> Self {
        Error::Timeout { message: message.into(), duration }
    }

    /// Creates a new abort error.
    pub fn abort(message: impl Into<String>) -> Self {
        Error::Abort { message: message.into() }
    }

    /// Creates a new connection error.
    pub fn connection(
        message: impl Into<String>,
        source: Option<Box<dyn error::Error + Send + Sync>>,
    ) -> Self {
        Error::Connection { message: message.into(), source: source.map(Arc::from) }
    }

    /// Creates a new internal server error.
    pub fn internal_server(message: impl Into<String>, request_id: Option<String>) -> Self {
        Error::InternalServer { message: message.into(), request_id }
    }

    /// Creates a new service unavailable error.
    pub fn service_unavailable(message: impl Into<String>, retry_after: Option<u64>) -> Self {
        Error::ServiceUnavailable { message: message.into(), retry_after }
    }

    /// Creates a new serialization error.
    pub fn serialization(
        message: impl Into<String>,
        source: Option<Box<dyn error::Error + Send + Sync>>,
    ) -> Self {
        Error::Serialization { message: message.into(), source: source.map(Arc::from) }
    }

    /// Creates a new I/O error.
    pub fn io(message: impl Into<String>, source: io::Error) -> Self {
        Error::Io { message: message.into(), source: Arc::new(source) }
    }

    /// Creates a new HTTP client error.
    pub fn http_client(
        message: impl Into<String>,
        source: Option<Box<dyn error::Error + Send + Sync>>,
    ) -> Self {
        Error::HttpClient { message: message.into(), source: source.map(Arc::from) }
    }

    /// Creates a new validation error.
    pub fn validation(message: impl Into<String>, param: Option<String>) -> Self {
        Error::Validation { message: message.into(), param }
    }

    /// Creates a new URL error.
    pub fn url(message: impl Into<String>, source: Option<url::ParseError>) -> Self {
        Error::Url { message: message.into(), source }
    }

    /// Creates a new streaming error.
    pub fn streaming(
        message: impl Into<String>,
        source: Option<Box<dyn error::Error + Send + Sync>>,
    ) -> Self {
        Error::Streaming { message: message.into(), source: source.map(Arc::from) }
    }

    /// Creates a new encoding error.
    pub fn encoding(
        message: impl Into<String>,
        source: Option<Box<dyn error::Error + Send + Sync>>,
    ) -> Self {
        Error::Encoding { message: message.into(), source: source.map(Arc::from) }
    }

    /// Creates a new unknown error.
    pub fn unknown(message: impl Into<String>) -> Self {
        Error::Unknown { message: message.into() }
    }

    /// Creates a new ToDo error for unimplemented functionality.
    pub fn todo(message: impl Into<String>) -> Self {
        Error::ToDo { message: message.into() }
    }

    /// Returns true if this error is related to authentication.
    pub fn is_authentication(&self) -> bool {
        matches!(self, Error::Authentication { .. })
    }

    /// Returns true if this error is related to permissions.
    pub fn is_permission(&self) -> bool {
        matches!(self, Error::Permission { .. })
    }

    /// Returns true if this error is a "not found" error.
    pub fn is_not_found(&self) -> bool {
        matches!(self, Error::NotFound { .. })
    }

    /// Returns true if this error is related to rate limiting.
    pub fn is_rate_limit(&self) -> bool {
        matches!(self, Error::RateLimit { .. })
    }

    /// Returns true if this error is a bad request.
    pub fn is_bad_request(&self) -> bool {
        matches!(self, Error::BadRequest { .. })
    }

    /// Returns true if this error is a timeout.
    pub fn is_timeout(&self) -> bool {
        matches!(self, Error::Timeout { .. })
    }

    /// Returns true if this error is an abort.
    pub fn is_abort(&self) -> bool {
        matches!(self, Error::Abort { .. })
    }

    /// Returns true if this error is a connection error.
    pub fn is_connection(&self) -> bool {
        matches!(self, Error::Connection { .. })
    }

    /// Returns true if this error is a server error.
    pub fn is_server_error(&self) -> bool {
        matches!(self, Error::InternalServer { .. } | Error::ServiceUnavailable { .. })
    }

    /// Returns true if this error is retryable.
    pub fn is_retryable(&self) -> bool {
        match self {
            Error::Api { status_code, .. } => {
                matches!(status_code, 408 | 409 | 429 | 500..=599)
            }
            Error::Timeout { .. } => true,
            Error::Connection { .. } => true,
            Error::RateLimit { .. } => true,
            Error::ServiceUnavailable { .. } => true,
            Error::InternalServer { .. } => true,
            _ => false,
        }
    }

    /// Returns true if this error is a ToDo error.
    pub fn is_todo(&self) -> bool {
        matches!(self, Error::ToDo { .. })
    }

    /// Returns true if this error is a validation error.
    pub fn is_validation(&self) -> bool {
        matches!(self, Error::Validation { .. })
    }

    /// Returns the request ID associated with this error, if any.
    pub fn request_id(&self) -> Option<&str> {
        match self {
            Error::Api { request_id, .. } => request_id.as_deref(),
            Error::InternalServer { request_id, .. } => request_id.as_deref(),
            _ => None,
        }
    }

    /// Returns the status code associated with this error, if any.
    pub fn status_code(&self) -> Option<u16> {
        match self {
            Error::Api { status_code, .. } => Some(*status_code),
            _ => None,
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Api { message, error_type, request_id, .. } => {
                if let Some(error_type) = error_type {
                    if let Some(request_id) = request_id {
                        write!(f, "{error_type}: {message} (Request ID: {request_id})")
                    } else {
                        write!(f, "{error_type}: {message}")
                    }
                } else if let Some(request_id) = request_id {
                    write!(f, "API error: {message} (Request ID: {request_id})")
                } else {
                    write!(f, "API error: {message}")
                }
            }
            Error::Authentication { message } => {
                write!(f, "Authentication error: {message}")
            }
            Error::Permission { message } => {
                write!(f, "Permission error: {message}")
            }
            Error::NotFound { message, resource_type, resource_id } => {
                let prefix = if let Some(resource_type) = resource_type {
                    format!("Resource not found ({resource_type})")
                } else {
                    "Resource not found".to_string()
                };

                let suffix = if let Some(resource_id) = resource_id {
                    format!(" [ID: {resource_id}]")
                } else {
                    "".to_string()
                };

                write!(f, "{prefix}: {message}{suffix}")
            }
            Error::RateLimit { message, retry_after } => {
                if let Some(retry_after) = retry_after {
                    write!(f, "Rate limit exceeded: {message} (retry after {retry_after} seconds)")
                } else {
                    write!(f, "Rate limit exceeded: {message}")
                }
            }
            Error::BadRequest { message, param } => {
                if let Some(param) = param {
                    write!(f, "Bad request: {message} (parameter: {param})")
                } else {
                    write!(f, "Bad request: {message}")
                }
            }
            Error::Timeout { message, duration } => {
                if let Some(duration) = duration {
                    write!(f, "Timeout error: {message} ({duration} seconds)")
                } else {
                    write!(f, "Timeout error: {message}")
                }
            }
            Error::Abort { message } => {
                write!(f, "Request aborted: {message}")
            }
            Error::Connection { message, .. } => {
                write!(f, "Connection error: {message}")
            }
            Error::InternalServer { message, request_id } => {
                if let Some(request_id) = request_id {
                    write!(f, "Internal server error: {message} (Request ID: {request_id})")
                } else {
                    write!(f, "Internal server error: {message}")
                }
            }
            Error::ServiceUnavailable { message, retry_after } => {
                if let Some(retry_after) = retry_after {
                    write!(f, "Service unavailable: {message} (retry after {retry_after} seconds)")
                } else {
                    write!(f, "Service unavailable: {message}")
                }
            }
            Error::Serialization { message, .. } => {
                write!(f, "Serialization error: {message}")
            }
            Error::Io { message, .. } => {
                write!(f, "I/O error: {message}")
            }
            Error::HttpClient { message, .. } => {
                write!(f, "HTTP client error: {message}")
            }
            Error::Validation { message, param } => {
                if let Some(param) = param {
                    write!(f, "Validation error: {message} (parameter: {param})")
                } else {
                    write!(f, "Validation error: {message}")
                }
            }
            Error::Url { message, .. } => {
                write!(f, "URL error: {message}")
            }
            Error::Streaming { message, .. } => {
                write!(f, "Streaming error: {message}")
            }
            Error::Encoding { message, .. } => {
                write!(f, "Encoding error: {message}")
            }
            Error::Unknown { message } => {
                write!(f, "Unknown error: {message}")
            }
            Error::ToDo { message } => {
                write!(f, "Unimplemented: {message}")
            }
        }
    }
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            Error::Connection { source, .. } => {
                source.as_ref().map(|e| e.as_ref() as &(dyn error::Error + 'static))
            }
            Error::Serialization { source, .. } => {
                source.as_ref().map(|e| e.as_ref() as &(dyn error::Error + 'static))
            }
            Error::Io { source, .. } => Some(source),
            Error::HttpClient { source, .. } => {
                source.as_ref().map(|e| e.as_ref() as &(dyn error::Error + 'static))
            }
            Error::Url { source, .. } => {
                source.as_ref().map(|e| e as &(dyn error::Error + 'static))
            }
            Error::Streaming { source, .. } => {
                source.as_ref().map(|e| e.as_ref() as &(dyn error::Error + 'static))
            }
            Error::Encoding { source, .. } => {
                source.as_ref().map(|e| e.as_ref() as &(dyn error::Error + 'static))
            }
            _ => None,
        }
    }
}

impl From<io::Error> for Error {
    fn from(err: io::Error) -> Self {
        Error::io(err.to_string(), err)
    }
}

impl From<serde_json::Error> for Error {
    fn from(err: serde_json::Error) -> Self {
        Error::serialization(format!("JSON error: {err}"), Some(Box::new(err)))
    }
}

impl From<url::ParseError> for Error {
    fn from(err: url::ParseError) -> Self {
        Error::url(format!("URL parse error: {err}"), Some(err))
    }
}

impl From<Utf8Error> for Error {
    fn from(err: Utf8Error) -> Self {
        Error::encoding(format!("UTF-8 error: {err}"), Some(Box::new(err)))
    }
}

/// A specialized Result type for adk-anthropic operations.
pub type Result<T> = std::result::Result<T, Error>;