Skip to main content

graphrt_core/
prompt_files.rs

1//! Prompt messages read from files: a message of a node's `prompt_template`
2//! (and the `revise.message` of an `llm` node) may name a `file` instead of
3//! writing its `text`.
4//!
5//! ```yaml
6//! prompt_template:
7//!   - role: system
8//!     file: ../prompts/report-rules.md   # relative to the workflow file
9//!     required: true                     # default: a missing or empty file is an error
10//!     strip_comments: true               # default: `<!-- ... -->` is taken out
11//!   - { role: user, text: "Write the report for {{#start.month#}}." }
12//! ```
13//!
14//! The file is read when the workflow is loaded ([`inline`]), and its text
15//! becomes the message's `text`, placeholders included. The document then
16//! holds the text, so validation sees it, the graph fingerprint covers it (a
17//! paused run is not resumed against a changed file) and a bundle carries it.
18//! Only a host that loads the workflow from a file can read prompt files: a
19//! document given as text with a `file` is an error.
20
21use crate::source_map::DocPath;
22use crate::validate::Diagnostic;
23
24/// Reads a prompt file named relative to the workflow, or says why it cannot.
25pub type ReadFile<'a> = &'a dyn Fn(&str) -> Result<String, String>;
26
27/// The keys of a message that reads its text from a file.
28const FILE_KEYS: [&str; 3] = ["file", "required", "strip_comments"];
29
30/// Replace every prompt message `file` of `raw` (a workflow document, as
31/// decoded from YAML or JSON) by its text, read with `read`. Returns what is
32/// wrong, located at the message's keys; a message that cannot be read is
33/// left as it is.
34pub fn inline(raw: &mut serde_json::Value, read: Option<ReadFile<'_>>) -> Vec<Diagnostic> {
35    let mut found = Vec::new();
36    let Some(nodes) = raw.get_mut("graph").and_then(|graph| graph.get_mut("nodes")).and_then(|n| n.as_array_mut())
37    else {
38        return found;
39    };
40    for (index, node) in nodes.iter_mut().enumerate() {
41        let node_path = DocPath::root().key("graph").key("nodes").index(index);
42        // A node writes its config next to `id` and `type`, or under `data`.
43        let (config, path) = match node.get("data").is_some_and(serde_json::Value::is_object) {
44            true => (node.get_mut("data"), node_path.key("data")),
45            false => (Some(node), node_path),
46        };
47        let Some(config) = config else { continue };
48        // The revision message of an `llm` node's `revise` is a prompt message too.
49        #[cfg(feature = "text-check")]
50        if let Some(message) = config.get_mut("revise").and_then(|revise| revise.get_mut("message")) {
51            inline_message(message, &path.key("revise").key("message"), read, &mut found);
52        }
53        let Some(template) = config.get_mut("prompt_template") else { continue };
54        let path = path.key("prompt_template");
55        match template {
56            serde_json::Value::Array(messages) => {
57                for (position, message) in messages.iter_mut().enumerate() {
58                    inline_message(message, &path.index(position), read, &mut found);
59                }
60            }
61            message @ serde_json::Value::Object(_) => inline_message(message, &path, read, &mut found),
62            _ => {}
63        }
64    }
65    found
66}
67
68fn inline_message(
69    message: &mut serde_json::Value,
70    path: &DocPath,
71    read: Option<ReadFile<'_>>,
72    found: &mut Vec<Diagnostic>,
73) {
74    let Some(fields) = message.as_object_mut() else { return };
75    if !FILE_KEYS.iter().any(|key| fields.contains_key(*key)) {
76        return;
77    }
78    let mut error = |key: &str, message: String| found.push(Diagnostic::error("prompt-file", path.key(key), message));
79    let Some(file) = fields.get("file").and_then(serde_json::Value::as_str).map(str::to_owned) else {
80        match fields.get("file") {
81            Some(_) => error("file", "`file` is the path of a text file, relative to the workflow".to_owned()),
82            None => error("required", "`required` and `strip_comments` go with a `file`".to_owned()),
83        }
84        return;
85    };
86    if fields.contains_key("text") {
87        error("file", "a message has `text` or `file`, not both".to_owned());
88        return;
89    }
90    let flag = |key: &str| match fields.get(key) {
91        None | Some(serde_json::Value::Null) => Ok(true),
92        Some(serde_json::Value::Bool(on)) => Ok(*on),
93        Some(_) => Err(format!("`{key}` is `true` or `false`")),
94    };
95    let (required, strip) = match (flag("required"), flag("strip_comments")) {
96        (Ok(required), Ok(strip)) => (required, strip),
97        (Err(why), _) => return error("required", why),
98        (_, Err(why)) => return error("strip_comments", why),
99    };
100    let Some(read) = read else {
101        return error(
102            "file",
103            format!("prompt file `{file}`: prompt files are read when the workflow is loaded from a file"),
104        );
105    };
106    let text = match read(&file) {
107        Ok(text) if strip => strip_comments(&text),
108        Ok(text) => text,
109        Err(why) if required => return error("file", format!("cannot read prompt file `{file}`: {why}")),
110        Err(_) => String::new(),
111    };
112    if required && text.trim().is_empty() {
113        return error("file", format!("prompt file `{file}` is empty"));
114    }
115    for key in FILE_KEYS {
116        fields.remove(key);
117    }
118    fields.insert("text".to_owned(), serde_json::Value::String(text));
119}
120
121/// `text` without its HTML comments (`<!-- ... -->`, an unclosed one runs to the end).
122pub fn strip_comments(text: &str) -> String {
123    let mut out = String::with_capacity(text.len());
124    let mut rest = text;
125    while let Some(start) = rest.find("<!--") {
126        out.push_str(rest.get(..start).unwrap_or_default());
127        let after = rest.get(start + 4..).unwrap_or_default();
128        match after.find("-->") {
129            Some(end) => rest = after.get(end + 3..).unwrap_or_default(),
130            None => return out,
131        }
132    }
133    out.push_str(rest);
134    out
135}
136
137#[cfg(test)]
138#[allow(clippy::unwrap_used, clippy::indexing_slicing)]
139mod tests {
140    use super::*;
141    use serde_json::json;
142
143    fn files(name: &str) -> Result<String, String> {
144        match name {
145            "rules.md" => {
146                Ok("<!-- for the editor -->Write short sentences.\n<!-- a\nnote -->Use {{#start.month#}}.\n".into())
147            }
148            "blank.md" => Ok("<!-- only a note -->\n".into()),
149            _ => Err("No such file or directory".into()),
150        }
151    }
152
153    fn doc(message: serde_json::Value) -> serde_json::Value {
154        json!({"graph": {"nodes": [{"id": "write", "type": "llm", "prompt_template": [
155            message, {"role": "user", "text": "Go."}
156        ]}]}})
157    }
158
159    #[test]
160    fn a_file_becomes_the_message_text() {
161        let mut raw = doc(json!({"role": "system", "file": "rules.md"}));
162        assert!(inline(&mut raw, Some(&files)).is_empty());
163        let message = &raw["graph"]["nodes"][0]["prompt_template"][0];
164        assert_eq!(*message, json!({"role": "system", "text": "Write short sentences.\nUse {{#start.month#}}.\n"}));
165        // As written, comments kept.
166        let mut raw = doc(json!({"file": "blank.md", "strip_comments": false}));
167        assert!(inline(&mut raw, Some(&files)).is_empty());
168        assert_eq!(raw["graph"]["nodes"][0]["prompt_template"][0]["text"], "<!-- only a note -->\n");
169    }
170
171    #[test]
172    fn a_missing_or_empty_file_is_an_error_unless_it_is_optional() {
173        for (message, said) in [
174            (json!({"file": "gone.md"}), "cannot read prompt file `gone.md`"),
175            (json!({"file": "blank.md"}), "is empty"),
176            (json!({"file": "rules.md", "text": "x"}), "not both"),
177            (json!({"file": 3}), "path of a text file"),
178            (json!({"file": "rules.md", "required": "yes"}), "`required`"),
179        ] {
180            let mut raw = doc(message.clone());
181            let found = inline(&mut raw, Some(&files));
182            assert_eq!(found.len(), 1, "{message}");
183            assert!(found[0].message.contains(said), "{message}: {}", found[0].message);
184            assert!(found[0].path.to_string().starts_with("graph.nodes[0].prompt_template[0]"), "{}", found[0].path);
185        }
186        let mut raw = doc(json!({"file": "gone.md", "required": false}));
187        assert!(inline(&mut raw, Some(&files)).is_empty());
188        assert_eq!(raw["graph"]["nodes"][0]["prompt_template"][0], json!({"text": ""}));
189    }
190
191    #[cfg(feature = "text-check")]
192    #[test]
193    fn the_revision_message_of_an_llm_node_is_read_too() {
194        let mut raw = json!({"graph": {"nodes": [{"id": "w", "type": "llm",
195            "prompt_template": [{"text": "Go."}], "revise": {"max_rounds": 2, "message": {"file": "rules.md"}}}]}});
196        assert!(inline(&mut raw, Some(&files)).is_empty());
197        assert!(raw["graph"]["nodes"][0]["revise"]["message"]["text"].as_str().unwrap().starts_with("Write"));
198        let mut raw =
199            json!({"graph": {"nodes": [{"id": "w", "type": "llm", "revise": {"message": {"file": "gone.md"}}}]}});
200        let found = inline(&mut raw, Some(&files));
201        assert_eq!(found[0].path.to_string(), "graph.nodes[0].revise.message.file");
202    }
203
204    #[test]
205    fn a_document_without_a_folder_cannot_read_files() {
206        let mut raw = doc(json!({"file": "rules.md"}));
207        let found = inline(&mut raw, None);
208        assert!(found[0].message.contains("loaded from a file"), "{}", found[0].message);
209        // A completion prompt and a node under `data` are read too.
210        let mut raw = json!({"graph": {"nodes": [{"id": "w", "data": {"type": "llm", "prompt_template": {"file": "rules.md"}}}]}});
211        assert!(inline(&mut raw, Some(&files)).is_empty());
212        assert!(raw["graph"]["nodes"][0]["data"]["prompt_template"]["text"].as_str().unwrap().starts_with("Write"));
213    }
214
215    #[test]
216    fn comments_are_taken_out() {
217        assert_eq!(strip_comments("a<!-- x -->b<!--c-->d"), "abd");
218        assert_eq!(strip_comments("keep <!-- open"), "keep ");
219        assert_eq!(strip_comments("no comment"), "no comment");
220    }
221}