1use serde_json::Value;
5
6use crate::{Error, Result};
7
8pub const TOOL_OPEN: &str = "<tool_call>";
9pub const TOOL_CLOSE: &str = "</tool_call>";
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum ChatRole {
13 System,
14 User,
15 Assistant,
16}
17
18impl ChatRole {
19 pub fn as_str(self) -> &'static str {
20 match self {
21 ChatRole::System => "system",
22 ChatRole::User => "user",
23 ChatRole::Assistant => "assistant",
24 }
25 }
26}
27
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct ChatMessage {
30 pub role: ChatRole,
31 pub content: String,
32}
33
34impl ChatMessage {
35 pub fn new(role: ChatRole, content: impl Into<String>) -> Self {
36 Self { role, content: content.into() }
37 }
38}
39
40#[derive(Debug, Clone, PartialEq)]
42pub struct ToolDesc {
43 pub name: String,
44 pub description: String,
45 pub schema: Value,
47}
48
49pub fn tool_prompt(tools: &[ToolDesc]) -> String {
51 if tools.is_empty() {
52 return String::new();
53 }
54 let mut s = String::from(
55 "You can call tools. To call one, reply with only\n<tool_call>{\"name\": \"TOOL\", \"arguments\": {...}}</tool_call>\nand wait for the result. Tools (JSON Schema arguments):\n",
56 );
57 for t in tools {
58 s.push_str(&format!("- {}: {} {}\n", t.name, t.description, t.schema));
59 }
60 s
61}
62
63pub fn call_text(name: &str, args: &Value) -> String {
65 format!("{TOOL_OPEN}{}{TOOL_CLOSE}", serde_json::json!({"name": name, "arguments": args}))
66}
67
68pub fn result_text(name: &str, content: &str, is_error: bool) -> String {
70 format!("<tool_result name=\"{name}\"{}>{content}</tool_result>", if is_error { " error=\"true\"" } else { "" })
71}
72
73pub fn render(template: &str, turns: &[ChatMessage], bos: &str) -> Result<String> {
76 let mut env = minijinja::Environment::new();
77 minijinja_contrib::add_to_environment(&mut env);
78 env.set_unknown_method_callback(minijinja_contrib::pycompat::unknown_method_callback);
79 env.add_function("raise_exception", |m: String| -> std::result::Result<String, minijinja::Error> {
80 Err(minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, m))
81 });
82 let model = |e: minijinja::Error| Error::Model(format!("chat template: {e}"));
83 env.add_template("chat", template).map_err(model)?;
84 let msgs: Vec<minijinja::Value> = turns.iter().map(|m| minijinja::context! { role => m.role.as_str(), content => &m.content }).collect();
85 env.get_template("chat")
86 .map_err(model)?
87 .render(minijinja::context! { messages => minijinja::Value::from(msgs), add_generation_prompt => true, bos_token => bos, eos_token => "" })
88 .map_err(model)
89}
90
91pub fn render_fallback(turns: &[ChatMessage]) -> String {
93 let mut s = String::new();
94 let mut pending_sys = String::new();
95 for m in turns {
96 match m.role {
97 ChatRole::System => pending_sys = format!("{}\n\n", m.content),
98 ChatRole::User => s.push_str(&format!("<start_of_turn>user\n{}{}<end_of_turn>\n", std::mem::take(&mut pending_sys), m.content)),
99 ChatRole::Assistant => s.push_str(&format!("<start_of_turn>model\n{}<end_of_turn>\n", m.content)),
100 }
101 }
102 s.push_str("<start_of_turn>model\n");
103 s
104}
105
106#[derive(Debug, Clone, PartialEq)]
108pub enum Piece {
109 Text(String),
110 Call { name: String, arguments: Value },
111}
112
113#[derive(Debug, Default)]
116pub struct ToolStream {
117 buf: String,
118 in_call: bool,
119 calls: usize,
120}
121
122impl ToolStream {
123 pub fn calls(&self) -> usize {
124 self.calls
125 }
126
127 pub fn feed(&mut self, piece: &str) -> Vec<Piece> {
128 let mut out = Vec::new();
129 self.buf.push_str(piece);
130 loop {
131 if self.in_call {
132 let Some(end) = self.buf.find(TOOL_CLOSE) else { return out };
133 let body: String = self.buf[..end].to_string();
134 self.buf.drain(..end + TOOL_CLOSE.len());
135 self.in_call = false;
136 out.push(self.call(&body));
137 } else if let Some(i) = self.buf.find(TOOL_OPEN) {
138 if i > 0 {
139 out.push(Piece::Text(self.buf[..i].to_string()));
140 }
141 self.buf.drain(..i + TOOL_OPEN.len());
142 self.in_call = true;
143 } else {
144 let keep = (1..TOOL_OPEN.len())
145 .rev()
146 .find(|&k| {
147 self.buf.len() >= k && self.buf.is_char_boundary(self.buf.len() - k) && TOOL_OPEN.starts_with(&self.buf[self.buf.len() - k..])
148 })
149 .unwrap_or(0);
150 let cut = self.buf.len() - keep;
151 if cut > 0 {
152 out.push(Piece::Text(self.buf[..cut].to_string()));
153 self.buf.drain(..cut);
154 }
155 return out;
156 }
157 }
158 }
159
160 fn call(&mut self, body: &str) -> Piece {
161 let v: Value = serde_json::from_str(body.trim()).unwrap_or(Value::Null);
162 self.calls += 1;
163 let arguments = if v["arguments"].is_null() { Value::Object(Default::default()) } else { v["arguments"].clone() };
164 Piece::Call { name: v["name"].as_str().unwrap_or("").to_string(), arguments }
165 }
166
167 pub fn finish(&mut self) -> Vec<Piece> {
169 let rest = std::mem::take(&mut self.buf);
170 if self.in_call {
171 self.in_call = false;
172 vec![self.call(&rest)]
173 } else if rest.is_empty() {
174 Vec::new()
175 } else {
176 vec![Piece::Text(rest)]
177 }
178 }
179}
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184
185 fn text(p: &[Piece]) -> String {
186 p.iter().filter_map(|p| if let Piece::Text(t) = p { Some(t.as_str()) } else { None }).collect()
187 }
188
189 #[test]
190 fn a_template_renders_roles_and_the_generation_prompt() {
191 let t = "{% for m in messages %}<{{ m.role }}>{{ m.content }}\n{% endfor %}{% if add_generation_prompt %}<model>{% endif %}";
192 let turns = [ChatMessage::new(ChatRole::System, "be brief"), ChatMessage::new(ChatRole::User, "hi")];
193 assert_eq!(render(t, &turns, "").unwrap(), "<system>be brief\n<user>hi\n<model>");
194 assert!(render("{{ raise_exception('no') }}", &turns, "").is_err());
195 assert!(render("{% bad", &turns, "").is_err());
196 }
197
198 #[test]
199 fn the_fallback_folds_the_system_text_into_the_first_user_turn() {
200 let turns = [ChatMessage::new(ChatRole::System, "S"), ChatMessage::new(ChatRole::User, "U"), ChatMessage::new(ChatRole::Assistant, "A")];
201 assert_eq!(render_fallback(&turns), "<start_of_turn>user\nS\n\nU<end_of_turn>\n<start_of_turn>model\nA<end_of_turn>\n<start_of_turn>model\n");
202 }
203
204 #[test]
205 fn tool_text_round_trips_through_the_stream_parser() {
206 let call = call_text("open_url", &serde_json::json!({"url": "https://a.com"}));
207 let mut s = ToolStream::default();
208 let mut got = Vec::new();
209 for chunk in ["Sure. <tool", "_call>{\"name\":\"open_url\",\"argu", "ments\":{\"url\":\"https://a.com\"}}</tool_", "call> done"] {
210 got.extend(s.feed(chunk));
211 }
212 got.extend(s.finish());
213 assert_eq!(text(&got), "Sure. done");
214 assert!(got.contains(&Piece::Call { name: "open_url".into(), arguments: serde_json::json!({"url": "https://a.com"}) }));
215 assert_eq!(s.calls(), 1);
216 let mut s2 = ToolStream::default();
217 assert!(matches!(s2.feed(&call).as_slice(), [Piece::Call { name, .. }] if name == "open_url"));
218 }
219
220 #[test]
221 fn a_partial_tag_is_held_back_and_plain_text_flows() {
222 let mut s = ToolStream::default();
223 assert_eq!(s.feed("a <"), vec![Piece::Text("a ".into())]);
224 assert_eq!(s.feed("b"), vec![Piece::Text("<b".into())]);
225 assert!(s.finish().is_empty());
226 let mut s = ToolStream::default();
227 assert!(s.feed("<tool_call>{\"name\":\"x\"}").is_empty());
228 assert_eq!(s.finish(), vec![Piece::Call { name: "x".into(), arguments: serde_json::json!({}) }]);
229 }
230
231 #[test]
232 fn tools_are_described_and_results_marked() {
233 assert_eq!(tool_prompt(&[]), "");
234 let p = tool_prompt(&[ToolDesc { name: "t".into(), description: "does t".into(), schema: serde_json::json!({"type": "object"}) }]);
235 assert!(p.contains("- t: does t {\"type\":\"object\"}"));
236 assert_eq!(result_text("t", "ok", true), "<tool_result name=\"t\" error=\"true\">ok</tool_result>");
237 }
238}