|
| 1 | +import json |
| 2 | +import logging |
| 3 | +import re |
| 4 | +from typing import Any, Dict, List, Optional, Tuple |
| 5 | + |
| 6 | +from . import register_tool_parser |
| 7 | +from .abstract_tool_parser import ToolParser |
| 8 | + |
| 9 | +logger = logging.getLogger(__name__) |
| 10 | + |
| 11 | + |
| 12 | +@register_tool_parser("gemma") |
| 13 | +class GemmaToolParser(ToolParser): |
| 14 | + """ |
| 15 | + Tool parser for Gemma-4 style tool call blocks. |
| 16 | +
|
| 17 | + Gemma emits tool invocations using tokens like: |
| 18 | + <|tool_call>call:get_weather{location:<|"|>Shanghai<|"|>}<tool_call|> |
| 19 | + where strings are wrapped with <|"|> ... <|"|>. |
| 20 | + """ |
| 21 | + |
| 22 | + def __init__(self): |
| 23 | + self.tool_call_start_token = "<|tool_call>" |
| 24 | + self.tool_call_end_token = "<tool_call|>" |
| 25 | + self.tool_call_regex = re.compile( |
| 26 | + r"(<\|tool_call\>.*?<tool_call\|>)", re.DOTALL |
| 27 | + ) |
| 28 | + self.call_header_regex = re.compile(r"call\s*:\s*([^{\s]+)", re.IGNORECASE) |
| 29 | + |
| 30 | + @staticmethod |
| 31 | + def _replace_quotes(text: str) -> str: |
| 32 | + return text.replace('<|"|>', '"') |
| 33 | + |
| 34 | + @staticmethod |
| 35 | + def _quote_keys(text: str) -> str: |
| 36 | + pattern = re.compile(r"(?P<prefix>[{,])\s*(?P<key>[A-Za-z0-9_\-]+)\s*:") |
| 37 | + |
| 38 | + def repl(match: re.Match) -> str: |
| 39 | + prefix = match.group("prefix") |
| 40 | + key = match.group("key") |
| 41 | + return f'{prefix}"{key}":' |
| 42 | + |
| 43 | + while True: |
| 44 | + new_text, count = pattern.subn(repl, text) |
| 45 | + text = new_text |
| 46 | + if count == 0: |
| 47 | + break |
| 48 | + return text |
| 49 | + |
| 50 | + def _parse_arguments(self, arg_block: str) -> Dict[str, Any]: |
| 51 | + cleaned = self._replace_quotes(arg_block.strip()) |
| 52 | + if not cleaned: |
| 53 | + return {} |
| 54 | + normalized = self._quote_keys(cleaned) |
| 55 | + return json.loads(normalized) |
| 56 | + |
| 57 | + def _parse_tool_call_block( |
| 58 | + self, block: str |
| 59 | + ) -> Tuple[Optional[str], Optional[str], Optional[Dict[str, Any]]]: |
| 60 | + content = block.strip() |
| 61 | + try: |
| 62 | + # Remove wrapper tokens |
| 63 | + if content.startswith(self.tool_call_start_token): |
| 64 | + content = content[len(self.tool_call_start_token) :] |
| 65 | + if content.endswith(self.tool_call_end_token): |
| 66 | + content = content[: -len(self.tool_call_end_token)] |
| 67 | + content = content.strip() |
| 68 | + |
| 69 | + match = self.call_header_regex.search(content) |
| 70 | + if not match: |
| 71 | + raise ValueError("Missing call header") |
| 72 | + func_name = match.group(1).strip() |
| 73 | + |
| 74 | + brace_start = content.find("{", match.end()) |
| 75 | + brace_end = content.rfind("}") |
| 76 | + if brace_start == -1 or brace_end == -1 or brace_end < brace_start: |
| 77 | + args = {} |
| 78 | + else: |
| 79 | + args_str = content[brace_start : brace_end + 1] |
| 80 | + args = self._parse_arguments(args_str) |
| 81 | + return (None, func_name, args) |
| 82 | + except Exception as exc: |
| 83 | + logger.warning("Failed to parse Gemma tool call: %s, error: %s", block, exc) |
| 84 | + return (block, None, None) |
| 85 | + |
| 86 | + def extract_tool_calls( |
| 87 | + self, model_output: str |
| 88 | + ) -> List[Tuple[Optional[str], Optional[str], Optional[Dict[str, Any]]]]: |
| 89 | + if self.tool_call_start_token not in model_output: |
| 90 | + return [(model_output, None, None)] |
| 91 | + |
| 92 | + results: List[Tuple[Optional[str], Optional[str], Optional[Dict[str, Any]]]] = ( |
| 93 | + [] |
| 94 | + ) |
| 95 | + last_end = 0 |
| 96 | + for match in self.tool_call_regex.finditer(model_output): |
| 97 | + if match.start() > last_end: |
| 98 | + content = model_output[last_end : match.start()] |
| 99 | + if content: |
| 100 | + results.append((content, None, None)) |
| 101 | + block = match.group(0) |
| 102 | + results.append(self._parse_tool_call_block(block)) |
| 103 | + last_end = match.end() |
| 104 | + |
| 105 | + if last_end < len(model_output): |
| 106 | + remainder = model_output[last_end:] |
| 107 | + if remainder: |
| 108 | + results.append((remainder, None, None)) |
| 109 | + |
| 110 | + return results or [(model_output, None, None)] |
| 111 | + |
| 112 | + def extract_tool_calls_streaming( |
| 113 | + self, |
| 114 | + previous_texts: List[str], |
| 115 | + current_text: str, |
| 116 | + delta_text: str, |
| 117 | + ) -> Optional[Tuple[Optional[str], Optional[str], Optional[Dict[str, Any]]]]: |
| 118 | + if self.tool_call_start_token not in current_text: |
| 119 | + return (delta_text, None, None) |
| 120 | + |
| 121 | + matches = list(self.tool_call_regex.finditer(current_text)) |
| 122 | + if not matches: |
| 123 | + return None |
| 124 | + |
| 125 | + prev_text = previous_texts[-1] if previous_texts else "" |
| 126 | + last_match = matches[-1] |
| 127 | + if last_match.end() <= len(prev_text): |
| 128 | + # The latest complete tool call was already processed, return delta as text |
| 129 | + return (delta_text, None, None) |
| 130 | + |
| 131 | + block = last_match.group(0) |
| 132 | + return self._parse_tool_call_block(block) |
0 commit comments