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