pythonic_parser.rs 16.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/// Pythonic format parser for tool calls
///
/// Handles Python function call syntax within square brackets:
/// ```text
/// [tool1(arg1=val1, arg2=val2), tool2(arg1=val3)]
/// ```
///
/// This format is used by Llama-4 models and uses Python literals
/// rather than JSON for arguments.
use async_trait::async_trait;
use regex::Regex;
use serde_json::{json, Value};

use crate::tool_parser::{
    errors::ToolParserResult,
    python_literal_parser::parse_python_literal,
    state::ParseState,
    traits::ToolParser,
    types::{FunctionCall, StreamResult, ToolCall},
};

/// Parser for Pythonic tool call format
pub struct PythonicParser {
    /// Regex to detect tool calls in Pythonic format
    tool_call_regex: Regex,
26
27
    /// Regex to parse function calls - cached for reuse
    call_regex: Regex,
28
29
30
31
32
33
34
35
36
37
}

impl PythonicParser {
    /// Create a new Pythonic parser
    pub fn new() -> Self {
        // Simple regex to detect start of Pythonic tool calls
        // We'll use manual parsing for the actual extraction
        let pattern = r"\[[a-zA-Z_]\w*\(";
        let tool_call_regex = Regex::new(pattern).expect("Valid regex pattern");

38
39
40
41
42
43
44
        // Compile the function call regex once
        let call_regex = Regex::new(r"(?s)^([a-zA-Z_]\w*)\((.*)\)$").expect("Valid regex pattern");

        Self {
            tool_call_regex,
            call_regex,
        }
45
46
47
    }

    /// Extract tool calls using bracket counting (similar to MistralParser)
48
49
    /// Returns extracted tool call group with [] and normal content
    fn extract_tool_calls(&self, text: &str) -> Option<(String, String)> {
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
        // Find the start of a tool call list - look for [ followed by a function name
        let chars: Vec<char> = text.chars().collect();

        for start_idx in 0..chars.len() {
            if chars[start_idx] != '[' {
                continue;
            }

            // Check if this looks like a tool call
            // Skip whitespace after [
            let mut check_idx = start_idx + 1;
            while check_idx < chars.len() && chars[check_idx].is_whitespace() {
                check_idx += 1;
            }

            // Check if we have a function name (starts with letter or underscore)
            if check_idx >= chars.len()
                || (!chars[check_idx].is_alphabetic() && chars[check_idx] != '_')
            {
                continue;
            }

            // Now count brackets to find the matching ]
            let mut bracket_count = 0;
            let mut _paren_count = 0;
            let mut _brace_count = 0;
            let mut in_string = false;
            let mut string_char = ' ';
            let mut escape_next = false;

            for i in start_idx..chars.len() {
                let ch = chars[i];

                if escape_next {
                    escape_next = false;
                    continue;
                }

                if ch == '\\' && in_string {
                    escape_next = true;
                    continue;
                }

                if !in_string && (ch == '"' || ch == '\'') {
                    in_string = true;
                    string_char = ch;
                } else if in_string && ch == string_char && !escape_next {
                    in_string = false;
                } else if !in_string {
                    match ch {
                        '[' => bracket_count += 1,
                        ']' => {
                            bracket_count -= 1;
                            if bracket_count == 0 {
                                // Found the matching bracket
                                let extracted: String = chars[start_idx..=i].iter().collect();
                                if extracted.contains('(') && extracted.contains(')') {
107
108
109
110
111
                                    // Calculate normal text by removing the tool call portion
                                    let before = &text[..start_idx];
                                    let after = &text[(i + 1)..];
                                    let normal_text = format!("{}{}", before, after);
                                    return Some((extracted, normal_text));
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
                                }
                            }
                        }
                        '(' => _paren_count += 1,
                        ')' => _paren_count -= 1,
                        '{' => _brace_count += 1,
                        '}' => _brace_count -= 1,
                        _ => {}
                    }
                }
            }
        }
        None
    }

    /// Strip special tokens that Llama 4 might output
    fn strip_special_tokens(text: &str) -> String {
        text.replace("<|python_start|>", "")
            .replace("<|python_end|>", "")
    }

    /// Parse a single function call from Python syntax
    fn parse_function_call(&self, call_str: &str) -> ToolParserResult<Option<ToolCall>> {
135
136
        // Use cached regex instead of creating new one
        if let Some(captures) = self.call_regex.captures(call_str.trim()) {
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
            let function_name = captures.get(1).unwrap().as_str();
            let args_str = captures.get(2).unwrap().as_str();

            // Parse arguments
            let arguments = self.parse_arguments(args_str)?;

            Ok(Some(ToolCall {
                id: format!("call_{}", uuid::Uuid::new_v4()),
                r#type: "function".to_string(),
                function: FunctionCall {
                    name: function_name.to_string(),
                    arguments: serde_json::to_string(&arguments)?,
                },
            }))
        } else {
            Ok(None)
        }
    }

    /// Parse Python-style arguments into JSON
    fn parse_arguments(&self, args_str: &str) -> ToolParserResult<Value> {
        if args_str.trim().is_empty() {
            return Ok(json!({}));
        }

        let mut result = serde_json::Map::new();
        let mut current_key = String::new();
        let mut current_value = String::new();
        let mut in_key = true;
        let mut depth = 0;
        let mut in_string = false;
        let mut string_char = ' ';
        let mut escape_next = false;

        let chars: Vec<char> = args_str.chars().collect();
        let mut i = 0;

        while i < chars.len() {
            let ch = chars[i];

            if escape_next {
                if in_key {
                    current_key.push(ch);
                } else {
                    current_value.push(ch);
                }
                escape_next = false;
                i += 1;
                continue;
            }

            if ch == '\\' && in_string {
                escape_next = true;
                current_value.push(ch);
                i += 1;
                continue;
            }

            // Handle string literals
            if !in_string && (ch == '"' || ch == '\'') {
                in_string = true;
                string_char = ch;
                if !in_key {
                    current_value.push(ch);
                }
            } else if in_string && ch == string_char && !escape_next {
                in_string = false;
                if !in_key {
                    current_value.push(ch);
                }
            } else if in_string {
                if in_key {
                    current_key.push(ch);
                } else {
                    current_value.push(ch);
                }
            } else {
                // Not in string
                match ch {
                    '=' if in_key && depth == 0 => {
                        in_key = false;
                    }
                    ',' if depth == 0 => {
                        // End of current argument
                        if !current_key.is_empty() {
                            let value = parse_python_literal(current_value.trim())?;
                            result.insert(current_key.trim().to_string(), value);
                        }
                        current_key.clear();
                        current_value.clear();
                        in_key = true;
                    }
                    '[' | '{' | '(' => {
                        depth += 1;
                        if !in_key {
                            current_value.push(ch);
                        }
                    }
                    ']' | '}' | ')' => {
                        depth -= 1;
                        if !in_key {
                            current_value.push(ch);
                        }
                    }
                    _ => {
                        if in_key {
                            if !ch.is_whitespace() || !current_key.is_empty() {
                                current_key.push(ch);
                            }
                        } else {
                            current_value.push(ch);
                        }
                    }
                }
            }

            i += 1;
        }

        // Handle the last argument
        if !current_key.is_empty() {
            let value = parse_python_literal(current_value.trim())?;
            result.insert(current_key.trim().to_string(), value);
        }

        Ok(Value::Object(result))
    }
}

#[async_trait]
impl ToolParser for PythonicParser {
268
    async fn parse_complete(&self, text: &str) -> ToolParserResult<(String, Vec<ToolCall>)> {
269
270
271
        let cleaned = Self::strip_special_tokens(text);

        // Extract tool calls using bracket counting
272
        if let Some((tool_calls_text, normal_text)) = self.extract_tool_calls(&cleaned) {
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
            // Remove the outer brackets
            let tool_calls_str = &tool_calls_text[1..tool_calls_text.len() - 1];

            // Split into individual function calls
            let mut calls = Vec::new();
            let mut current_call = String::new();
            let mut paren_depth = 0;
            let mut in_string = false;
            let mut string_char = ' ';

            for ch in tool_calls_str.chars() {
                if !in_string && (ch == '"' || ch == '\'') {
                    in_string = true;
                    string_char = ch;
                    current_call.push(ch);
                } else if in_string && ch == string_char {
                    in_string = false;
                    current_call.push(ch);
                } else if in_string {
                    current_call.push(ch);
                } else {
                    match ch {
                        '(' => {
                            paren_depth += 1;
                            current_call.push(ch);
                        }
                        ')' => {
                            paren_depth -= 1;
                            current_call.push(ch);
                        }
                        ',' if paren_depth == 0 => {
                            // End of current function call
                            if let Some(call) = self.parse_function_call(current_call.trim())? {
                                calls.push(call);
                            }
                            current_call.clear();
                        }
                        _ => {
                            if !ch.is_whitespace() || !current_call.is_empty() {
                                current_call.push(ch);
                            }
                        }
                    }
                }
            }

            // Handle the last call (important for single calls or the last call in a list)
            if !current_call.trim().is_empty() {
                if let Some(call) = self.parse_function_call(current_call.trim())? {
                    calls.push(call);
                }
            }

326
            Ok((normal_text, calls))
327
        } else {
328
            Ok((text.to_string(), vec![]))
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
        }
    }

    async fn parse_incremental(
        &self,
        chunk: &str,
        state: &mut ParseState,
    ) -> ToolParserResult<StreamResult> {
        // For Pythonic format, we accumulate until we have a complete tool call
        // This is a simplified implementation
        state.buffer.push_str(chunk);

        // Try to parse if we have a complete tool call
        let cleaned = Self::strip_special_tokens(&state.buffer);
        if self.extract_tool_calls(&cleaned).is_some() {
344
345
            let (_normal_text, tools) = self.parse_complete(&state.buffer).await?;
            if !tools.is_empty() {
346
347
                state.buffer.clear();
                return Ok(StreamResult::ToolComplete(
348
                    tools.into_iter().next().unwrap(),
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
                ));
            }
        }

        Ok(StreamResult::Incomplete)
    }

    fn detect_format(&self, text: &str) -> bool {
        let cleaned = Self::strip_special_tokens(text);
        self.tool_call_regex.is_match(&cleaned)
    }
}

impl Default for PythonicParser {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_single_function_call() {
        let parser = PythonicParser::new();
        let input = r#"[search_web(query="Rust programming", max_results=5)]"#;

377
378
379
        let (_normal_text, tools) = parser.parse_complete(input).await.unwrap();
        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0].function.name, "search_web");
380

381
        let args: Value = serde_json::from_str(&tools[0].function.arguments).unwrap();
382
383
384
385
386
387
388
389
390
        assert_eq!(args["query"], "Rust programming");
        assert_eq!(args["max_results"], 5);
    }

    #[tokio::test]
    async fn test_multiple_function_calls() {
        let parser = PythonicParser::new();
        let input = r#"[get_weather(city="Tokyo"), search(query="news")]"#;

391
392
393
394
        let (_normal_text, tools) = parser.parse_complete(input).await.unwrap();
        assert_eq!(tools.len(), 2);
        assert_eq!(tools[0].function.name, "get_weather");
        assert_eq!(tools[1].function.name, "search");
395
396
397
398
399
400
401
    }

    #[tokio::test]
    async fn test_python_literals() {
        let parser = PythonicParser::new();
        let input = r#"[test(flag=True, disabled=False, optional=None)]"#;

402
403
        let (_normal_text, tools) = parser.parse_complete(input).await.unwrap();
        assert_eq!(tools.len(), 1);
404

405
        let args: Value = serde_json::from_str(&tools[0].function.arguments).unwrap();
406
407
408
409
410
411
412
413
414
415
        assert_eq!(args["flag"], true);
        assert_eq!(args["disabled"], false);
        assert_eq!(args["optional"], Value::Null);
    }

    #[tokio::test]
    async fn test_special_tokens() {
        let parser = PythonicParser::new();
        let input = r#"<|python_start|>[calculate(x=10, y=20)]<|python_end|>"#;

416
417
418
        let (_normal_text, tools) = parser.parse_complete(input).await.unwrap();
        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0].function.name, "calculate");
419

420
        let args: Value = serde_json::from_str(&tools[0].function.arguments).unwrap();
421
422
423
424
425
426
427
428
429
        assert_eq!(args["x"], 10);
        assert_eq!(args["y"], 20);
    }

    #[tokio::test]
    async fn test_llama4_format() {
        let parser = PythonicParser::new();
        let input = r#"[get_weather(city="London", units="celsius")]"#;

430
431
432
        let (_normal_text, tools) = parser.parse_complete(input).await.unwrap();
        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0].function.name, "get_weather");
433

434
        let args: Value = serde_json::from_str(&tools[0].function.arguments).unwrap();
435
436
437
        assert_eq!(args["city"], "London");
        assert_eq!(args["units"], "celsius");
    }
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466

    #[tokio::test]
    async fn test_normal_text_extraction() {
        let parser = PythonicParser::new();

        // Test with text before and after
        let input = r#"Please check the weather [get_weather(city="Tokyo")] and let me know."#;
        let (normal_text, tools) = parser.parse_complete(input).await.unwrap();

        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0].function.name, "get_weather");
        assert_eq!(normal_text, "Please check the weather  and let me know.");

        // Test with only normal text (no tool calls)
        let input_no_tools = "This is just normal text without any tool calls.";
        let (normal_text, tools) = parser.parse_complete(input_no_tools).await.unwrap();

        assert_eq!(tools.len(), 0);
        assert_eq!(normal_text, input_no_tools);

        // Test with multiple tool calls in single bracket group and normal text
        let input_multiple = r#"First, [search(query="rust"), calculate(x=5, y=10)] please."#;
        let (normal_text, tools) = parser.parse_complete(input_multiple).await.unwrap();

        assert_eq!(tools.len(), 2);
        assert_eq!(tools[0].function.name, "search");
        assert_eq!(tools[1].function.name, "calculate");
        assert_eq!(normal_text, "First,  please.");
    }
467
}