1use std::collections::HashSet;
31
32use adk_core::Part;
33
34pub fn contains_tool_call_tag(text: &str) -> bool {
36 text.contains("<tool_call>")
37 || text.contains("<|tool_call>")
38 || text.contains("<|python_tag|>")
39 || text.contains("[TOOL_CALLS]")
40 || text.contains("<|tool▁call")
41 || text.contains("<|action_start|>")
42 || (text.contains("```json") && text.contains("\"name\""))
43}
44
45pub fn parse_text_tool_calls(text: &str) -> Option<Vec<Part>> {
53 if !contains_tool_call_tag(text) {
54 return None;
55 }
56
57 let mut parts = Vec::new();
58
59 if let Some(parsed) = parse_qwen_format(text, &mut parts) {
61 return Some(parsed);
62 }
63
64 if let Some(parsed) = parse_llama_format(text, &mut parts) {
66 return Some(parsed);
67 }
68
69 if let Some(parsed) = parse_mistral_nemo_format(text, &mut parts) {
71 return Some(parsed);
72 }
73
74 if let Some(parsed) = parse_deepseek_native_format(text) {
76 return Some(parsed);
77 }
78
79 if let Some(parsed) = parse_deepseek_format(text) {
81 return Some(parsed);
82 }
83
84 if let Some(parsed) = parse_gemma4_format(text) {
86 return Some(parsed);
87 }
88
89 if let Some(parsed) = parse_action_tag_format(text) {
91 return Some(parsed);
92 }
93
94 None
95}
96
97pub fn parse_declared_tool_calls(
121 text: &str,
122 declared_tools: &HashSet<String>,
123) -> Option<Vec<Part>> {
124 if declared_tools.is_empty() {
125 return None;
126 }
127 let parts = parse_text_tool_calls(text)?;
128 let all_declared = parts.iter().all(|part| match part {
129 Part::FunctionCall { name, .. } => declared_tools.contains(name),
130 _ => true,
131 });
132 let has_call = parts.iter().any(|part| matches!(part, Part::FunctionCall { .. }));
133 (all_declared && has_call).then_some(parts)
134}
135
136fn parse_qwen_format(text: &str, _parts: &mut Vec<Part>) -> Option<Vec<Part>> {
142 let mut result = Vec::new();
143 let mut remaining = text;
144
145 loop {
146 let start = remaining.find("<tool_call>")?;
147
148 let before = &remaining[..start];
150 if !before.is_empty() {
151 result.push(Part::Text { text: before.to_string() });
152 }
153
154 let after_open = &remaining[start + "<tool_call>".len()..];
155 let end = after_open.find("</tool_call>")?;
156 let inner = after_open[..end].trim();
157
158 if let Some(part) = parse_json_tool_call(inner) {
160 result.push(part);
161 }
162 else if let Some(part) = parse_function_tag(inner) {
164 result.push(part);
165 } else {
166 result.push(Part::Text {
168 text: remaining[start..start + "<tool_call>".len() + end + "</tool_call>".len()]
169 .to_string(),
170 });
171 }
172
173 remaining = &after_open[end + "</tool_call>".len()..];
174 if remaining.trim().is_empty() || !remaining.contains("<tool_call>") {
175 let trailing = remaining;
176 if !trailing.is_empty() {
177 result.push(Part::Text { text: trailing.to_string() });
178 }
179 break;
180 }
181 }
182
183 if result.is_empty() { None } else { Some(result) }
184}
185
186fn parse_function_tag(inner: &str) -> Option<Part> {
188 let func_start = inner.find("<function=")?;
189 let after_eq = &inner[func_start + "<function=".len()..];
190 let name_end = after_eq.find('>')?;
191 let name = after_eq[..name_end].trim().to_string();
192
193 let body_start = name_end + 1;
194 let func_end = after_eq.find("</function>")?;
195 let body = after_eq[body_start..func_end].trim();
196
197 let args = if body.is_empty() {
198 serde_json::json!({})
199 } else {
200 serde_json::from_str(body).unwrap_or_else(|_| serde_json::json!({}))
201 };
202
203 Some(Part::FunctionCall { name, args, id: None, thought_signature: None })
204}
205
206fn parse_json_tool_call(json_str: &str) -> Option<Part> {
209 let value: serde_json::Value = serde_json::from_str(json_str).ok()?;
210 let obj = value.as_object()?;
211
212 let name =
213 obj.get("name").or_else(|| obj.get("function")).and_then(|v| v.as_str())?.to_string();
214
215 let args = obj
216 .get("arguments")
217 .or_else(|| obj.get("parameters"))
218 .cloned()
219 .unwrap_or(serde_json::json!({}));
220
221 Some(Part::FunctionCall { name, args, id: None, thought_signature: None })
222}
223
224fn parse_llama_format(text: &str, _parts: &mut Vec<Part>) -> Option<Vec<Part>> {
226 let tag = "<|python_tag|>";
227 let start = text.find(tag)?;
228
229 let mut result = Vec::new();
230 let before = &text[..start];
231 if !before.is_empty() {
232 result.push(Part::Text { text: before.to_string() });
233 }
234
235 let json_str = text[start + tag.len()..].trim();
236 if let Some(part) = parse_json_tool_call(json_str) {
237 result.push(part);
238 } else {
239 return None;
240 }
241
242 Some(result)
243}
244
245fn parse_mistral_nemo_format(text: &str, _parts: &mut Vec<Part>) -> Option<Vec<Part>> {
247 let tag = "[TOOL_CALLS]";
248 let start = text.find(tag)?;
249
250 let mut result = Vec::new();
251 let before = &text[..start];
252 if !before.is_empty() {
253 result.push(Part::Text { text: before.to_string() });
254 }
255
256 let json_str = text[start + tag.len()..].trim();
257 let arr: Vec<serde_json::Value> = serde_json::from_str(json_str).ok()?;
259 for item in &arr {
260 let obj = item.as_object()?;
261 let name = obj.get("name").and_then(|v| v.as_str())?.to_string();
262 let args = obj
263 .get("arguments")
264 .or_else(|| obj.get("parameters"))
265 .cloned()
266 .unwrap_or(serde_json::json!({}));
267 result.push(Part::FunctionCall { name, args, id: None, thought_signature: None });
268 }
269
270 if result.is_empty() { None } else { Some(result) }
271}
272
273const DEEPSEEK_END_MARKERS: &[&str] = &[DEEPSEEK_CALL_END, DEEPSEEK_CALLS_END];
275
276fn parse_deepseek_format(text: &str) -> Option<Vec<Part>> {
283 let fence_start = text.find("```json")?;
284 let json_start = fence_start + "```json".len();
285 let after_fence = &text[json_start..];
286 let fence_end = after_fence.find("```")?;
287 let json_str = after_fence[..fence_end].trim();
288
289 let value: serde_json::Value = serde_json::from_str(json_str).ok()?;
290 let calls = match &value {
291 serde_json::Value::Array(items) => {
292 items.iter().map(parse_fenced_tool_call).collect::<Option<Vec<_>>>()?
293 }
294 object => vec![parse_fenced_tool_call(object)?],
295 };
296 if calls.is_empty() {
297 return None;
298 }
299
300 let mut result = Vec::new();
301 let before = &text[..fence_start];
302 if !before.is_empty() {
303 result.push(Part::Text { text: before.to_string() });
304 }
305 result.extend(calls);
306
307 let mut trailing = &after_fence[fence_end + "```".len()..];
308 while let Some(rest) =
309 DEEPSEEK_END_MARKERS.iter().find_map(|m| trailing.trim_start().strip_prefix(m))
310 {
311 trailing = rest;
312 }
313 if !trailing.is_empty() {
314 result.push(Part::Text { text: trailing.to_string() });
315 }
316
317 Some(result)
318}
319
320const DEEPSEEK_CALLS_BEGIN: &str = "<\u{ff5c}tool\u{2581}calls\u{2581}begin\u{ff5c}>";
321const DEEPSEEK_CALL_BEGIN: &str = "<\u{ff5c}tool\u{2581}call\u{2581}begin\u{ff5c}>";
322const DEEPSEEK_SEP: &str = "<\u{ff5c}tool\u{2581}sep\u{ff5c}>";
323const DEEPSEEK_CALL_END: &str = "<\u{ff5c}tool\u{2581}call\u{2581}end\u{ff5c}>";
324const DEEPSEEK_CALLS_END: &str = "<\u{ff5c}tool\u{2581}calls\u{2581}end\u{ff5c}>";
325
326fn parse_deepseek_native_format(text: &str) -> Option<Vec<Part>> {
334 let first_call = text.find(DEEPSEEK_CALL_BEGIN)?;
335 let start = text[..first_call].rfind(DEEPSEEK_CALLS_BEGIN).unwrap_or(first_call);
336 let mut result = Vec::new();
337 if !text[..start].trim().is_empty() {
338 result.push(Part::Text { text: text[..start].to_string() });
339 }
340
341 let mut rest = &text[first_call..];
342 while let Some(begin) = rest.find(DEEPSEEK_CALL_BEGIN) {
343 let body = &rest[begin + DEEPSEEK_CALL_BEGIN.len()..];
344 let end = [DEEPSEEK_CALL_END, DEEPSEEK_CALLS_END, DEEPSEEK_CALL_BEGIN]
345 .iter()
346 .filter_map(|marker| body.find(marker))
347 .min()
348 .unwrap_or(body.len());
349 let (head, arguments) = body[..end].split_once(DEEPSEEK_SEP)?;
350 let (name, arguments) = if head.trim() == "function" {
351 let (name, arguments) = arguments.split_once('\n').unwrap_or((arguments, ""));
352 (name.trim(), arguments)
353 } else {
354 (head.trim(), arguments)
355 };
356 let arguments = arguments.trim();
357 let arguments = arguments
358 .strip_prefix("```json")
359 .or_else(|| arguments.strip_prefix("```"))
360 .map(|fenced| fenced.trim_end().trim_end_matches("```"))
361 .unwrap_or(arguments);
362 let args: serde_json::Value = serde_json::from_str(arguments.trim()).ok()?;
363 if name.is_empty() || !args.is_object() {
364 return None;
365 }
366 result.push(Part::FunctionCall {
367 name: name.to_string(),
368 args,
369 id: None,
370 thought_signature: None,
371 });
372 rest = body[end..].strip_prefix(DEEPSEEK_CALL_END).unwrap_or(&body[end..]);
373 }
374
375 let trailing = rest.trim_start().strip_prefix(DEEPSEEK_CALLS_END).unwrap_or(rest);
376 if !trailing.trim().is_empty() {
377 result.push(Part::Text { text: trailing.to_string() });
378 }
379 Some(result)
380}
381
382fn parse_fenced_tool_call(value: &serde_json::Value) -> Option<Part> {
385 let obj = value.as_object()?;
386 let name = obj.get("name").or_else(|| obj.get("function")).and_then(|v| v.as_str())?;
387 let args = obj.get("arguments").or_else(|| obj.get("parameters")).filter(|v| v.is_object())?;
388 Some(Part::FunctionCall {
389 name: name.to_string(),
390 args: args.clone(),
391 id: None,
392 thought_signature: None,
393 })
394}
395
396fn parse_gemma4_format(text: &str) -> Option<Vec<Part>> {
401 let mut result = Vec::new();
402 let mut remaining = text;
403
404 loop {
405 let start = remaining.find("<|tool_call>")?;
406 let before = &remaining[..start];
407 if !before.is_empty() {
408 result.push(Part::Text { text: before.to_string() });
409 }
410
411 let after_open = &remaining[start + "<|tool_call>".len()..];
412 let end = after_open.find("<tool_call|>")?;
413 let inner = after_open[..end].trim();
414
415 if let Some(call_body) = inner.strip_prefix("call:") {
417 let brace_start = call_body.find('{');
418 let name = if let Some(bs) = brace_start {
419 call_body[..bs].trim().to_string()
420 } else {
421 call_body.trim().to_string()
422 };
423
424 let args = if let Some(bs) = brace_start {
425 let args_raw = &call_body[bs..];
426 let json_str = args_raw.replace("<|\"|>", "\"");
428 serde_json::from_str(&json_str).unwrap_or(serde_json::json!({}))
429 } else {
430 serde_json::json!({})
431 };
432
433 result.push(Part::FunctionCall { name, args, id: None, thought_signature: None });
434 }
435
436 remaining = &after_open[end + "<tool_call|>".len()..];
437 if remaining.trim().is_empty() || !remaining.contains("<|tool_call>") {
438 let trailing = remaining;
439 if !trailing.is_empty() {
440 result.push(Part::Text { text: trailing.to_string() });
441 }
442 break;
443 }
444 }
445
446 if result.is_empty() { None } else { Some(result) }
447}
448
449fn parse_action_tag_format(text: &str) -> Option<Vec<Part>> {
454 let start_tag = "<|action_start|>";
455 let end_tag = "<|action_end|>";
456
457 let start = text.find(start_tag)?;
458 let mut result = Vec::new();
459
460 let before = &text[..start];
461 if !before.is_empty() {
462 result.push(Part::Text { text: before.to_string() });
463 }
464
465 let after_open = &text[start + start_tag.len()..];
466 let end = after_open.find(end_tag)?;
467 let inner = after_open[..end].trim();
468
469 if let Some(part) = parse_json_tool_call(inner) {
470 result.push(part);
471 } else {
472 return None;
473 }
474
475 let trailing = &after_open[end + end_tag.len()..];
476 if !trailing.is_empty() {
477 result.push(Part::Text { text: trailing.to_string() });
478 }
479
480 Some(result)
481}
482
483const TOOL_CALL_PREFIXES: &[&str] = &[
487 "<tool_call",
488 "<|tool_call>",
489 "<|python_tag|",
490 "[TOOL_CALLS]",
491 "<|action_start|>",
492 "<\u{ff5c}tool", ];
494
495const MAX_BUFFER_SIZE: usize = 4096;
497
498pub struct ToolCallBuffer {
521 buffer: String,
522 buffering: bool,
523 declared_tools: Option<HashSet<String>>,
525}
526
527pub enum BufferAction {
529 Emit(Vec<Part>),
531 Buffering,
533}
534
535impl ToolCallBuffer {
536 pub fn new() -> Self {
538 Self { buffer: String::new(), buffering: false, declared_tools: None }
539 }
540
541 pub fn for_declared_tools(declared_tools: HashSet<String>) -> Self {
562 Self { buffer: String::new(), buffering: false, declared_tools: Some(declared_tools) }
563 }
564
565 pub fn push(&mut self, text: &str) -> BufferAction {
570 self.buffer.push_str(text);
571
572 if self.declared_tools.as_ref().is_some_and(HashSet::is_empty) {
573 return self.flush_as_emit();
574 }
575
576 if self.buffering {
577 if self.has_complete_tool_call() {
579 return self.try_parse_and_emit();
580 }
581 if !self.starts_tool_call_prefix() && !self.has_partial_prefix() {
583 return self.flush_as_emit();
584 }
585 if self.buffer.len() > MAX_BUFFER_SIZE {
587 return self.flush_as_emit();
588 }
589 BufferAction::Buffering
590 } else {
591 if self.starts_tool_call_prefix() {
593 self.buffering = true;
594 if self.has_complete_tool_call() {
596 return self.try_parse_and_emit();
597 }
598 BufferAction::Buffering
599 } else if self.has_partial_prefix() {
600 self.buffering = true;
602 BufferAction::Buffering
603 } else {
604 self.flush_as_emit()
606 }
607 }
608 }
609
610 pub fn flush(&mut self) -> Vec<Part> {
613 if self.buffer.is_empty() {
614 return Vec::new();
615 }
616
617 if let Some(parts) = self.parse_buffer() {
619 self.buffer.clear();
620 self.buffering = false;
621 return parts;
622 }
623
624 let text = std::mem::take(&mut self.buffer);
626 self.buffering = false;
627 if text.is_empty() { Vec::new() } else { vec![Part::Text { text }] }
628 }
629
630 fn parse_buffer(&self) -> Option<Vec<Part>> {
631 match &self.declared_tools {
632 Some(declared_tools) => parse_declared_tool_calls(&self.buffer, declared_tools),
633 None => parse_text_tool_calls(&self.buffer),
634 }
635 }
636
637 fn starts_tool_call_prefix(&self) -> bool {
638 TOOL_CALL_PREFIXES.iter().any(|prefix| self.buffer.contains(prefix))
639 }
640
641 fn has_partial_prefix(&self) -> bool {
642 let buf = &self.buffer;
644 for prefix in TOOL_CALL_PREFIXES {
645 let prefix_chars: Vec<char> = prefix.chars().collect();
647 for i in 1..prefix_chars.len() {
648 let partial: String = prefix_chars[..i].iter().collect();
649 if buf.ends_with(&partial) {
650 return true;
651 }
652 }
653 }
654 false
655 }
656
657 fn has_complete_tool_call(&self) -> bool {
658 if self.buffer.contains(DEEPSEEK_CALL_BEGIN) {
660 return self.buffer.contains(DEEPSEEK_CALLS_END);
661 }
662 (self.buffer.contains("<tool_call>") && self.buffer.contains("</tool_call>"))
663 || (self.buffer.contains("<|tool_call>") && self.buffer.contains("<tool_call|>"))
664 || (self.buffer.contains("<|python_tag|>")
665 && self.buffer.contains('\n')
666 && self.buffer.len() > "<|python_tag|>".len() + 5)
667 || (self.buffer.contains("[TOOL_CALLS]")
668 && self.buffer.contains(']')
669 && self.buffer.rfind(']') > self.buffer.find("[TOOL_CALLS]").map(|i| i + 12))
670 || (self.buffer.contains("```json") && self.buffer.matches("```").count() >= 2)
671 || (self.buffer.contains("<|action_start|>") && self.buffer.contains("<|action_end|>"))
672 }
673
674 fn try_parse_and_emit(&mut self) -> BufferAction {
675 if let Some(parts) = self.parse_buffer() {
676 self.buffer.clear();
677 self.buffering = false;
678 BufferAction::Emit(parts)
679 } else {
680 self.flush_as_emit()
682 }
683 }
684
685 fn flush_as_emit(&mut self) -> BufferAction {
686 let text = std::mem::take(&mut self.buffer);
687 self.buffering = false;
688 if text.is_empty() {
689 BufferAction::Emit(Vec::new())
690 } else {
691 BufferAction::Emit(vec![Part::Text { text }])
692 }
693 }
694}
695
696impl Default for ToolCallBuffer {
697 fn default() -> Self {
698 Self::new()
699 }
700}
701
702#[cfg(test)]
703mod tests {
704 use super::*;
705
706 #[test]
707 fn test_qwen_json_format() {
708 let text =
709 r#"<tool_call>{"name": "get_weather", "arguments": {"city": "Tokyo"}}</tool_call>"#;
710 let parts = parse_text_tool_calls(text).unwrap();
711 assert_eq!(parts.len(), 1);
712 match &parts[0] {
713 Part::FunctionCall { name, args, .. } => {
714 assert_eq!(name, "get_weather");
715 assert_eq!(args["city"], "Tokyo");
716 }
717 _ => panic!("expected FunctionCall"),
718 }
719 }
720
721 #[test]
722 fn test_qwen_function_tag_format() {
723 let text = r#"<tool_call><function=screenshot></function></tool_call>"#;
724 let parts = parse_text_tool_calls(text).unwrap();
725 assert_eq!(parts.len(), 1);
726 match &parts[0] {
727 Part::FunctionCall { name, args, .. } => {
728 assert_eq!(name, "screenshot");
729 assert_eq!(*args, serde_json::json!({}));
730 }
731 _ => panic!("expected FunctionCall"),
732 }
733 }
734
735 #[test]
736 fn test_qwen_function_tag_with_args() {
737 let text = r#"<tool_call><function=get_weather>{"city": "Tokyo"}</function></tool_call>"#;
738 let parts = parse_text_tool_calls(text).unwrap();
739 assert_eq!(parts.len(), 1);
740 match &parts[0] {
741 Part::FunctionCall { name, args, .. } => {
742 assert_eq!(name, "get_weather");
743 assert_eq!(args["city"], "Tokyo");
744 }
745 _ => panic!("expected FunctionCall"),
746 }
747 }
748
749 #[test]
750 fn test_text_before_tool_call() {
751 let text = r#"Let me check that for you.
752<tool_call>{"name": "search", "arguments": {"query": "rust"}}</tool_call>"#;
753 let parts = parse_text_tool_calls(text).unwrap();
754 assert_eq!(parts.len(), 2);
755 assert!(matches!(&parts[0], Part::Text { text } if text.contains("check that")));
756 assert!(matches!(&parts[1], Part::FunctionCall { name, .. } if name == "search"));
757 }
758
759 #[test]
760 fn test_multiple_tool_calls() {
761 let text = r#"<tool_call>{"name": "a", "arguments": {}}</tool_call>
766<tool_call>{"name": "b", "arguments": {"x": 1}}</tool_call>"#;
767 let parts = parse_text_tool_calls(text).unwrap();
768 assert_eq!(parts.len(), 3);
769 assert!(matches!(&parts[0], Part::FunctionCall { name, .. } if name == "a"));
770 assert!(matches!(&parts[1], Part::Text { text } if text == "\n"));
771 assert!(matches!(&parts[2], Part::FunctionCall { name, .. } if name == "b"));
772 }
773
774 #[test]
775 fn test_llama_format() {
776 let text = r#"<|python_tag|>{"name": "get_weather", "parameters": {"city": "NYC"}}"#;
777 let parts = parse_text_tool_calls(text).unwrap();
778 assert_eq!(parts.len(), 1);
779 match &parts[0] {
780 Part::FunctionCall { name, args, .. } => {
781 assert_eq!(name, "get_weather");
782 assert_eq!(args["city"], "NYC");
783 }
784 _ => panic!("expected FunctionCall"),
785 }
786 }
787
788 #[test]
789 fn test_mistral_nemo_format() {
790 let text = r#"[TOOL_CALLS][{"name": "search", "arguments": {"q": "rust"}}]"#;
791 let parts = parse_text_tool_calls(text).unwrap();
792 assert_eq!(parts.len(), 1);
793 match &parts[0] {
794 Part::FunctionCall { name, args, .. } => {
795 assert_eq!(name, "search");
796 assert_eq!(args["q"], "rust");
797 }
798 _ => panic!("expected FunctionCall"),
799 }
800 }
801
802 #[test]
803 fn test_no_tool_call_returns_none() {
804 assert!(parse_text_tool_calls("Hello, how can I help?").is_none());
805 assert!(parse_text_tool_calls("").is_none());
806 }
807
808 #[test]
809 fn test_contains_tool_call_tag() {
810 assert!(contains_tool_call_tag("<tool_call>"));
811 assert!(contains_tool_call_tag("text <tool_call> more"));
812 assert!(contains_tool_call_tag("<|python_tag|>"));
813 assert!(contains_tool_call_tag("[TOOL_CALLS]"));
814 assert!(!contains_tool_call_tag("normal text"));
815 }
816
817 #[test]
820 fn test_buffer_normal_text_emits_immediately() {
821 let mut buf = ToolCallBuffer::new();
822 match buf.push("Hello world") {
823 BufferAction::Emit(parts) => {
824 assert_eq!(parts.len(), 1);
825 assert!(matches!(&parts[0], Part::Text { text } if text == "Hello world"));
826 }
827 BufferAction::Buffering => panic!("should emit immediately"),
828 }
829 }
830
831 #[test]
832 fn test_buffer_complete_tool_call_in_one_chunk() {
833 let mut buf = ToolCallBuffer::new();
834 let text = r#"<tool_call>{"name": "search", "arguments": {"q": "rust"}}</tool_call>"#;
835 match buf.push(text) {
836 BufferAction::Emit(parts) => {
837 assert_eq!(parts.len(), 1);
838 assert!(matches!(&parts[0], Part::FunctionCall { name, .. } if name == "search"));
839 }
840 BufferAction::Buffering => panic!("should emit parsed tool call"),
841 }
842 }
843
844 #[test]
845 fn test_buffer_tool_call_split_across_chunks() {
846 let mut buf = ToolCallBuffer::new();
847
848 assert!(matches!(buf.push("<tool_call>"), BufferAction::Buffering));
850
851 assert!(matches!(
853 buf.push(r#"{"name": "get_weather", "arguments": {"city": "Tokyo"}}"#),
854 BufferAction::Buffering
855 ));
856
857 match buf.push("</tool_call>") {
859 BufferAction::Emit(parts) => {
860 assert_eq!(parts.len(), 1);
861 assert!(
862 matches!(&parts[0], Part::FunctionCall { name, .. } if name == "get_weather")
863 );
864 }
865 BufferAction::Buffering => panic!("should emit after closing tag"),
866 }
867 }
868
869 #[test]
870 fn test_buffer_text_then_tool_call() {
871 let mut buf = ToolCallBuffer::new();
872
873 match buf.push("Let me check. ") {
875 BufferAction::Emit(parts) => {
876 assert_eq!(parts.len(), 1);
877 assert!(matches!(&parts[0], Part::Text { .. }));
878 }
879 BufferAction::Buffering => panic!("should emit text"),
880 }
881
882 let tc = r#"<tool_call>{"name": "search", "arguments": {}}</tool_call>"#;
884 match buf.push(tc) {
885 BufferAction::Emit(parts) => {
886 assert_eq!(parts.len(), 1);
887 assert!(matches!(&parts[0], Part::FunctionCall { name, .. } if name == "search"));
888 }
889 BufferAction::Buffering => panic!("should emit tool call"),
890 }
891 }
892
893 #[test]
894 fn test_buffer_flush_incomplete_as_text() {
895 let mut buf = ToolCallBuffer::new();
896 assert!(matches!(buf.push("<tool_call>partial"), BufferAction::Buffering));
897
898 let parts = buf.flush();
900 assert_eq!(parts.len(), 1);
901 assert!(matches!(&parts[0], Part::Text { text } if text.contains("<tool_call>")));
902 }
903
904 #[test]
905 fn test_buffer_flush_empty() {
906 let mut buf = ToolCallBuffer::new();
907 let parts = buf.flush();
908 assert!(parts.is_empty());
909 }
910
911 #[test]
912 fn test_buffer_partial_prefix_detection() {
913 let mut buf = ToolCallBuffer::new();
914 assert!(matches!(buf.push("<tool"), BufferAction::Buffering));
916 assert!(matches!(buf.push("_call>"), BufferAction::Buffering));
918 match buf.push(r#"{"name":"x","arguments":{}}</tool_call>"#) {
920 BufferAction::Emit(parts) => {
921 assert_eq!(parts.len(), 1);
922 assert!(matches!(&parts[0], Part::FunctionCall { name, .. } if name == "x"));
923 }
924 BufferAction::Buffering => panic!("should emit"),
925 }
926 }
927
928 #[test]
929 fn test_buffer_markdown_link_is_not_mistaken_for_tool_call() {
930 let mut buf = ToolCallBuffer::new();
931
932 assert!(matches!(buf.push("["), BufferAction::Buffering));
933
934 match buf.push("documentation](https://example.com) trailing text") {
935 BufferAction::Emit(parts) => {
936 assert_eq!(
937 parts,
938 vec trailing text".to_string()
940 }]
941 );
942 }
943 BufferAction::Buffering => panic!("markdown link must not stay buffered"),
944 }
945
946 assert!(buf.flush().is_empty());
947 }
948
949 #[test]
950 fn test_buffer_mistral_prefix_can_still_span_chunks() {
951 let mut buf = ToolCallBuffer::new();
952
953 assert!(matches!(buf.push("["), BufferAction::Buffering));
954 assert!(matches!(buf.push("TOOL"), BufferAction::Buffering));
955
956 match buf.push(r#"_CALLS][{"name":"search","arguments":{"q":"rust"}}]"#) {
957 BufferAction::Emit(parts) => {
958 assert_eq!(parts.len(), 1);
959 assert!(matches!(
960 &parts[0],
961 Part::FunctionCall { name, .. } if name == "search"
962 ));
963 }
964 BufferAction::Buffering => panic!("should emit parsed tool call"),
965 }
966 }
967
968 #[test]
971 fn test_deepseek_json_fence() {
972 let text = "```json\n{\"name\": \"search\", \"arguments\": {\"q\": \"rust\"}}\n```";
973 let parts = parse_text_tool_calls(text).unwrap();
974 assert_eq!(parts.len(), 1);
975 match &parts[0] {
976 Part::FunctionCall { name, args, .. } => {
977 assert_eq!(name, "search");
978 assert_eq!(args["q"], "rust");
979 }
980 _ => panic!("expected FunctionCall"),
981 }
982 }
983
984 #[test]
985 fn test_deepseek_with_text_before() {
986 let text = "I'll search for that.\n```json\n{\"name\": \"search\", \"arguments\": {\"q\": \"rust\"}}\n```\n<|tool▁call▁end|>";
987 let parts = parse_text_tool_calls(text).unwrap();
988 assert!(!parts.is_empty());
989 let has_fn_call =
990 parts.iter().any(|p| matches!(p, Part::FunctionCall { name, .. } if name == "search"));
991 assert!(has_fn_call);
992 }
993
994 fn declared(names: &[&str]) -> HashSet<String> {
995 names.iter().map(|name| (*name).to_string()).collect()
996 }
997
998 #[test]
999 fn json_example_without_declared_tools_stays_text() {
1000 let text = "Here is the record:\n```json\n{\"name\":\"Alice\",\"age\":30}\n```\nDone.";
1001
1002 assert_eq!(parse_declared_tool_calls(text, &declared(&[])), None);
1003 }
1004
1005 #[test]
1006 fn json_example_with_other_declared_tool_stays_text() {
1007 let text = "Here is the record:\n```json\n{\"name\":\"Alice\",\"age\":30}\n```\nDone.";
1008
1009 assert_eq!(parse_declared_tool_calls(text, &declared(&["lookup"])), None);
1010 assert_eq!(parse_text_tool_calls(text), None);
1012 }
1013
1014 #[test]
1015 fn fenced_call_to_undeclared_tool_stays_text() {
1016 let text = "```json\n{\"name\":\"delete_all\",\"arguments\":{}}\n```";
1017
1018 assert_eq!(parse_declared_tool_calls(text, &declared(&["lookup"])), None);
1019 }
1020
1021 #[test]
1022 fn fenced_call_to_declared_tool_parses_and_keeps_trailing_text() {
1023 let text = "Checking.\n```json\n{\"name\":\"lookup\",\"arguments\":{\"id\":7}}\n```\nI will report back.";
1024
1025 assert_eq!(
1026 parse_declared_tool_calls(text, &declared(&["lookup"])),
1027 Some(vec![
1028 Part::Text { text: "Checking.\n".to_string() },
1029 Part::FunctionCall {
1030 name: "lookup".to_string(),
1031 args: serde_json::json!({"id": 7}),
1032 id: None,
1033 thought_signature: None,
1034 },
1035 Part::Text { text: "\nI will report back.".to_string() },
1036 ])
1037 );
1038 }
1039
1040 #[test]
1041 fn deepseek_end_marker_is_not_kept_as_text() {
1042 let text = "```json\n{\"name\":\"lookup\",\"arguments\":{}}\n```\n<|tool▁call▁end|>";
1043
1044 assert_eq!(
1045 parse_text_tool_calls(text),
1046 Some(vec![Part::FunctionCall {
1047 name: "lookup".to_string(),
1048 args: serde_json::json!({}),
1049 id: None,
1050 thought_signature: None,
1051 }])
1052 );
1053 }
1054
1055 #[test]
1056 fn declared_buffer_keeps_undeclared_calls_as_text() {
1057 let text = "<tool_call>{\"name\":\"rm\",\"arguments\":{}}</tool_call>";
1058 let mut buffer = ToolCallBuffer::for_declared_tools(declared(&["lookup"]));
1059
1060 let BufferAction::Emit(parts) = buffer.push(text) else {
1061 panic!("a complete tag is resolved immediately");
1062 };
1063 assert_eq!(parts, vec![Part::Text { text: text.to_string() }]);
1064 }
1065
1066 #[test]
1069 fn test_gemma4_simple() {
1070 let text = "<|tool_call>call:get_weather{}<tool_call|>";
1071 let parts = parse_text_tool_calls(text).unwrap();
1072 assert_eq!(parts.len(), 1);
1073 match &parts[0] {
1074 Part::FunctionCall { name, .. } => assert_eq!(name, "get_weather"),
1075 _ => panic!("expected FunctionCall"),
1076 }
1077 }
1078
1079 #[test]
1080 fn test_gemma4_with_args() {
1081 let text = "<|tool_call>call:get_weather{<|\"|>city<|\"|>:<|\"|>Tokyo<|\"|>}<tool_call|>";
1082 let parts = parse_text_tool_calls(text).unwrap();
1083 assert_eq!(parts.len(), 1);
1084 match &parts[0] {
1085 Part::FunctionCall { name, args, .. } => {
1086 assert_eq!(name, "get_weather");
1087 assert_eq!(args["city"], "Tokyo");
1088 }
1089 _ => panic!("expected FunctionCall"),
1090 }
1091 }
1092
1093 #[test]
1096 fn test_action_tags() {
1097 let text = "<|action_start|>{\"name\": \"search\", \"arguments\": {\"q\": \"rust\"}}<|action_end|>";
1098 let parts = parse_text_tool_calls(text).unwrap();
1099 assert_eq!(parts.len(), 1);
1100 match &parts[0] {
1101 Part::FunctionCall { name, args, .. } => {
1102 assert_eq!(name, "search");
1103 assert_eq!(args["q"], "rust");
1104 }
1105 _ => panic!("expected FunctionCall"),
1106 }
1107 }
1108
1109 #[test]
1110 fn test_action_tags_with_surrounding_text() {
1111 let text = "Let me look that up. <|action_start|>{\"name\": \"search\", \"arguments\": {}}<|action_end|> Done.";
1112 let parts = parse_text_tool_calls(text).unwrap();
1113 assert!(parts.len() >= 2); let has_fn_call =
1115 parts.iter().any(|p| matches!(p, Part::FunctionCall { name, .. } if name == "search"));
1116 assert!(has_fn_call);
1117 }
1118
1119 fn stream_and_reconstruct(deltas: &[&str]) -> String {
1124 let mut buf = ToolCallBuffer::new();
1125 let mut out = String::new();
1126 let mut collect = |parts: Vec<Part>| {
1127 for part in parts {
1128 if let Part::Text { text } = part {
1129 out.push_str(&text);
1130 }
1131 }
1132 };
1133 for delta in deltas {
1134 if let BufferAction::Emit(parts) = buf.push(delta) {
1135 collect(parts);
1136 }
1137 }
1138 collect(buf.flush());
1139 out
1140 }
1141
1142 #[test]
1143 fn test_regression_markdown_structure_reconstructs() {
1144 let reconstructed =
1147 stream_and_reconstruct(&["Heading", "\n\n", "- first", "\n", "- second"]);
1148 assert_eq!(reconstructed, "Heading\n\n- first\n- second");
1149 }
1150
1151 #[test]
1152 fn test_regression_single_space_reconstructs() {
1153 let reconstructed = stream_and_reconstruct(&["Hello", " ", "world"]);
1156 assert_eq!(reconstructed, "Hello world");
1157 }
1158
1159 #[test]
1160 fn test_flush_as_emit_whitespace_only_emits_text() {
1161 let mut buf = ToolCallBuffer::new();
1164 match buf.push("\n\n") {
1165 BufferAction::Emit(parts) => {
1166 assert_eq!(parts.len(), 1);
1167 assert!(matches!(&parts[0], Part::Text { text } if text == "\n\n"));
1168 }
1169 BufferAction::Buffering => panic!("whitespace-only delta should emit"),
1170 }
1171 }
1172
1173 #[test]
1174 fn test_flush_whitespace_only_emits_text() {
1175 let mut buf = ToolCallBuffer::new();
1178 buf.buffer.push_str(" \n\t");
1181 buf.buffering = true;
1182 let parts = buf.flush();
1183 assert_eq!(parts.len(), 1);
1184 assert!(matches!(&parts[0], Part::Text { text } if text == " \n\t"));
1185 }
1186
1187 #[test]
1190 fn test_boundary_whitespace_qwen_preserved() {
1191 let text = "lead \n<tool_call> {\"name\": \"search\", \"arguments\": {\"q\": \"rust\"}} </tool_call>\n trail";
1194 let parts = parse_text_tool_calls(text).unwrap();
1195 assert_eq!(parts.len(), 3);
1196 assert!(matches!(&parts[0], Part::Text { text } if text == "lead \n"));
1197 match &parts[1] {
1198 Part::FunctionCall { name, args, .. } => {
1199 assert_eq!(name, "search");
1200 assert_eq!(args["q"], "rust");
1201 }
1202 _ => panic!("expected FunctionCall"),
1203 }
1204 assert!(matches!(&parts[2], Part::Text { text } if text == "\n trail"));
1205 }
1206
1207 #[test]
1208 fn test_boundary_whitespace_llama_preserved() {
1209 let text = "pre \n<|python_tag|> {\"name\": \"get_weather\", \"parameters\": {\"city\": \"NYC\"}}";
1210 let parts = parse_text_tool_calls(text).unwrap();
1211 assert_eq!(parts.len(), 2);
1212 assert!(matches!(&parts[0], Part::Text { text } if text == "pre \n"));
1213 match &parts[1] {
1214 Part::FunctionCall { name, args, .. } => {
1215 assert_eq!(name, "get_weather");
1216 assert_eq!(args["city"], "NYC");
1217 }
1218 _ => panic!("expected FunctionCall"),
1219 }
1220 }
1221
1222 #[test]
1223 fn test_boundary_whitespace_mistral_nemo_preserved() {
1224 let text = "pre \n[TOOL_CALLS] [{\"name\": \"search\", \"arguments\": {\"q\": \"rust\"}}]";
1225 let parts = parse_text_tool_calls(text).unwrap();
1226 assert_eq!(parts.len(), 2);
1227 assert!(matches!(&parts[0], Part::Text { text } if text == "pre \n"));
1228 match &parts[1] {
1229 Part::FunctionCall { name, args, .. } => {
1230 assert_eq!(name, "search");
1231 assert_eq!(args["q"], "rust");
1232 }
1233 _ => panic!("expected FunctionCall"),
1234 }
1235 }
1236
1237 #[test]
1238 fn test_boundary_whitespace_deepseek_preserved() {
1239 let text = "pre \n```json\n{\"name\": \"search\", \"arguments\": {\"q\": \"rust\"}}\n```";
1240 let parts = parse_text_tool_calls(text).unwrap();
1241 assert_eq!(parts.len(), 2);
1242 assert!(matches!(&parts[0], Part::Text { text } if text == "pre \n"));
1243 match &parts[1] {
1244 Part::FunctionCall { name, args, .. } => {
1245 assert_eq!(name, "search");
1246 assert_eq!(args["q"], "rust");
1247 }
1248 _ => panic!("expected FunctionCall"),
1249 }
1250 }
1251
1252 #[test]
1253 fn test_boundary_whitespace_gemma4_preserved() {
1254 let text = "pre \n<|tool_call>call:get_weather{<|\"|>city<|\"|>:<|\"|>Tokyo<|\"|>}<tool_call|>\n post";
1255 let parts = parse_text_tool_calls(text).unwrap();
1256 assert_eq!(parts.len(), 3);
1257 assert!(matches!(&parts[0], Part::Text { text } if text == "pre \n"));
1258 match &parts[1] {
1259 Part::FunctionCall { name, args, .. } => {
1260 assert_eq!(name, "get_weather");
1261 assert_eq!(args["city"], "Tokyo");
1262 }
1263 _ => panic!("expected FunctionCall"),
1264 }
1265 assert!(matches!(&parts[2], Part::Text { text } if text == "\n post"));
1266 }
1267
1268 #[test]
1269 fn test_boundary_whitespace_action_tag_preserved() {
1270 let text = "pre \n<|action_start|> {\"name\": \"search\", \"arguments\": {\"q\": \"rust\"}} <|action_end|>\n post";
1271 let parts = parse_text_tool_calls(text).unwrap();
1272 assert_eq!(parts.len(), 3);
1273 assert!(matches!(&parts[0], Part::Text { text } if text == "pre \n"));
1274 match &parts[1] {
1275 Part::FunctionCall { name, args, .. } => {
1276 assert_eq!(name, "search");
1277 assert_eq!(args["q"], "rust");
1278 }
1279 _ => panic!("expected FunctionCall"),
1280 }
1281 assert!(matches!(&parts[2], Part::Text { text } if text == "\n post"));
1282 }
1283
1284 const V3_CALLS: &str = "Checking.<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>get_weather\n```json\n{\"city\": \"Paris\"}\n```<|tool▁call▁end|>\n<|tool▁call▁begin|>function<|tool▁sep|>get_time\n```json\n{\"city\": \"Tokyo\"}\n```<|tool▁call▁end|><|tool▁calls▁end|>";
1285
1286 fn call(name: &str, args: serde_json::Value) -> Part {
1287 Part::FunctionCall { name: name.to_string(), args, id: None, thought_signature: None }
1288 }
1289
1290 #[test]
1291 fn deepseek_v3_native_tokens_parse_into_calls() {
1292 let parts =
1293 parse_declared_tool_calls(V3_CALLS, &declared(&["get_weather", "get_time"])).unwrap();
1294 assert_eq!(
1295 parts,
1296 vec![
1297 Part::Text { text: "Checking.".to_string() },
1298 call("get_weather", serde_json::json!({"city": "Paris"})),
1299 call("get_time", serde_json::json!({"city": "Tokyo"})),
1300 ]
1301 );
1302 }
1303
1304 #[test]
1305 fn deepseek_v31_native_tokens_parse_into_calls() {
1306 let text = "<|tool▁calls▁begin|><|tool▁call▁begin|>get_weather<|tool▁sep|>{\"city\": \"Paris\"}<|tool▁call▁end|><|tool▁calls▁end|>";
1307 let parts = parse_declared_tool_calls(text, &declared(&["get_weather"])).unwrap();
1308 assert_eq!(parts, vec![call("get_weather", serde_json::json!({"city": "Paris"}))]);
1309 }
1310
1311 #[test]
1312 fn deepseek_native_call_to_undeclared_tool_stays_text() {
1313 assert!(parse_declared_tool_calls(V3_CALLS, &declared(&["get_weather"])).is_none());
1314 }
1315
1316 #[test]
1317 fn deepseek_native_tokens_stream_into_calls() {
1318 let mut buffer = ToolCallBuffer::for_declared_tools(declared(&["get_weather", "get_time"]));
1319 let mut parts = Vec::new();
1320 let chars: Vec<char> = V3_CALLS.chars().collect();
1321 for chunk in chars.chunks(7) {
1322 if let BufferAction::Emit(emitted) = buffer.push(&chunk.iter().collect::<String>()) {
1323 parts.extend(emitted);
1324 }
1325 }
1326 parts.extend(buffer.flush());
1327 let calls: Vec<&Part> =
1328 parts.iter().filter(|part| matches!(part, Part::FunctionCall { .. })).collect();
1329 assert_eq!(
1330 calls,
1331 vec![
1332 &call("get_weather", serde_json::json!({"city": "Paris"})),
1333 &call("get_time", serde_json::json!({"city": "Tokyo"})),
1334 ]
1335 );
1336 let text: String = parts
1337 .iter()
1338 .filter_map(|part| match part {
1339 Part::Text { text } => Some(text.as_str()),
1340 _ => None,
1341 })
1342 .collect();
1343 assert!(!text.contains("tool▁"), "native tokens leaked as text: {text}");
1344 }
1345}