1use 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
27pub(crate) const AF_FUNCTION_CALL_ID_PREFIX: &str = "adk-";
29
30pub(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
44pub(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
63pub(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
73fn go_marshaled_numbers(v: Value) -> Value {
78 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)] 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 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
106pub(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
119fn settings() -> SchemaSettings {
124 SchemaSettings::draft2020_12()
125 .with(|s| {
126 s.meta_schema = None; s.inline_subschemas = true; })
129 .with_transform(RecursiveTransform(
130 go_schema_shape as fn(&mut schemars::Schema),
131 ))
132}
133
134fn 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 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
163pub(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
173pub(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#[derive(Debug, Clone)]
185pub(crate) struct CompiledSchema {
186 schema: Value,
187 validator: Arc<jsonschema::Validator>,
189}
190
191impl CompiledSchema {
192 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 pub(crate) fn schema(&self) -> &Value {
203 &self.schema
204 }
205
206 pub(crate) fn validate(&self, v: &Value) -> Result<(), String> {
208 self.validator.validate(v).map_err(|e| e.to_string())
209 }
210}
211
212const UNORDERED_ARRAY_KEYWORDS: [&str; 2] = ["required", "type"];
218
219pub(crate) fn canonical_schema_json(schema: &Value) -> String {
223 canonicalize(schema)
224}
225
226pub(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
261fn 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
272fn 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
283pub(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
293pub(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 nil".to_string());
301 };
302 if value.is_null() {
303 return Ok(schema.nullable == Some(true));
304 }
305 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
337pub(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 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
386pub(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 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
409pub(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
423pub(crate) fn generate_function_call_id(platform: &Platform) -> String {
425 format!("{AF_FUNCTION_CALL_ID_PREFIX}{}", platform.new_uuid())
426}
427
428pub(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
444pub(crate) use gadk_session::compaction::content;
446
447pub 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
458pub(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
469pub(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#[allow(dead_code)] pub(crate) fn content_text(c: &Content) -> String {
484 text_parts(Some(c)).concat()
485}
486
487#[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
501pub(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
509pub(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
520pub(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
536fn 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 #[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}