Skip to main content

gadk_engine/tool/
utils.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//! Typed conversion, schema validation, canonical schema JSON and function-call helpers.
17
18use gadk_agent::go_quote;
19use std::sync::Arc;
20
21use gadk_genai::{Content, FunctionCall, FunctionResponse, Schema};
22use gadk_platform::Platform;
23use schemars::generate::SchemaSettings;
24use schemars::transform::RecursiveTransform;
25use serde_json::{Map, Value};
26
27/// The prefix of client-generated function call ids.
28pub(crate) const AF_FUNCTION_CALL_ID_PREFIX: &str = "adk-";
29
30// ---------------------------------------------------------------------------------------------
31// Typed conversion and validation
32// ---------------------------------------------------------------------------------------------
33
34/// Whether the root of a JSON schema value expects an object:
35/// `"type": "object"` or a `"type"` array containing `"object"`.
36pub(crate) fn schema_expects_object(schema: &Value) -> bool {
37    match schema.get("type") {
38        Some(Value::String(t)) => t == "object",
39        Some(Value::Array(ts)) => ts.iter().any(|t| t == "object"),
40        _ => false,
41    }
42}
43
44/// Serializes `v`, validates the JSON form (a `null` against an object schema becomes `{}`),
45/// then deserializes.
46///
47/// The substituted value is the one deserialized, so a tool called with no arguments yields
48/// `Args` built from `{}` instead of a serde error.
49pub(crate) fn convert_with_schema<In: serde::Serialize, Out: serde::de::DeserializeOwned>(
50    v: &In,
51    schema: Option<&CompiledSchema>,
52) -> Result<Out, String> {
53    let mut decoded = serde_json::to_value(v).map_err(|e| e.to_string())?;
54    if let Some(s) = schema {
55        if decoded.is_null() && schema_expects_object(s.schema()) {
56            decoded = Value::Object(Map::new());
57        }
58        s.validate(&decoded)?;
59    }
60    serde_json::from_value(decoded).map_err(|e| e.to_string())
61}
62
63/// [`convert_with_schema`] for a function tool's call arguments: integral floats are first
64/// written as integers, so a typed decode into an integer field accepts them
65/// ([`go_marshaled_numbers`]).
66pub(crate) fn convert_args_with_schema<Out: serde::de::DeserializeOwned>(
67    args: &Value,
68    schema: Option<&CompiledSchema>,
69) -> Result<Out, String> {
70    convert_with_schema(&go_marshaled_numbers(args.clone()), schema)
71}
72
73/// Integral float numbers become integers: a float with an integral value is written without a
74/// fraction (`1`, not `1.0`), so a typed decode into an integer field accepts it. serde_json
75/// keeps a `1.0` float a float, which an `i64` field rejects; such floats (as streamed partial
76/// arguments carry them) become integers here.
77fn go_marshaled_numbers(v: Value) -> Value {
78    /// Integral floats below 1e21 become integers; from 1e21 on they stay floats.
79    const GO_EXPONENT_FROM: f64 = 1e21;
80    match v {
81        Value::Number(n) if !n.is_i64() && !n.is_u64() => match n.as_f64() {
82            Some(f) if f.fract() == 0.0 && f.abs() < GO_EXPONENT_FROM => {
83                if f >= i64::MIN as f64 && f < i64::MAX as f64 {
84                    #[allow(clippy::cast_possible_truncation)] // integral and in range
85                    Value::from(f as i64)
86                } else if f >= 0.0 && f < u64::MAX as f64 {
87                    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
88                    // integral, in range
89                    Value::from(f as u64)
90                } else {
91                    Value::Number(n)
92                }
93            }
94            _ => Value::Number(n),
95        },
96        Value::Array(items) => Value::Array(items.into_iter().map(go_marshaled_numbers).collect()),
97        Value::Object(m) => Value::Object(
98            m.into_iter()
99                .map(|(k, v)| (k, go_marshaled_numbers(v)))
100                .collect(),
101        ),
102        other => other,
103    }
104}
105
106/// Validates the JSON form of `v` against the schema.
107pub(crate) fn validate_with_schema<In: serde::Serialize>(
108    v: &In,
109    schema: Option<&CompiledSchema>,
110) -> Result<(), String> {
111    let Some(s) = schema else { return Ok(()) };
112    let mut decoded = serde_json::to_value(v).map_err(|e| e.to_string())?;
113    if decoded.is_null() && schema_expects_object(s.schema()) {
114        decoded = Value::Object(Map::new());
115    }
116    s.validate(&decoded)
117}
118
119// ---------------------------------------------------------------------------------------------
120// Schema inference and compilation
121// ---------------------------------------------------------------------------------------------
122
123fn settings() -> SchemaSettings {
124    SchemaSettings::draft2020_12()
125        .with(|s| {
126            s.meta_schema = None; // no "$schema" key
127            s.inline_subschemas = true; // no "$defs"/"$ref" except for recursive types
128        })
129        .with_transform(RecursiveTransform(
130            go_schema_shape as fn(&mut schemars::Schema),
131        ))
132}
133
134/// Shapes one schemars subschema for tool declarations:
135/// - struct schemas forbid unknown keys: an object schema (with `properties`, or a bare
136///   `"type": "object"` from a field-less struct) and no `additionalProperties` gets
137///   `"additionalProperties": false`;
138/// - integer/number schemas carry no `format` (schemars adds `"int64"`, `"double"`, …).
139///
140/// Applied to every subschema via [`RecursiveTransform`].
141fn go_schema_shape(schema: &mut schemars::Schema) {
142    let Some(obj) = schema.as_object_mut() else {
143        return;
144    };
145    let is_numeric = |t: &Value| t == "integer" || t == "number";
146    let numeric = match obj.get("type") {
147        Some(Value::Array(ts)) => ts.iter().any(is_numeric),
148        Some(t) => is_numeric(t),
149        None => false,
150    };
151    if numeric {
152        obj.remove("format");
153    }
154    // A field-less struct is a bare `{"type": "object"}` in schemars; maps always carry
155    // `additionalProperties`, so a bare object schema is a struct too.
156    let is_struct =
157        obj.contains_key("properties") || obj.get("type").is_some_and(|t| t == "object");
158    if is_struct && !obj.contains_key("additionalProperties") {
159        obj.insert("additionalProperties".to_string(), Value::Bool(false));
160    }
161}
162
163/// The JSON schema for `T` as a function tool declares it: draft 2020-12, no `$schema`,
164/// inlined subschemas, and the root `title` (schemars' `T::schema_name()`) removed. Nested
165/// titles that derive from doc comments are kept. Deserialize contract (describes what `T`
166/// accepts).
167pub(crate) fn infer_schema<T: schemars::JsonSchema>() -> Value {
168    let mut schema = settings().into_generator().into_root_schema_for::<T>();
169    schema.remove("title");
170    schema.to_value()
171}
172
173/// Same as [`infer_schema`] with the serialize contract (describes what `T` emits); used for tool outputs.
174pub(crate) fn infer_output_schema<T: schemars::JsonSchema>() -> Value {
175    let mut schema = settings()
176        .for_serialize()
177        .into_generator()
178        .into_root_schema_for::<T>();
179    schema.remove("title");
180    schema.to_value()
181}
182
183/// A schema compiled once, validated many times.
184#[derive(Debug, Clone)]
185pub(crate) struct CompiledSchema {
186    schema: Value,
187    // Arc: Clone is cheap and does not depend on `jsonschema::Validator: Clone`.
188    validator: Arc<jsonschema::Validator>,
189}
190
191impl CompiledSchema {
192    /// Compiles the schema. `$schema` absent ⇒ draft 2020-12 (jsonschema's default).
193    pub(crate) fn new(schema: Value) -> Result<Self, String> {
194        let validator = jsonschema::validator_for(&schema).map_err(|e| e.to_string())?;
195        Ok(Self {
196            schema,
197            validator: Arc::new(validator),
198        })
199    }
200
201    /// The schema this was compiled from.
202    pub(crate) fn schema(&self) -> &Value {
203        &self.schema
204    }
205
206    /// Validates `v`: the first error's text.
207    pub(crate) fn validate(&self, v: &Value) -> Result<(), String> {
208        self.validator.validate(v).map_err(|e| e.to_string())
209    }
210}
211
212// ---------------------------------------------------------------------------------------------
213// Canonical schema JSON
214// ---------------------------------------------------------------------------------------------
215
216/// JSON Schema keywords whose array value is a set.
217const UNORDERED_ARRAY_KEYWORDS: [&str; 2] = ["required", "type"];
218
219/// The schema re-emitted with object keys sorted (recursively) and the
220/// unordered set keywords (`required`, `type`) sorted, so equivalent schemas canonicalize
221/// identically.
222pub(crate) fn canonical_schema_json(schema: &Value) -> String {
223    canonicalize(schema)
224}
225
226/// Serializes `v` with sorted object keys; arrays keep their order unless
227/// they are the value of an unordered set keyword.
228pub(crate) fn canonicalize(v: &Value) -> String {
229    match v {
230        Value::Object(map) => {
231            let mut keys: Vec<&String> = map.keys().collect();
232            keys.sort();
233            let mut out = String::from("{");
234            for (i, k) in keys.into_iter().enumerate() {
235                if i > 0 {
236                    out.push(',');
237                }
238                out.push_str(&encode_string(k));
239                out.push(':');
240                match &map[k] {
241                    Value::Array(items) if UNORDERED_ARRAY_KEYWORDS.contains(&k.as_str()) => {
242                        out.push_str(&canonicalize_unordered_array(items));
243                    }
244                    other => out.push_str(&canonicalize(other)),
245                }
246            }
247            out.push('}');
248            out
249        }
250        Value::Array(items) => {
251            let encoded: Vec<String> = items.iter().map(canonicalize).collect();
252            format!("[{}]", encoded.join(","))
253        }
254        Value::Number(n) => encode_number(n),
255        Value::String(s) => encode_string(s),
256        Value::Bool(b) => b.to_string(),
257        Value::Null => "null".to_string(),
258    }
259}
260
261/// Canonicalized elements sorted by their encoded bytes.
262fn canonicalize_unordered_array(items: &[Value]) -> String {
263    let mut encoded: Vec<String> = items.iter().map(canonicalize).collect();
264    encoded.sort();
265    format!("[{}]", encoded.join(","))
266}
267
268fn encode_string(s: &str) -> String {
269    Value::String(s.to_string()).to_string()
270}
271
272/// Integral values are written without a fraction: `123.0` → `123`.
273fn encode_number(n: &serde_json::Number) -> String {
274    if n.is_i64() || n.is_u64() {
275        return n.to_string();
276    }
277    match n.as_f64() {
278        Some(f) if f.fract() == 0.0 && f.abs() < 1e21 => format!("{f:.0}"),
279        _ => n.to_string(),
280    }
281}
282
283// ---------------------------------------------------------------------------------------------
284// Schema-based argument validation
285// ---------------------------------------------------------------------------------------------
286
287pub(crate) use gadk_platform::json_kind_article;
288
289fn type_str(schema: &Schema) -> &str {
290    schema.r#type.as_ref().map(|t| t.as_str()).unwrap_or("")
291}
292
293/// Whether `value` matches the schema's type. An object error returns `Err`.
294pub(crate) fn match_type(
295    value: &Value,
296    schema: Option<&Schema>,
297    is_input: bool,
298) -> Result<bool, String> {
299    let Some(schema) = schema else {
300        return Err("schema is missing".to_string());
301    };
302    if value.is_null() {
303        return Ok(schema.nullable == Some(true));
304    }
305    // Convert type to upper case to match the type in the schema.
306    match type_str(schema).to_uppercase().as_str() {
307        "STRING" => Ok(value.is_string()),
308        "INTEGER" => Ok(value.as_f64().is_some_and(|f| f == f.trunc())),
309        "BOOLEAN" => Ok(value.is_boolean()),
310        "NUMBER" => Ok(value.is_number()),
311        "ARRAY" => {
312            let Value::Array(items) = value else {
313                return Ok(false);
314            };
315            let Some(item_schema) = schema.items.as_deref() else {
316                return Err("array schema missing items definition".to_string());
317            };
318            for (i, item) in items.iter().enumerate() {
319                match match_type(item, Some(item_schema), is_input) {
320                    Err(e) => return Err(format!("array item {i}: {e}")),
321                    Ok(false) => return Ok(false),
322                    Ok(true) => {}
323                }
324            }
325            Ok(true)
326        }
327        "OBJECT" => {
328            let Value::Object(obj) = value else {
329                return Ok(false);
330            };
331            validate_map_on_schema(obj, schema, is_input).map(|()| true)
332        }
333        _ => Err(format!("unsupported type: {}", type_str(schema))),
334    }
335}
336
337/// Validates `args` against the schema's properties. The schema is a reference, so there is no
338/// nil-schema error.
339pub(crate) fn validate_map_on_schema(
340    args: &Map<String, Value>,
341    schema: &Schema,
342    is_input: bool,
343) -> Result<(), String> {
344    let arg_type = if is_input { "input" } else { "output" };
345    for (key, value) in args {
346        let Some(prop_schema) = schema.properties.get(key) else {
347            // Note: OpenAPI schemas can allow additional properties. This implementation assumes strictness.
348            return Err(format!(
349                "{arg_type} arg: '{}' does not exist in schema properties",
350                go_quote(key)
351            ));
352        };
353        match match_type(value, Some(prop_schema), is_input) {
354            Err(e) => {
355                return Err(format!(
356                    "{arg_type} arg: '{}' validation failed: {e}",
357                    go_quote(key)
358                ));
359            }
360            Ok(false) => {
361                let found = match value {
362                    Value::Null => "null".to_owned(),
363                    other => format!("{} ({other})", json_kind_article(other)),
364                };
365                return Err(format!(
366                    "{arg_type} arg: '{}' type mismatch, expected schema type {}, found {found}",
367                    go_quote(key),
368                    type_str(prop_schema),
369                ));
370            }
371            Ok(true) => {}
372        }
373    }
374    for required_key in &schema.required {
375        if !args.contains_key(required_key) {
376            return Err(format!(
377                "{} args does not contain required key: '{}'",
378                go_quote(arg_type),
379                go_quote(required_key)
380            ));
381        }
382    }
383    Ok(())
384}
385
386/// Parses `output` as JSON and validates it against the schema. The schema is a reference, so
387/// there is no nil-schema error.
388pub(crate) fn validate_output_schema(
389    output: &str,
390    schema: &Schema,
391) -> Result<Map<String, Value>, String> {
392    let parsed: Value =
393        serde_json::from_str(output).map_err(|e| format!("failed to parse output JSON: {e}"))?;
394    let map = match parsed {
395        Value::Object(m) => m,
396        // `null` becomes an empty map.
397        Value::Null => Map::new(),
398        other => {
399            return Err(format!(
400                "failed to parse output JSON: {}",
401                gadk_platform::json_expected_found("a JSON object", &other)
402            ));
403        }
404    };
405    validate_map_on_schema(&map, schema, false)?;
406    Ok(map)
407}
408
409// ---------------------------------------------------------------------------------------------
410// Function call ids, content parts and branches
411// ---------------------------------------------------------------------------------------------
412
413/// Assigns a client id to every function call without one.
414pub(crate) fn populate_client_function_call_id(platform: &Platform, c: Option<&mut Content>) {
415    let Some(c) = c else { return };
416    for fc in c.parts.iter_mut().filter_map(|p| p.function_call.as_mut()) {
417        if fc.id.is_empty() {
418            fc.id = generate_function_call_id(platform);
419        }
420    }
421}
422
423/// A new client-generated function call id.
424pub(crate) fn generate_function_call_id(platform: &Platform) -> String {
425    format!("{AF_FUNCTION_CALL_ID_PREFIX}{}", platform.new_uuid())
426}
427
428/// Clears client-generated ids on function calls and responses.
429pub(crate) fn remove_client_function_call_id(c: &mut Content) {
430    for p in &mut c.parts {
431        if let Some(fc) = p.function_call.as_mut()
432            && fc.id.starts_with(AF_FUNCTION_CALL_ID_PREFIX)
433        {
434            fc.id.clear();
435        }
436        if let Some(fr) = p.function_response.as_mut()
437            && fr.id.starts_with(AF_FUNCTION_CALL_ID_PREFIX)
438        {
439            fr.id.clear();
440        }
441    }
442}
443
444/// Shared with `gadk_session::compaction`.
445pub(crate) use gadk_session::compaction::content;
446
447/// The function calls of `c`, in order (none for `None`).
448pub fn function_calls(c: Option<&Content>) -> Vec<&FunctionCall> {
449    c.map(|c| {
450        c.parts
451            .iter()
452            .filter_map(|p| p.function_call.as_ref())
453            .collect()
454    })
455    .unwrap_or_default()
456}
457
458/// The function responses of `c`, in order.
459pub(crate) fn function_responses(c: Option<&Content>) -> Vec<&FunctionResponse> {
460    c.map(|c| {
461        c.parts
462            .iter()
463            .filter_map(|p| p.function_response.as_ref())
464            .collect()
465    })
466    .unwrap_or_default()
467}
468
469/// The non-empty texts, in part order.
470pub(crate) fn text_parts(c: Option<&Content>) -> Vec<String> {
471    c.map(|c| {
472        c.parts
473            .iter()
474            .filter(|p| !p.text.is_empty())
475            .map(|p| p.text.clone())
476            .collect()
477    })
478    .unwrap_or_default()
479}
480
481/// The content's text parts concatenated without a separator.
482#[allow(dead_code)] // No caller yet.
483pub(crate) fn content_text(c: &Content) -> String {
484    text_parts(Some(c)).concat()
485}
486
487/// The function declarations of the config's tools.
488#[cfg(test)]
489pub(crate) fn function_decls(
490    c: Option<&gadk_genai::GenerateContentConfig>,
491) -> Vec<&gadk_genai::FunctionDeclaration> {
492    c.map(|c| {
493        c.tools
494            .iter()
495            .flat_map(|t| t.function_declarations.iter())
496            .collect()
497    })
498    .unwrap_or_default()
499}
500
501/// An event belongs to its own branch and every descendant of it.
502pub(crate) fn event_belongs_to_branch(invocation_branch: &str, event_branch: &str) -> bool {
503    invocation_branch.is_empty()
504        || event_branch.is_empty()
505        || event_branch == invocation_branch
506        || invocation_branch.starts_with(&format!("{event_branch}."))
507}
508
509/// The text of a recovered panic payload: `&str`/`String` payloads verbatim.
510pub(crate) fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
511    if let Some(s) = payload.downcast_ref::<&'static str>() {
512        (*s).to_string()
513    } else if let Some(s) = payload.downcast_ref::<String>() {
514        s.clone()
515    } else {
516        "Box<dyn Any>".to_string()
517    }
518}
519
520/// The text a failed call of the tool named
521/// `tool_name` may show the model, and whether `err` turned out to be a recovered panic. A
522/// [`ToolError::Panic`](gadk_agent::ToolError::Panic) anywhere in the error chain
523/// gives the generic ``Invoking `<tool>()` failed with an internal
524/// error.``, because the panic's own text carries the panic value; any other error gives its
525/// own text.
526pub(crate) fn model_error_text(tool_name: &str, err: &gadk_agent::ToolError) -> (String, bool) {
527    if chain_has_panic(err) {
528        return (
529            format!("Invoking `{tool_name}()` failed with an internal error."),
530            true,
531        );
532    }
533    (err.to_string(), false)
534}
535
536/// Whether a [`ToolError::Panic`](gadk_agent::ToolError::Panic) is anywhere in `err`'s chain.
537/// Transparent layers (`ToolError::Execution`, `SharedToolError`, `AgentError::Other` /
538/// `AgentError::Workflow`) forward `source()` past their inner error, so the walk descends into
539/// them directly.
540fn chain_has_panic(err: &(dyn std::error::Error + 'static)) -> bool {
541    use gadk_agent::{AgentError, SharedToolError, ToolError};
542    let mut cur: Option<&(dyn std::error::Error + 'static)> = Some(err);
543    while let Some(e) = cur {
544        cur = if let Some(te) = e.downcast_ref::<ToolError>() {
545            match te {
546                ToolError::Panic(_) => return true,
547                ToolError::Execution(inner) => Some(&**inner),
548                _ => std::error::Error::source(te),
549            }
550        } else if let Some(shared) = e.downcast_ref::<SharedToolError>() {
551            Some(&*shared.0)
552        } else if let Some(AgentError::Other(inner) | AgentError::Workflow(inner)) =
553            e.downcast_ref::<AgentError>()
554        {
555            Some(&**inner)
556        } else {
557            e.source()
558        };
559    }
560    false
561}
562
563#[cfg(test)]
564mod tests {
565    use std::collections::BTreeMap;
566
567    use gadk_genai::Type;
568    use pretty_assertions::assert_eq;
569    use serde_json::json;
570
571    use super::*;
572
573    /// A type mismatch names the JSON kind found and shows the value as JSON text.
574    #[test]
575    fn type_mismatch_names_the_kind_and_json_value() {
576        let schema = Schema {
577            r#type: Some(Type::Object),
578            properties: BTreeMap::from([(
579                "answer".to_owned(),
580                Schema {
581                    r#type: Some(Type::Integer),
582                    ..Default::default()
583                },
584            )]),
585            ..Default::default()
586        };
587        let check = |args: Value| {
588            let Value::Object(m) = args else {
589                unreachable!()
590            };
591            validate_map_on_schema(&m, &schema, false).unwrap_err()
592        };
593        assert_eq!(
594            check(json!({"answer": "42"})),
595            "output arg: '\"answer\"' type mismatch, expected schema type INTEGER, found a string (\"42\")"
596        );
597        assert_eq!(
598            check(json!({"answer": {"a": 1, "b": 1_000_000}})),
599            r#"output arg: '"answer"' type mismatch, expected schema type INTEGER, found an object ({"a":1,"b":1000000})"#
600        );
601    }
602}