use serde_json::Value; pub const INSTRUCTION: &str = "\n\nYour final answer must be a single JSON value that matches this JSON schema. Reply with the JSON only, no prose and no code fence:\n"; pub struct Schema { validator: jsonschema::Validator, pub text: String, } impl Schema { pub fn load(path: &std::path::Path) -> anyhow::Result { let text = std::fs::read_to_string(path) .map_err(|e| anyhow::anyhow!("--schema {}: {e}", path.display()))?; let v: Value = serde_json::from_str(&text) .map_err(|e| anyhow::anyhow!("--schema {}: {e}", path.display()))?; let validator = jsonschema::validator_for(&v) .map_err(|e| anyhow::anyhow!("--schema {}: {e}", path.display()))?; Ok(Self { validator, text }) } pub fn check(&self, answer: &str) -> Result { let v = extract(answer).ok_or("the answer is not valid JSON")?; let errs: Vec = self .validator .iter_errors(&v) .map(|e| format!("{} (at {})", e, e.instance_path())) .collect(); if errs.is_empty() { Ok(v) } else { Err(errs.join("\n")) } } } pub fn retry_prompt(problem: &str) -> String { format!( "Your last answer does not match the schema:\n{problem}\nReply again with only the corrected JSON." ) } fn extract(s: &str) -> Option { let s = s.trim(); let body = match s.strip_prefix("```") { Some(rest) => { let rest = rest.split_once('\n').map_or(rest, |(_, b)| b); rest.rsplit_once("```").map_or(rest, |(b, _)| b) } None => s, }; serde_json::from_str(body.trim()).ok() } #[cfg(test)] mod tests { use super::*; fn schema() -> Schema { let v: Value = serde_json::json!({ "type": "object", "required": ["name"], "properties": {"name": {"type": "string"}} }); Schema { validator: jsonschema::validator_for(&v).unwrap(), text: v.to_string(), } } #[test] fn accepts_plain_and_fenced() { let s = schema(); assert!(s.check(r#"{"name":"a"}"#).is_ok()); assert!(s.check("```json\n{\"name\":\"a\"}\n```").is_ok()); } #[test] fn rejects_wrong_shape_and_prose() { let s = schema(); assert!(s.check(r#"{"name":1}"#).unwrap_err().contains("name")); assert!(s.check("here you go").is_err()); } }