Skip to main content

gadk_model/
error.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Model errors.
17
18use serde::Deserialize;
19use serde_json::Value;
20
21/// Maximum number of body bytes kept by [`body_prefix`].
22const BODY_PREFIX_LIMIT: usize = 2048;
23
24/// Errors produced by model backends.
25#[derive(Debug, thiserror::Error)]
26#[non_exhaustive]
27pub enum ModelError {
28    /// The API returned an error response.
29    #[error("model API error {code} {status}: {message}")]
30    Api {
31        /// HTTP / API error code.
32        code: u16,
33        /// API status string (e.g. `RESOURCE_EXHAUSTED`); empty if unknown.
34        status: String,
35        /// Error message.
36        message: String,
37        /// Error details as returned by the API.
38        details: Vec<Value>,
39    },
40    /// The request could not be sent or the response could not be read.
41    #[error("transport error: {0}")]
42    Transport(Box<dyn std::error::Error + Send + Sync>),
43    /// The response body could not be decoded.
44    #[error("decode error: {message}")]
45    Decode {
46        /// What went wrong.
47        message: String,
48        /// The start of the offending body (see [`body_prefix`]).
49        body_prefix: String,
50    },
51    /// The model returned no response.
52    #[error("empty response")]
53    EmptyResponse,
54    /// Invalid configuration.
55    #[error("config error: {0}")]
56    Config(String),
57    /// Any other error.
58    #[error("{0}")]
59    Other(Box<dyn std::error::Error + Send + Sync>),
60}
61
62#[derive(Deserialize)]
63struct ErrorEnvelope {
64    error: ErrorBody,
65}
66
67#[derive(Deserialize)]
68struct ErrorBody {
69    #[serde(default)]
70    code: Option<i64>,
71    #[serde(default)]
72    status: String,
73    #[serde(default)]
74    message: String,
75    #[serde(default)]
76    details: Vec<Value>,
77}
78
79/// Builds a [`ModelError::Api`] from an HTTP error status and body.
80///
81/// Parses Google's `{"error":{"code","status","message","details"}}` envelope; when the
82/// body does not parse, `status` is empty and `message` is [`body_prefix`] of the body.
83pub fn api_error_from_body(status: u16, body: &[u8]) -> ModelError {
84    match serde_json::from_slice::<ErrorEnvelope>(body) {
85        Ok(ErrorEnvelope { error }) => ModelError::Api {
86            code: error
87                .code
88                .and_then(|c| u16::try_from(c).ok())
89                .filter(|c| *c != 0)
90                .unwrap_or(status),
91            status: error.status,
92            message: error.message,
93            details: error.details,
94        },
95        Err(_) => ModelError::Api {
96            code: status,
97            status: String::new(),
98            message: body_prefix(body),
99            details: Vec::new(),
100        },
101    }
102}
103
104/// The first ≤ 2048 bytes of `body` as lossy UTF-8, never cutting a multi-byte character.
105pub fn body_prefix(body: &[u8]) -> String {
106    let mut end = body.len().min(BODY_PREFIX_LIMIT);
107    if end < body.len() {
108        // Back off over UTF-8 continuation bytes (at most 3) so the cut lands on a
109        // character boundary.
110        let mut backed = 0;
111        while end > 0 && backed < 3 && body.get(end).is_some_and(|b| b & 0xC0 == 0x80) {
112            end -= 1;
113            backed += 1;
114        }
115    }
116    String::from_utf8_lossy(body.get(..end).unwrap_or_default()).into_owned()
117}