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
27use crate::llm::processors::{as_go_floats, go_sprint};
28
29pub(crate) const AF_FUNCTION_CALL_ID_PREFIX: &str = "adk-";
31
32pub(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
46pub(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
65pub(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
75fn go_marshaled_numbers(v: Value) -> Value {
80 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)] 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 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
108pub(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
121fn settings() -> SchemaSettings {
126 SchemaSettings::draft2020_12()
127 .with(|s| {
128 s.meta_schema = None; s.inline_subschemas = true; })
131 .with_transform(RecursiveTransform(
132 go_schema_shape as fn(&mut schemars::Schema),
133 ))
134}
135
136fn 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 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
165pub(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
175pub(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#[derive(Debug, Clone)]
187pub(crate) struct CompiledSchema {
188 schema: Value,
189 validator: Arc<jsonschema::Validator>,
191}
192
193impl CompiledSchema {
194 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 pub(crate) fn schema(&self) -> &Value {
205 &self.schema
206 }
207
208 pub(crate) fn validate(&self, v: &Value) -> Result<(), String> {
210 self.validator.validate(v).map_err(|e| e.to_string())
211 }
212}
213
214const UNORDERED_ARRAY_KEYWORDS: [&str; 2] = ["required", "type"];
220
221pub(crate) fn canonical_schema_json(schema: &Value) -> String {
225 canonicalize(schema)
226}
227
228pub(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
263fn 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
274fn 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
285pub(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
295pub(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 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
339pub(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 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
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 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
414pub(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
428pub(crate) fn generate_function_call_id(platform: &Platform) -> String {
430 format!("{AF_FUNCTION_CALL_ID_PREFIX}{}", platform.new_uuid())
431}
432
433pub(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
449pub(crate) use gadk_session::compaction::content;
451
452pub 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
463pub(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
474pub(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#[allow(dead_code)] pub(crate) fn content_text(c: &Content) -> String {
489 text_parts(Some(c)).concat()
490}
491
492#[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
506pub(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
514pub(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
525pub(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
541fn 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 #[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}