Skip to main content

adk_model/
tool_call_parser.rs

1//! Text-based tool call parser for models that emit tool calls as text tags.
2//!
3//! Some models emit tool calls as text tags instead of structured `tool_calls`
4//! JSON when served through endpoints that don't support native tool calling
5//! (e.g., HuggingFace TGI without `--enable-auto-tool-choice`).
6//!
7//! This module detects and parses these text-based tool calls, converting
8//! them to proper `Part::FunctionCall` entries so the agent pipeline works
9//! regardless of the serving backend.
10//!
11//! ## Supported Formats
12//!
13//! - **Qwen/Hermes**: `<tool_call>{"name":"...", "arguments":{...}}</tool_call>`
14//! - **Qwen function tag**: `<tool_call><function=NAME>ARGS</function></tool_call>`
15//! - **Llama**: `<|python_tag|>{"name":"...", "parameters":{...}}`
16//! - **Mistral Nemo**: `[TOOL_CALLS][{"name":"...", "arguments":{...}}]`
17//! - **DeepSeek**: `` ```json\n{"name":"...","arguments":{...}}\n``` `` with `<|tool▁call▁end|>`
18//! - **DeepSeek-V3 native**: `<|tool▁call▁begin|>function<|tool▁sep|>NAME` followed by a
19//!   ` ```json ` fenced arguments object, and the V3.1 form `NAME<|tool▁sep|>{...}`, up to
20//!   `<|tool▁calls▁end|>`
21//! - **Gemma 4**: `<|tool_call>call:NAME{key:<|"|>value<|"|>}<tool_call|>`
22//! - **Action tags**: `<|action_start|>JSON<|action_end|>`
23//!
24//! Provider clients call [`parse_declared_tool_calls`] and
25//! [`ToolCallBuffer::for_declared_tools`], which accept a parse only when every
26//! call names a tool the request declared. A markdown ` ```json ` fence is
27//! ordinary model output, so the DeepSeek format also requires an `arguments`
28//! or `parameters` object.
29
30use std::collections::HashSet;
31
32use adk_core::Part;
33
34/// Check if text contains a tool call tag that should be parsed.
35pub 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
45/// Parse text-based tool calls from model output.
46///
47/// Returns `Some(parts)` if tool calls were found and parsed, where `parts`
48/// contains `Part::FunctionCall` entries (and optionally `Part::Text` for
49/// any non-tool-call text before/after the tags).
50///
51/// Returns `None` if no tool call tags were detected.
52pub 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    // Try Qwen/Hermes format: <tool_call>JSON</tool_call>
60    if let Some(parsed) = parse_qwen_format(text, &mut parts) {
61        return Some(parsed);
62    }
63
64    // Try Llama format: <|python_tag|>JSON
65    if let Some(parsed) = parse_llama_format(text, &mut parts) {
66        return Some(parsed);
67    }
68
69    // Try Mistral Nemo format: [TOOL_CALLS][JSON]
70    if let Some(parsed) = parse_mistral_nemo_format(text, &mut parts) {
71        return Some(parsed);
72    }
73
74    // Try DeepSeek-V3 native tokens: <|tool▁call▁begin|>function<|tool▁sep|>NAME ```json ...```
75    if let Some(parsed) = parse_deepseek_native_format(text) {
76        return Some(parsed);
77    }
78
79    // Try DeepSeek format: ```json\n{...}\n``` with optional <|tool▁call▁end|>
80    if let Some(parsed) = parse_deepseek_format(text) {
81        return Some(parsed);
82    }
83
84    // Try Gemma 4 format: <|tool_call>call:NAME{...}<tool_call|>
85    if let Some(parsed) = parse_gemma4_format(text) {
86        return Some(parsed);
87    }
88
89    // Try action tags: <|action_start|>JSON<|action_end|>
90    if let Some(parsed) = parse_action_tag_format(text) {
91        return Some(parsed);
92    }
93
94    None
95}
96
97/// Parse text-based tool calls, accepting them only when they call declared tools.
98///
99/// Returns `None` — the caller keeps the text as text — when `declared_tools`
100/// is empty, when no tool call is detected, or when any parsed call names a
101/// tool outside `declared_tools`. This keeps ordinary output such as a JSON
102/// example with a `"name"` key from being turned into a tool call.
103///
104/// # Example
105///
106/// ```rust
107/// use std::collections::HashSet;
108///
109/// use adk_core::Part;
110/// use adk_model::tool_call_parser::parse_declared_tool_calls;
111///
112/// let declared = HashSet::from(["lookup".to_string()]);
113/// let example = "```json\n{\"name\": \"Alice\", \"age\": 30}\n```";
114/// assert!(parse_declared_tool_calls(example, &declared).is_none());
115///
116/// let call = "<tool_call>{\"name\": \"lookup\", \"arguments\": {\"id\": 7}}</tool_call>";
117/// let parts = parse_declared_tool_calls(call, &declared).unwrap();
118/// assert!(matches!(&parts[0], Part::FunctionCall { name, .. } if name == "lookup"));
119/// ```
120pub 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
136/// Parse Qwen/Hermes format tool calls.
137///
138/// Handles two sub-formats:
139/// 1. JSON body: `<tool_call>{"name":"fn", "arguments":{...}}</tool_call>`
140/// 2. Function tag: `<tool_call><function=fn>ARGS</function></tool_call>`
141fn 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        // Add any text before the tool call
149        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        // Try JSON format first: {"name":"...", "arguments":{...}}
159        if let Some(part) = parse_json_tool_call(inner) {
160            result.push(part);
161        }
162        // Try function tag format: <function=NAME>ARGS</function>
163        else if let Some(part) = parse_function_tag(inner) {
164            result.push(part);
165        } else {
166            // Couldn't parse — keep as text
167            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
186/// Parse `<function=NAME>ARGS</function>` tag.
187fn 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
206/// Parse JSON tool call: `{"name":"...", "arguments":{...}}`
207/// Also handles `{"function":"...", "parameters":{...}}` variant.
208fn 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
224/// Parse Llama format: `<|python_tag|>{"name":"...", "parameters":{...}}`
225fn 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
245/// Parse Mistral Nemo format: `[TOOL_CALLS][{"name":"...", "arguments":{...}}]`
246fn 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    // Expect a JSON array of tool calls
258    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
273/// DeepSeek end-of-call markers that may follow the closing fence.
274const DEEPSEEK_END_MARKERS: &[&str] = &[DEEPSEEK_CALL_END, DEEPSEEK_CALLS_END];
275
276/// Parse DeepSeek format: ` ```json\n{"name":"...","arguments":{...}}\n``` `
277///
278/// DeepSeek models wrap tool calls in markdown JSON fences, optionally
279/// followed by `<|tool▁call▁end|>` (full-width Unicode delimiters). A fence
280/// is also ordinary markdown, so every object must carry a name and an
281/// `arguments` or `parameters` object; text after the fence is kept.
282fn 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
326/// Parse DeepSeek-V3's native tool-call tokens, as its chat template renders them when the
327/// server has no tool-call parser.
328///
329/// V3 writes `<|tool▁call▁begin|>function<|tool▁sep|>NAME\n```json\n{...}\n```<|tool▁call▁end|>`;
330/// V3.1 writes `<|tool▁call▁begin|>NAME<|tool▁sep|>{...}<|tool▁call▁end|>`. Calls sit between
331/// `<|tool▁calls▁begin|>` and `<|tool▁calls▁end|>`; text around them is kept. Every call must
332/// carry a name and an arguments object.
333fn 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
382/// Parse one fenced tool-call object; `arguments`/`parameters` must be present
383/// and be an object, never defaulted.
384fn 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
396/// Parse Gemma 4 format: `<|tool_call>call:NAME{key:<|"|>value<|"|>}<tool_call|>`
397///
398/// Gemma 4 uses a non-JSON format with custom `<|"|>` string delimiters.
399/// The body after `call:NAME` is a key-value block using `<|"|>` to quote strings.
400fn 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        // Parse: call:NAME{key:<|"|>value<|"|>, ...}
416        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                // Convert Gemma 4 format to JSON: replace <|"|> with "
427                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
449/// Parse action tag format: `<|action_start|>JSON<|action_end|>`
450///
451/// Used by some models (e.g., InternLM, ChatGLM variants) that wrap
452/// tool calls in action start/end tags.
453fn 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
483// ===== Streaming buffer for token-by-token tool call detection =====
484
485/// Prefixes that indicate a potential tool call is starting.
486const TOOL_CALL_PREFIXES: &[&str] = &[
487    "<tool_call",
488    "<|tool_call>",
489    "<|python_tag|",
490    "[TOOL_CALLS]",
491    "<|action_start|>",
492    "<\u{ff5c}tool", // <|tool (DeepSeek full-width)
493];
494
495/// Maximum buffer size before flushing as plain text (safety valve).
496const MAX_BUFFER_SIZE: usize = 4096;
497
498/// Streaming buffer that accumulates tokens and detects tool call boundaries.
499///
500/// Use this in streaming response handlers to buffer tokens when a tool call
501/// prefix is detected, then parse and emit `Part::FunctionCall` when the
502/// closing tag arrives.
503///
504/// # Example
505///
506/// ```rust,ignore
507/// let mut buffer = ToolCallBuffer::new();
508///
509/// for chunk in stream {
510///     match buffer.push(&chunk.text) {
511///         BufferAction::Emit(parts) => {
512///             for part in parts { yield part; }
513///         }
514///         BufferAction::Buffering => { /* still accumulating */ }
515///     }
516/// }
517/// // Flush any remaining content at end of stream
518/// for part in buffer.flush() { yield part; }
519/// ```
520pub struct ToolCallBuffer {
521    buffer: String,
522    buffering: bool,
523    /// Tools the request declared; `None` accepts any parsed call.
524    declared_tools: Option<HashSet<String>>,
525}
526
527/// Action returned by `ToolCallBuffer::push()`.
528pub enum BufferAction {
529    /// Emit these parts immediately (text or parsed tool calls).
530    Emit(Vec<Part>),
531    /// Still buffering — don't emit anything yet.
532    Buffering,
533}
534
535impl ToolCallBuffer {
536    /// Create a new empty buffer that accepts a parsed call to any tool name.
537    pub fn new() -> Self {
538        Self { buffer: String::new(), buffering: false, declared_tools: None }
539    }
540
541    /// Create a buffer that emits a parsed call only when every call names one of
542    /// `declared_tools`, as [`parse_declared_tool_calls`] does.
543    ///
544    /// With no declared tools the buffer never holds text back: every chunk is
545    /// emitted as text immediately.
546    ///
547    /// # Example
548    ///
549    /// ```rust
550    /// use std::collections::HashSet;
551    ///
552    /// use adk_core::Part;
553    /// use adk_model::tool_call_parser::{BufferAction, ToolCallBuffer};
554    ///
555    /// let mut buffer = ToolCallBuffer::for_declared_tools(HashSet::new());
556    /// let BufferAction::Emit(parts) = buffer.push("<tool_call>{\"name\":\"x\"}</tool_call>") else {
557    ///     panic!("nothing is buffered without declared tools");
558    /// };
559    /// assert!(matches!(&parts[0], Part::Text { .. }));
560    /// ```
561    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    /// Push a text chunk into the buffer.
566    ///
567    /// Returns `BufferAction::Emit` with parts to yield, or
568    /// `BufferAction::Buffering` if we're accumulating a potential tool call.
569    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            // Check if we have a complete tool call
578            if self.has_complete_tool_call() {
579                return self.try_parse_and_emit();
580            }
581            // A prefix-like chunk can become ordinary text once more data arrives.
582            if !self.starts_tool_call_prefix() && !self.has_partial_prefix() {
583                return self.flush_as_emit();
584            }
585            // Safety valve: if buffer is too large, flush as text
586            if self.buffer.len() > MAX_BUFFER_SIZE {
587                return self.flush_as_emit();
588            }
589            BufferAction::Buffering
590        } else {
591            // Check if this chunk starts or contains a tool call prefix
592            if self.starts_tool_call_prefix() {
593                self.buffering = true;
594                // Check if the complete tool call arrived in one chunk
595                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                // Could be the start of a prefix split across chunks (e.g., "<tool" then "_call>")
601                self.buffering = true;
602                BufferAction::Buffering
603            } else {
604                // Normal text — emit immediately
605                self.flush_as_emit()
606            }
607        }
608    }
609
610    /// Flush any remaining buffered content as parts.
611    /// Call this when the stream ends.
612    pub fn flush(&mut self) -> Vec<Part> {
613        if self.buffer.is_empty() {
614            return Vec::new();
615        }
616
617        // Try to parse as tool calls one last time
618        if let Some(parts) = self.parse_buffer() {
619            self.buffer.clear();
620            self.buffering = false;
621            return parts;
622        }
623
624        // Otherwise emit as text
625        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        // Check if the buffer ends with a partial prefix like "<tool" or "<|python"
643        let buf = &self.buffer;
644        for prefix in TOOL_CALL_PREFIXES {
645            // Use char-based iteration to avoid slicing multi-byte Unicode
646            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        // DeepSeek-V3 native calls hold a ```json fence each, so only the closing token ends them.
659        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            // Couldn't parse — flush as text
681            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        // The two tool-call markups are separated by a single `\n`. After the
762        // whitespace-preservation fix, that separating newline is emitted as a
763        // `Part::Text` between the two `Part::FunctionCall`s (byte-exact
764        // reconstruction per Requirements 2.5/2.6), yielding 3 parts.
765        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    // ===== Streaming buffer tests =====
818
819    #[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        // Chunk 1: prefix starts
849        assert!(matches!(buf.push("<tool_call>"), BufferAction::Buffering));
850
851        // Chunk 2: JSON body
852        assert!(matches!(
853            buf.push(r#"{"name": "get_weather", "arguments": {"city": "Tokyo"}}"#),
854            BufferAction::Buffering
855        ));
856
857        // Chunk 3: closing tag
858        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        // Normal text first
874        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        // Then tool call
883        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        // Stream ends without closing tag
899        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        // "<tool" could be the start of "<tool_call>"
915        assert!(matches!(buf.push("<tool"), BufferAction::Buffering));
916        // Complete it
917        assert!(matches!(buf.push("_call>"), BufferAction::Buffering));
918        // Add body and close
919        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![Part::Text {
939                        text: "[documentation](https://example.com) 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    // ===== DeepSeek format tests =====
969
970    #[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        // The fence carries no arguments, so it is not a call even without the filter.
1011        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    // ===== Gemma 4 format tests =====
1067
1068    #[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    // ===== Action tag format tests =====
1094
1095    #[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); // text + function call (+ optional trailing text)
1114        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    // ===== Whitespace-preservation regression tests =====
1120
1121    /// Stream a sequence of deltas through `ToolCallBuffer` (push each, then
1122    /// flush) and return the concatenation of all emitted `Part::Text` values.
1123    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        // Counterexample 1 (Requirements 2.1, 2.2, 2.3): whitespace-only deltas
1145        // between visible text must be preserved so Markdown structure survives.
1146        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        // Counterexample 2 (Requirements 2.1, 2.4): a single-space delta between
1154        // words must be preserved.
1155        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        // Requirement 2.1: a whitespace-only delta must be emitted as Part::Text
1162        // (previously dropped by the `text.trim().is_empty()` guard).
1163        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        // Requirement 2.2: whitespace-only buffered content at end-of-stream must
1176        // be emitted by flush rather than discarded.
1177        let mut buf = ToolCallBuffer::new();
1178        // Place whitespace-only content into the buffer as if mid-tool-call
1179        // buffering had accumulated it, then flush at end of stream.
1180        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    // ===== Boundary-whitespace preservation across the six markup formats =====
1188
1189    #[test]
1190    fn test_boundary_whitespace_qwen_preserved() {
1191        // Leading/trailing whitespace around the markup is preserved, while the
1192        // inner tool name/args stay trimmed (inner is `.trim()`ed before parse).
1193        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}