use derive_more::From;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use value_ext::JsonValueExt;
#[derive(Debug, Clone, From, Serialize, Deserialize)]
pub enum ChatResponseFormat {
JsonMode,
#[from]
JsonSpec(JsonSpec),
}
#[derive(Debug, Clone, From, Serialize, Deserialize)]
pub struct JsonSpec {
pub name: String,
pub description: Option<String>,
pub schema: Value,
}
impl JsonSpec {
pub fn new(name: impl Into<String>, schema: impl Into<Value>) -> Self {
Self {
name: name.into(),
description: None,
schema: schema.into(),
}
}
}
impl JsonSpec {
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
}
impl JsonSpec {
pub fn schema_with_additional_properties_false(&self) -> Value {
let mut schema = self.schema.clone();
schema.x_walk(|parent_map, name| {
if name == "type" {
let typ = parent_map.get("type").and_then(|v| v.as_str()).unwrap_or("");
if typ == "object" {
parent_map.insert("additionalProperties".to_string(), false.into());
}
}
true
});
schema
}
}