use gadk_genai::{Schema, Type};
use serde_json::{Map, Value};
pub(crate) fn model_output_schema(resolved: Option<&Value>) -> Option<Schema> {
let root = resolved?.as_object()?;
if type_list(root).is_some_and(|ts| ts.iter().any(|t| t == "null")) {
return None;
}
let s = to_genai_schema(resolved?)?;
(s.r#type == Some(Type::Object)).then_some(s)
}
fn type_list(s: &Map<String, Value>) -> Option<Vec<String>> {
match s.get("type")? {
Value::Array(ts) => Some(
ts.iter()
.map(|t| t.as_str().unwrap_or_default().to_string())
.collect(),
),
_ => None,
}
}
fn genai_type(name: &str) -> Option<Type> {
match name {
"string" => Some(Type::String),
"integer" => Some(Type::Integer),
"number" => Some(Type::Number),
"boolean" => Some(Type::Boolean),
"array" => Some(Type::Array),
"object" => Some(Type::Object),
_ => None,
}
}
fn to_genai_schema(v: &Value) -> Option<Schema> {
let s = v.as_object()?;
if !only_known_keywords(s) {
return None;
}
let (typ, nullable) = schema_type(s)?;
let enum_values = match s.get("enum") {
None => Vec::new(),
Some(Value::Array(vals)) => vals.clone(),
Some(_) => return None,
};
if !enum_values.is_empty() && typ != Type::String {
return None;
}
let mut out = Schema {
r#type: Some(typ.clone()),
title: string_keyword(s, "title")?,
description: string_keyword(s, "description")?,
..Schema::default()
};
if nullable {
out.nullable = Some(true);
}
for e in &enum_values {
out.r#enum.push(e.as_str()?.to_string());
}
match typ {
Type::Object => {
let props = match s.get("properties") {
Some(Value::Object(p)) if !p.is_empty() => p,
_ => return None,
};
if !s.get("additionalProperties").is_some_and(is_false_schema) {
return None;
}
let required = match s.get("required") {
None => Vec::new(),
Some(Value::Array(r)) => r
.iter()
.map(|n| n.as_str().map(str::to_string))
.collect::<Option<Vec<_>>>()?,
Some(_) => return None,
};
if required.iter().any(|n| !props.contains_key(n)) {
return None;
}
for (name, prop) in props {
out.properties.insert(name.clone(), to_genai_schema(prop)?);
}
out.required = required;
}
Type::Array => {
out.items = Some(Box::new(to_genai_schema(s.get("items")?)?));
}
_ => {}
}
Some(out)
}
fn string_keyword(s: &Map<String, Value>, key: &str) -> Option<String> {
match s.get(key) {
None => Some(String::new()),
Some(Value::String(v)) => Some(v.clone()),
Some(_) => None,
}
}
fn only_known_keywords(s: &Map<String, Value>) -> bool {
const CONVERTED: &[&str] = &[
"type",
"enum",
"title",
"description",
"properties",
"required",
"items",
];
const DROPPED: &[&str] = &[
"propertyOrder",
"minimum",
"maximum",
"exclusiveMinimum",
"exclusiveMaximum",
"multipleOf",
"minLength",
"maxLength",
"pattern",
"format",
"minItems",
"maxItems",
"uniqueItems",
"minProperties",
"maxProperties",
"default",
"examples",
"$comment",
"$schema",
"$id",
"$anchor",
"deprecated",
"readOnly",
"writeOnly",
];
s.iter().all(|(k, v)| {
CONVERTED.contains(&k.as_str())
|| DROPPED.contains(&k.as_str())
|| (k == "additionalProperties" && is_false_schema(v))
})
}
fn is_false_schema(v: &Value) -> bool {
match v {
Value::Bool(b) => !b,
Value::Object(o) => {
o.len() == 1
&& o.get("not")
.is_some_and(|n| n.as_object().is_some_and(Map::is_empty))
}
_ => false,
}
}
fn schema_type(s: &Map<String, Value>) -> Option<(Type, bool)> {
match s.get("type")? {
Value::String(t) => Some((genai_type(t)?, false)),
Value::Array(ts) => {
let mut name: Option<&str> = None;
let mut nullable = false;
for t in ts {
let t = t.as_str()?;
if t == "null" {
nullable = true;
continue;
}
if name.is_some() {
return None;
}
name = Some(t);
}
Some((genai_type(name?)?, nullable))
}
_ => None,
}
}