Skip to main content

reflex/pulse/write/
contract.rs

1//! The output contract of grounded sections: sentences with citations.
2//!
3//! ```json
4//! {"status": "ok", "missing": [],
5//!  "paragraphs": [{"sentences": [{"text": "…", "cite": ["F1", "F3"]}]}]}
6//! ```
7//! `status` is `insufficient_evidence` when the facts do not support a useful section;
8//! `missing` then says what would. Every field is required, so providers can enforce
9//! the schema strictly.
10
11use serde::{Deserialize, Serialize};
12use serde_json::json;
13
14#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
15pub struct Contract {
16    pub status: String,
17    #[serde(default)]
18    pub missing: Vec<String>,
19    #[serde(default)]
20    pub paragraphs: Vec<Paragraph>,
21}
22
23#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
24pub struct Paragraph {
25    pub sentences: Vec<Sentence>,
26}
27
28#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
29pub struct Sentence {
30    pub text: String,
31    #[serde(default)]
32    pub cite: Vec<String>,
33}
34
35/// The JSON schema of [`Contract`].
36pub fn schema() -> serde_json::Value {
37    let sentence = json!({
38        "type": "object",
39        "properties": {
40            "text": {"type": "string"},
41            "cite": {"type": "array", "items": {"type": "string"}}
42        },
43        "required": ["text", "cite"],
44        "additionalProperties": false
45    });
46    let paragraph = json!({
47        "type": "object",
48        "properties": {"sentences": {"type": "array", "items": sentence}},
49        "required": ["sentences"],
50        "additionalProperties": false
51    });
52    json!({
53        "type": "object",
54        "properties": {
55            "status": {"type": "string", "enum": ["ok", "insufficient_evidence"]},
56            "missing": {"type": "array", "items": {"type": "string"}},
57            "paragraphs": {"type": "array", "items": paragraph}
58        },
59        "required": ["status", "missing", "paragraphs"],
60        "additionalProperties": false
61    })
62}
63
64/// Parse a response: plain JSON, fenced JSON, or JSON inside prose.
65pub fn parse(text: &str) -> anyhow::Result<Contract> {
66    let t = text.trim();
67    let body = if let (Some(a), Some(b)) = (t.find('{'), t.rfind('}')) {
68        &t[a..=b]
69    } else {
70        t
71    };
72    let mut c: Contract = serde_json::from_str(body)?;
73    c.status = c.status.trim().to_ascii_lowercase().replace('-', "_");
74    Ok(c)
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80
81    #[test]
82    fn parses_plain_fenced_and_wrapped() {
83        let j = r#"{"status":"ok","missing":[],"paragraphs":[{"sentences":[{"text":"A.","cite":["F1"]}]}]}"#;
84        assert_eq!(
85            parse(j).unwrap().paragraphs[0].sentences[0].cite,
86            vec!["F1"]
87        );
88        assert!(parse(&format!("```json\n{j}\n```")).is_ok());
89        assert!(parse(&format!("Here you go:\n{j}\nThanks")).is_ok());
90        assert_eq!(
91            parse(r#"{"status":"Insufficient-Evidence"}"#)
92                .unwrap()
93                .status,
94            "insufficient_evidence"
95        );
96        assert!(parse("no json").is_err());
97    }
98
99    #[test]
100    fn schema_is_strict() {
101        let s = schema();
102        assert_eq!(s["additionalProperties"], false);
103        assert_eq!(s["required"].as_array().unwrap().len(), 3);
104    }
105}