use crate::prelude::*;
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, Hash)]
#[serde(rename_all = "lowercase")]
pub enum JsonSchemaKind {
Object,
Array,
String,
Number,
Integer,
Boolean,
Null,
}
impl JsonSchemaKind {
pub fn is_object(&self) -> bool {
matches!(self, Self::Object)
}
pub fn is_array(&self) -> bool {
matches!(self, Self::Array)
}
pub fn is_string(&self) -> bool {
matches!(self, Self::String)
}
pub fn is_integer(&self) -> bool {
matches!(self, Self::Integer)
}
pub fn is_boolean(&self) -> bool {
matches!(self, Self::Boolean)
}
pub fn is_null(&self) -> bool {
matches!(self, Self::Null)
}
}
impl Default for JsonSchemaKind {
fn default() -> Self {
Self::Object
}
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct JsonSchema {
#[serde(rename = "type")]
pub kind: JsonSchemaKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[serde(alias = "enum")]
pub variants: Option<HashSet<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub minimum: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub maximum: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub items: Option<Box<JsonSchema>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<HashMap<String, Box<JsonSchema>>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub required: Option<HashSet<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub optional: Option<bool>,
#[serde(rename = "additionalProperties")]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub additional_properties: Option<bool>,
}
impl JsonSchema {
pub fn new(kind: JsonSchemaKind, descr: impl Into<String>) -> Self {
Self {
kind,
description: match descr.into() {
s if !s.is_empty() => Some(s),
_ => None,
},
..Default::default()
}
}
pub fn object(descr: impl Into<String>) -> Self {
Self::new(JsonSchemaKind::Object, descr)
}
pub fn array(descr: impl Into<String>) -> Self {
Self::new(JsonSchemaKind::Array, descr)
}
pub fn string(descr: impl Into<String>) -> Self {
Self::new(JsonSchemaKind::String, descr)
}
pub fn number(descr: impl Into<String>) -> Self {
Self::new(JsonSchemaKind::Number, descr)
}
pub fn integer(descr: impl Into<String>) -> Self {
Self::new(JsonSchemaKind::Integer, descr)
}
pub fn boolean(descr: impl Into<String>) -> Self {
Self::new(JsonSchemaKind::Boolean, descr)
}
pub fn null(descr: impl Into<String>) -> Self {
Self::new(JsonSchemaKind::Null, descr)
}
pub fn description(mut self, descr: impl Into<String>) -> Self {
self.description.replace(descr.into());
self
}
pub fn variants(mut self, vars: HashSet<String>) -> Self {
self.variants.get_or_insert_default().extend(vars);
self
}
pub fn variant(mut self, var: impl Into<String>) -> Self {
self.variants.get_or_insert_default().insert(var.into());
self
}
pub fn minimum(mut self, min: f64) -> Self {
self.minimum.replace(min);
self
}
pub fn maximum(mut self, max: f64) -> Self {
self.maximum.replace(max);
self
}
pub fn items(mut self, schema: JsonSchema) -> Self {
self.items.replace(Box::new(schema));
self
}
pub fn properties(mut self, props: HashMap<impl Into<String>, Box<JsonSchema>>) -> Self {
self.properties
.get_or_insert_default()
.extend(props.into_iter().map(|(k, v)| (k.into(), v)));
self
}
pub fn property(mut self, name: impl Into<String>, schema: JsonSchema, required: bool) -> Self {
let name = name.into();
let reqs = self.required.get_or_insert_default();
if required {
reqs.insert(name.clone());
}
self.properties
.get_or_insert_default()
.insert(name, Box::new(schema));
self
}
pub fn required_property(self, name: impl Into<String>, schema: JsonSchema) -> Self {
self.property(name, schema, true)
}
pub fn optional_property(self, name: impl Into<String>, schema: JsonSchema) -> Self {
self.property(name, schema, false)
}
pub fn required(mut self, reqs: Vec<impl Into<String>>) -> Self {
self.required
.get_or_insert_default()
.extend(reqs.into_iter().map(Into::into));
self
}
pub fn add_required(mut self, name: impl Into<String>) -> Self {
self.required.get_or_insert_default().insert(name.into());
self
}
}
impl JsonSchema {
pub fn to_openai_format(&self) -> Result<JsonValue, Error> {
let mut schema_json = self.to_json_schema()?;
Self::apply_openai_strict_rules(&mut schema_json);
Ok(json!({
"type": "json_schema",
"json_schema": {
"name": "response",
"schema": schema_json,
"strict": true
}
}))
}
fn apply_openai_strict_rules(value: &mut JsonValue) {
if let Some(obj) = value.as_object_mut() {
if obj.get("type").and_then(|t| t.as_str()) == Some("object") {
obj.insert("additionalProperties".to_string(), json!(false));
if !obj.contains_key("properties") {
obj.insert("properties".to_string(), json!({}));
}
if !obj.contains_key("required") {
obj.insert("required".to_string(), json!([]));
}
}
if let Some(props) = obj.get_mut("properties").and_then(|p| p.as_object_mut()) {
for prop in props.values_mut() {
Self::apply_openai_strict_rules(prop);
}
}
if let Some(items) = obj.get_mut("items") {
Self::apply_openai_strict_rules(items);
}
}
}
pub fn to_anthropic_format(&self) -> Result<JsonValue, Error> {
let mut schema_json = self.to_json_schema()?;
if let Some(obj) = schema_json.as_object_mut() {
obj.insert("additionalProperties".to_string(), json!(false));
}
Ok(json!({
"format": {
"type": "json_schema",
"schema": schema_json
}
}))
}
pub fn to_google_format(&self) -> Result<JsonValue, Error> {
let schema_json = self.to_json_schema()?;
Ok(json!({
"response_mime_type": "application/json",
"response_schema": schema_json
}))
}
}
impl JsonSchema {
pub fn to_json_schema(&self) -> Result<JsonValue, Error> {
let mut v = serde_json::to_value(self)?;
Self::sanitize_json_schema(&mut v);
Ok(v)
}
pub fn sanitize_json_schema(value: &mut JsonValue) {
if let Some(obj) = value.as_object_mut() {
if let Some(variants_value) = obj.remove("variants") {
obj.insert("enum".to_string(), variants_value);
}
if let Some(items) = obj.get_mut("items") {
Self::sanitize_json_schema(items);
}
let mut required_set: HashSet<String> = obj
.get("required")
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.collect()
})
.unwrap_or_default();
if let Some(props) = obj.get_mut("properties").and_then(|p| p.as_object_mut()) {
for (name, prop) in props.iter_mut() {
Self::sanitize_json_schema(prop);
if let Some(prop_obj) = prop.as_object_mut() {
let is_optional = prop_obj
.remove("optional")
.and_then(|v| v.as_bool())
.unwrap_or(false);
if !is_optional {
required_set.insert(name.clone());
}
}
}
let mut final_required: Vec<_> = required_set.into_iter().collect();
final_required.sort();
obj.insert("required".to_string(), serde_json::json!(final_required));
} else if obj.get("type").and_then(|t| t.as_str()) == Some("object") {
if !obj.contains_key("required") {
obj.insert("required".to_string(), json!([]));
}
}
}
}
}