1use crate::source_map::DocPath;
21use crate::validate::Diagnostic;
22
23pub type ReadFile<'a> = &'a dyn Fn(&str) -> Result<String, String>;
25
26const FILE_KEYS: [&str; 3] = ["file", "required", "strip_comments"];
28
29pub fn inline(raw: &mut serde_json::Value, read: Option<ReadFile<'_>>) -> Vec<Diagnostic> {
34 let mut found = Vec::new();
35 let Some(nodes) = raw.get_mut("graph").and_then(|graph| graph.get_mut("nodes")).and_then(|n| n.as_array_mut())
36 else {
37 return found;
38 };
39 for (index, node) in nodes.iter_mut().enumerate() {
40 let node_path = DocPath::root().key("graph").key("nodes").index(index);
41 let (config, path) = match node.get("data").is_some_and(serde_json::Value::is_object) {
43 true => (node.get_mut("data"), node_path.key("data")),
44 false => (Some(node), node_path),
45 };
46 let Some(template) = config.and_then(|config| config.get_mut("prompt_template")) else { continue };
47 let path = path.key("prompt_template");
48 match template {
49 serde_json::Value::Array(messages) => {
50 for (position, message) in messages.iter_mut().enumerate() {
51 inline_message(message, &path.index(position), read, &mut found);
52 }
53 }
54 message @ serde_json::Value::Object(_) => inline_message(message, &path, read, &mut found),
55 _ => {}
56 }
57 }
58 found
59}
60
61fn inline_message(
62 message: &mut serde_json::Value,
63 path: &DocPath,
64 read: Option<ReadFile<'_>>,
65 found: &mut Vec<Diagnostic>,
66) {
67 let Some(fields) = message.as_object_mut() else { return };
68 if !FILE_KEYS.iter().any(|key| fields.contains_key(*key)) {
69 return;
70 }
71 let mut error = |key: &str, message: String| found.push(Diagnostic::error("prompt-file", path.key(key), message));
72 let Some(file) = fields.get("file").and_then(serde_json::Value::as_str).map(str::to_owned) else {
73 match fields.get("file") {
74 Some(_) => error("file", "`file` is the path of a text file, relative to the workflow".to_owned()),
75 None => error("required", "`required` and `strip_comments` go with a `file`".to_owned()),
76 }
77 return;
78 };
79 if fields.contains_key("text") {
80 error("file", "a message has `text` or `file`, not both".to_owned());
81 return;
82 }
83 let flag = |key: &str| match fields.get(key) {
84 None | Some(serde_json::Value::Null) => Ok(true),
85 Some(serde_json::Value::Bool(on)) => Ok(*on),
86 Some(_) => Err(format!("`{key}` is `true` or `false`")),
87 };
88 let (required, strip) = match (flag("required"), flag("strip_comments")) {
89 (Ok(required), Ok(strip)) => (required, strip),
90 (Err(why), _) => return error("required", why),
91 (_, Err(why)) => return error("strip_comments", why),
92 };
93 let Some(read) = read else {
94 return error(
95 "file",
96 format!("prompt file `{file}`: prompt files are read when the workflow is loaded from a file"),
97 );
98 };
99 let text = match read(&file) {
100 Ok(text) if strip => strip_comments(&text),
101 Ok(text) => text,
102 Err(why) if required => return error("file", format!("cannot read prompt file `{file}`: {why}")),
103 Err(_) => String::new(),
104 };
105 if required && text.trim().is_empty() {
106 return error("file", format!("prompt file `{file}` is empty"));
107 }
108 for key in FILE_KEYS {
109 fields.remove(key);
110 }
111 fields.insert("text".to_owned(), serde_json::Value::String(text));
112}
113
114pub fn strip_comments(text: &str) -> String {
116 let mut out = String::with_capacity(text.len());
117 let mut rest = text;
118 while let Some(start) = rest.find("<!--") {
119 out.push_str(rest.get(..start).unwrap_or_default());
120 let after = rest.get(start + 4..).unwrap_or_default();
121 match after.find("-->") {
122 Some(end) => rest = after.get(end + 3..).unwrap_or_default(),
123 None => return out,
124 }
125 }
126 out.push_str(rest);
127 out
128}
129
130#[cfg(test)]
131#[allow(clippy::unwrap_used, clippy::indexing_slicing)]
132mod tests {
133 use super::*;
134 use serde_json::json;
135
136 fn files(name: &str) -> Result<String, String> {
137 match name {
138 "rules.md" => {
139 Ok("<!-- for the editor -->Write short sentences.\n<!-- a\nnote -->Use {{#start.month#}}.\n".into())
140 }
141 "blank.md" => Ok("<!-- only a note -->\n".into()),
142 _ => Err("No such file or directory".into()),
143 }
144 }
145
146 fn doc(message: serde_json::Value) -> serde_json::Value {
147 json!({"graph": {"nodes": [{"id": "write", "type": "llm", "prompt_template": [
148 message, {"role": "user", "text": "Go."}
149 ]}]}})
150 }
151
152 #[test]
153 fn a_file_becomes_the_message_text() {
154 let mut raw = doc(json!({"role": "system", "file": "rules.md"}));
155 assert!(inline(&mut raw, Some(&files)).is_empty());
156 let message = &raw["graph"]["nodes"][0]["prompt_template"][0];
157 assert_eq!(*message, json!({"role": "system", "text": "Write short sentences.\nUse {{#start.month#}}.\n"}));
158 let mut raw = doc(json!({"file": "blank.md", "strip_comments": false}));
160 assert!(inline(&mut raw, Some(&files)).is_empty());
161 assert_eq!(raw["graph"]["nodes"][0]["prompt_template"][0]["text"], "<!-- only a note -->\n");
162 }
163
164 #[test]
165 fn a_missing_or_empty_file_is_an_error_unless_it_is_optional() {
166 for (message, said) in [
167 (json!({"file": "gone.md"}), "cannot read prompt file `gone.md`"),
168 (json!({"file": "blank.md"}), "is empty"),
169 (json!({"file": "rules.md", "text": "x"}), "not both"),
170 (json!({"file": 3}), "path of a text file"),
171 (json!({"file": "rules.md", "required": "yes"}), "`required`"),
172 ] {
173 let mut raw = doc(message.clone());
174 let found = inline(&mut raw, Some(&files));
175 assert_eq!(found.len(), 1, "{message}");
176 assert!(found[0].message.contains(said), "{message}: {}", found[0].message);
177 assert!(found[0].path.to_string().starts_with("graph.nodes[0].prompt_template[0]"), "{}", found[0].path);
178 }
179 let mut raw = doc(json!({"file": "gone.md", "required": false}));
180 assert!(inline(&mut raw, Some(&files)).is_empty());
181 assert_eq!(raw["graph"]["nodes"][0]["prompt_template"][0], json!({"text": ""}));
182 }
183
184 #[test]
185 fn a_document_without_a_folder_cannot_read_files() {
186 let mut raw = doc(json!({"file": "rules.md"}));
187 let found = inline(&mut raw, None);
188 assert!(found[0].message.contains("loaded from a file"), "{}", found[0].message);
189 let mut raw = json!({"graph": {"nodes": [{"id": "w", "data": {"type": "llm", "prompt_template": {"file": "rules.md"}}}]}});
191 assert!(inline(&mut raw, Some(&files)).is_empty());
192 assert!(raw["graph"]["nodes"][0]["data"]["prompt_template"]["text"].as_str().unwrap().starts_with("Write"));
193 }
194
195 #[test]
196 fn comments_are_taken_out() {
197 assert_eq!(strip_comments("a<!-- x -->b<!--c-->d"), "abd");
198 assert_eq!(strip_comments("keep <!-- open"), "keep ");
199 assert_eq!(strip_comments("no comment"), "no comment");
200 }
201}