use crate::prelude::*;
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, Hash)]
#[serde(rename_all = "lowercase")]
pub enum SchemaKind {
Object,
Array,
String,
Number,
Integer,
Boolean,
Null,
}
impl SchemaKind {
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 SchemaKind {
fn default() -> Self {
Self::Object
}
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Schema {
#[serde(rename = "type")]
pub kind: SchemaKind,
#[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<Schema>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<HashMap<String, Box<Schema>>>,
#[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 Schema {
pub fn new(kind: SchemaKind, 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(SchemaKind::Object, descr)
}
pub fn array(descr: impl Into<String>) -> Self {
Self::new(SchemaKind::Array, descr)
}
pub fn string(descr: impl Into<String>) -> Self {
Self::new(SchemaKind::String, descr)
}
pub fn number(descr: impl Into<String>) -> Self {
Self::new(SchemaKind::Number, descr)
}
pub fn integer(descr: impl Into<String>) -> Self {
Self::new(SchemaKind::Integer, descr)
}
pub fn boolean(descr: impl Into<String>) -> Self {
Self::new(SchemaKind::Boolean, descr)
}
pub fn null(descr: impl Into<String>) -> Self {
Self::new(SchemaKind::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: Schema) -> Self {
self.items.replace(Box::new(schema));
self
}
pub fn properties(mut self, props: HashMap<impl Into<String>, Box<Schema>>) -> 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: Schema, 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: Schema) -> Self {
self.property(name, schema, true)
}
pub fn optional_property(self, name: impl Into<String>, schema: Schema) -> 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 Schema {
pub fn to_openai_format(&self) -> Result<JsonValue> {
let mut schema_json = self.to_json_schema()?;
if let Some(obj) = schema_json.as_object_mut() {
if obj.get("type").and_then(|t| t.as_str()) == Some("object") {
obj.insert("additionalProperties".to_string(), json!(false));
}
}
Ok(json!({
"type": "json_schema",
"json_schema": {
"name": "response",
"schema": schema_json,
"strict": true
}
}))
}
pub fn to_anthropic_format(&self) -> Result<JsonValue> {
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> {
let schema_json = self.to_json_schema()?;
Ok(json!({
"response_mime_type": "application/json",
"response_schema": schema_json
}))
}
}
impl Schema {
pub fn to_json_schema(&self) -> Result<JsonValue> {
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());
}
}
}
if !required_set.is_empty() {
let mut final_required: Vec<_> = required_set.into_iter().collect();
final_required.sort();
obj.insert("required".to_string(), serde_json::json!(final_required));
} else {
obj.remove("required");
}
}
}
}
}