tool_utils.py 21.4 KB
Newer Older
chenych's avatar
chenych committed
1
# Copyright 2025 the LlamaFactory team.
chenych's avatar
chenych committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import re
from abc import ABC, abstractmethod
from dataclasses import dataclass
luopl's avatar
luopl committed
19
from datetime import datetime
chenych's avatar
chenych committed
20
from typing import Any, NamedTuple, Union
chenych's avatar
chenych committed
21

luopl's avatar
luopl committed
22
23
from typing_extensions import override

chenych's avatar
chenych committed
24

luopl's avatar
luopl committed
25
26
27
28
29
class FunctionCall(NamedTuple):
    name: str
    arguments: str


chenych's avatar
chenych committed
30
31
32
33
34
35
36
37
38
39
40
DEFAULT_TOOL_PROMPT = (
    "You have access to the following tools:\n{tool_text}"
    "Use the following format if using a tool:\n"
    "```\n"
    "Action: tool name (one of [{tool_names}])\n"
    "Action Input: the input to the tool, in a JSON format representing the kwargs "
    """(e.g. ```{{"input": "hello world", "num_beams": 5}}```)\n"""
    "```\n"
)

GLM4_TOOL_PROMPT = (
chenych's avatar
chenych committed
41
42
    "你是一个名为 ChatGLM 的人工智能助手。你是基于智谱 AI 公司训练的语言模型 GLM-4 模型开发的,"
    "你的任务是针对用户的问题和要求提供适当的答复和支持。\n\n# 可用工具{tool_text}"
chenych's avatar
chenych committed
43
44
)

shihm's avatar
uodata  
shihm committed
45
46
47
48
49
50
51
52
53
54
55
56
GLM4_MOE_TOOL_PROMPT = (
    "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\n"
    "You are provided with function signatures within <tools></tools> XML tags:\n<tools>{tool_text}"
    "\n</tools>\n\nFor each function call, output the function name and arguments within the following XML format:"
    "\n<tool_call>{{function-name}}"
    "\n<arg_key>{{arg-key-1}}</arg_key>"
    "\n<arg_value>{{arg-value-1}}</arg_value>"
    "\n<arg_key>{{arg-key-2}}</arg_key>"
    "\n<arg_value>{{arg-value-2}}</arg_value>"
    "\n...\n</tool_call>\n"
)

luopl's avatar
luopl committed
57
58
59
60
61
62
LLAMA3_TOOL_PROMPT = (
    "Cutting Knowledge Date: December 2023\nToday Date: {date}\n\n"
    "You have access to the following functions. To call a function, please respond with JSON for a function call. "
    """Respond in the format {{"name": function name, "parameters": dictionary of argument name and its value}}. """
    "Do not use variables.\n\n{tool_text}"
)
chenych's avatar
chenych committed
63

shihm's avatar
uodata  
shihm committed
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
MINIMAX_M1_TOOL_PROMPT = (
    "You are provided with these tools:\n<tools>\n{tool_text}</tools>\n\n"
    "If you need to call tools, please respond with <tool_calls></tool_calls> XML tags, and provide tool-name and "
    "json-object of arguments, following the format below:\n<tool_calls>\n"
    """{{"name": <tool-name-1>, "arguments": <args-json-object-1>}}\n...\n</tool_calls>"""
)

MINIMAX_M2_TOOL_PROMPT = (
    "\n\n# Tools\n\nYou may call one or more tools to assist with the user query.\n"
    "Here are the tools available in JSONSchema format:\n\n<tools>\n{tool_text}</tools>\n\n"
    "When making tool calls, use XML format to invoke tools and pass parameters:\n"
    """\n<minimax:tool_call>\n<invoke name="tool-name-1">\n<parameter name="param-key-1">param-value-1</parameter>\n"""
    """<parameter name="param-key-2">param-value-2</parameter>\n...\n</invoke>\n</minimax:tool_call>"""
)

luopl's avatar
luopl committed
79
80
81
82
83
QWEN_TOOL_PROMPT = (
    "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\n"
    "You are provided with function signatures within <tools></tools> XML tags:\n<tools>{tool_text}"
    "\n</tools>\n\nFor each function call, return a json object with function name and arguments within "
    """<tool_call></tool_call> XML tags:\n<tool_call>\n{{"name": <function-name>, """
chenych's avatar
chenych committed
84
    """"arguments": <args-json-object>}}\n</tool_call>"""
luopl's avatar
luopl committed
85
)
luopl's avatar
luopl committed
86

shihm's avatar
uodata  
shihm committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
SEED_TOOL_PROMPT = (
    "system\nYou are Doubao, a helpful AI assistant. You may call one or more functions to assist with the user query."
    "Tool List:\nYou are authorized to use the following tools (described in JSON Schema format). Before performing "
    "any task, you must decide how to call them based on the descriptions and parameters of these tools.{tool_text}\n"
    "工具调用请遵循如下格式:\n<seed:tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>value_1"
    "</parameter>\n<parameter=example_parameter_2>This is the value for the second parameter\nthat can span\nmultiple "
    "lines</parameter>\n</function>\n</seed:tool_call>\n"
)

LING_TOOL_PROMPT = (
    "# Tools\n\nYou may call one or more functions to assist with the user query.\n\n"
    "You are provided with function signatures within <tools></tools> XML tags:\n<tools>{tool_text}"
    "\n</tools>\n\nFor each function call, return a json object with function name and arguments within "
    """<tool_call></tool_call> XML tags:\n<tool_call>\n{{"name": <function-name>, """
    """"arguments": <args-json-object>}}\n</tool_call>"""
)

luopl's avatar
luopl committed
104

chenych's avatar
chenych committed
105
106
@dataclass
class ToolUtils(ABC):
chenych's avatar
chenych committed
107
    """Base class for tool utilities."""
luopl's avatar
luopl committed
108

chenych's avatar
chenych committed
109
110
    @staticmethod
    @abstractmethod
chenych's avatar
chenych committed
111
112
    def tool_formatter(tools: list[dict[str, Any]]) -> str:
        r"""Generate the system message describing all the available tools."""
luopl's avatar
luopl committed
113
        ...
chenych's avatar
chenych committed
114
115
116

    @staticmethod
    @abstractmethod
chenych's avatar
chenych committed
117
118
    def function_formatter(functions: list["FunctionCall"]) -> str:
        r"""Generate the assistant message including all the tool calls."""
luopl's avatar
luopl committed
119
        ...
chenych's avatar
chenych committed
120
121
122

    @staticmethod
    @abstractmethod
chenych's avatar
chenych committed
123
124
    def tool_extractor(content: str) -> Union[str, list["FunctionCall"]]:
        r"""Extract all the function calls from the assistant message.
luopl's avatar
luopl committed
125
126

        It should be an inverse function of `function_formatter`.
luopl's avatar
luopl committed
127
128
        """
        ...
chenych's avatar
chenych committed
129
130
131


class DefaultToolUtils(ToolUtils):
chenych's avatar
chenych committed
132
    r"""Default tool using template."""
chenych's avatar
chenych committed
133

luopl's avatar
luopl committed
134
    @override
chenych's avatar
chenych committed
135
    @staticmethod
chenych's avatar
chenych committed
136
    def tool_formatter(tools: list[dict[str, Any]]) -> str:
chenych's avatar
chenych committed
137
138
139
        tool_text = ""
        tool_names = []
        for tool in tools:
chenych's avatar
chenych committed
140
            tool = tool.get("function", "") if tool.get("type") == "function" else tool
chenych's avatar
chenych committed
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
            param_text = ""
            for name, param in tool["parameters"]["properties"].items():
                required, enum, items = "", "", ""
                if name in tool["parameters"].get("required", []):
                    required = ", required"

                if param.get("enum", None):
                    enum = ", should be one of [{}]".format(", ".join(param["enum"]))

                if param.get("items", None):
                    items = ", where each item should be {}".format(param["items"].get("type", ""))

                param_text += "  - {name} ({type}{required}): {desc}{enum}{items}\n".format(
                    name=name,
                    type=param.get("type", ""),
                    required=required,
                    desc=param.get("description", ""),
                    enum=enum,
                    items=items,
                )

            tool_text += "> Tool Name: {name}\nTool Description: {desc}\nTool Args:\n{args}\n".format(
                name=tool["name"], desc=tool.get("description", ""), args=param_text
            )
            tool_names.append(tool["name"])

        return DEFAULT_TOOL_PROMPT.format(tool_text=tool_text, tool_names=", ".join(tool_names))

luopl's avatar
luopl committed
169
170
    @override
    @staticmethod
chenych's avatar
chenych committed
171
    def function_formatter(functions: list["FunctionCall"]) -> str:
chenych's avatar
chenych committed
172
        return "\n".join([f"Action: {name}\nAction Input: {arguments}" for name, arguments in functions])
luopl's avatar
luopl committed
173

luopl's avatar
luopl committed
174
    @override
chenych's avatar
chenych committed
175
    @staticmethod
chenych's avatar
chenych committed
176
    def tool_extractor(content: str) -> Union[str, list["FunctionCall"]]:
chenych's avatar
chenych committed
177
        regex = re.compile(r"Action:\s*([a-zA-Z0-9_]+)\s*Action Input:\s*(.+?)(?=\s*Action:|\s*$)", re.DOTALL)
chenych's avatar
chenych committed
178
        action_match: list[tuple[str, str]] = re.findall(regex, content)
chenych's avatar
chenych committed
179
180
181
182
183
184
185
186
187
        if not action_match:
            return content

        results = []
        for match in action_match:
            tool_name = match[0].strip()
            tool_input = match[1].strip().strip('"').strip("```")
            try:
                arguments = json.loads(tool_input)
luopl's avatar
luopl committed
188
                results.append(FunctionCall(tool_name, json.dumps(arguments, ensure_ascii=False)))
chenych's avatar
chenych committed
189
190
191
192
193
194
195
            except json.JSONDecodeError:
                return content

        return results


class GLM4ToolUtils(ToolUtils):
chenych's avatar
chenych committed
196
    r"""GLM-4 tool using template."""
chenych's avatar
chenych committed
197

luopl's avatar
luopl committed
198
    @override
chenych's avatar
chenych committed
199
    @staticmethod
chenych's avatar
chenych committed
200
    def tool_formatter(tools: list[dict[str, Any]]) -> str:
chenych's avatar
chenych committed
201
202
        tool_text = ""
        for tool in tools:
chenych's avatar
chenych committed
203
            tool = tool.get("function", "") if tool.get("type") == "function" else tool
chenych's avatar
chenych committed
204
205
206
207
208
209
            tool_text += "\n\n## {name}\n\n{body}\n在调用上述函数时,请使用 Json 格式表示调用的参数。".format(
                name=tool["name"], body=json.dumps(tool, indent=4, ensure_ascii=False)
            )

        return GLM4_TOOL_PROMPT.format(tool_text=tool_text)

luopl's avatar
luopl committed
210
211
    @override
    @staticmethod
chenych's avatar
chenych committed
212
    def function_formatter(functions: list["FunctionCall"]) -> str:
luopl's avatar
luopl committed
213
214
215
        if len(functions) > 1:
            raise ValueError("GLM-4 does not support parallel functions.")

chenych's avatar
chenych committed
216
        return f"{functions[0].name}\n{functions[0].arguments}"
luopl's avatar
luopl committed
217

luopl's avatar
luopl committed
218
    @override
chenych's avatar
chenych committed
219
    @staticmethod
chenych's avatar
chenych committed
220
    def tool_extractor(content: str) -> Union[str, list["FunctionCall"]]:
chenych's avatar
chenych committed
221
222
223
224
225
        if "\n" not in content:
            return content

        tool_name, tool_input = content.split("\n", maxsplit=1)
        try:
luopl's avatar
luopl committed
226
227
228
229
230
231
232
233
            arguments = json.loads(tool_input.strip())
        except json.JSONDecodeError:
            return content

        return [FunctionCall(tool_name, json.dumps(arguments, ensure_ascii=False))]


class Llama3ToolUtils(ToolUtils):
chenych's avatar
chenych committed
234
    r"""Llama 3.x tool using template with `tools_in_user_message=False`.
luopl's avatar
luopl committed
235
236
237
238
239
240

    Reference: https://www.llama.com/docs/model-cards-and-prompt-formats/llama3_1/#json-based-tool-calling
    """

    @override
    @staticmethod
chenych's avatar
chenych committed
241
    def tool_formatter(tools: list[dict[str, Any]]) -> str:
luopl's avatar
luopl committed
242
243
244
        date = datetime.now().strftime("%d %b %Y")
        tool_text = ""
        for tool in tools:
chenych's avatar
chenych committed
245
            wrapped_tool = tool if tool.get("type") == "function" else {"type": "function", "function": tool}
luopl's avatar
luopl committed
246
247
248
249
250
251
            tool_text += json.dumps(wrapped_tool, indent=4, ensure_ascii=False) + "\n\n"

        return LLAMA3_TOOL_PROMPT.format(date=date, tool_text=tool_text)

    @override
    @staticmethod
chenych's avatar
chenych committed
252
    def function_formatter(functions: list["FunctionCall"]) -> str:
chenych's avatar
chenych committed
253
254
        function_objects = [{"name": name, "parameters": json.loads(arguments)} for name, arguments in functions]
        return json.dumps(function_objects[0] if len(function_objects) == 1 else function_objects, ensure_ascii=False)
luopl's avatar
luopl committed
255
256
257

    @override
    @staticmethod
chenych's avatar
chenych committed
258
    def tool_extractor(content: str) -> Union[str, list["FunctionCall"]]:
luopl's avatar
luopl committed
259
        try:
chenych's avatar
chenych committed
260
            tools = json.loads(content.strip())
chenych's avatar
chenych committed
261
262
263
        except json.JSONDecodeError:
            return content

chenych's avatar
chenych committed
264
265
266
267
        tools = [tools] if not isinstance(tools, list) else tools
        try:
            return [FunctionCall(tool["name"], json.dumps(tool["parameters"], ensure_ascii=False)) for tool in tools]
        except KeyError:
luopl's avatar
luopl committed
268
269
270
            return content


shihm's avatar
uodata  
shihm committed
271
272
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
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
class MiniMaxM1ToolUtils(ToolUtils):
    r"""MiniMax-M1 tool using template."""

    @override
    @staticmethod
    def tool_formatter(tools: list[dict[str, Any]]) -> str:
        tool_text = ""
        for tool in tools:
            tool = tool.get("function", "") if tool.get("type") == "function" else tool
            tool_text += json.dumps(tool, ensure_ascii=False) + "\n"

        return MINIMAX_M1_TOOL_PROMPT.format(tool_text=tool_text)

    @override
    @staticmethod
    def function_formatter(functions: list["FunctionCall"]) -> str:
        function_texts = []
        for func in functions:
            name, arguments = func.name, json.loads(func.arguments)
            function_texts.append(json.dumps({"name": name, "arguments": arguments}, ensure_ascii=False))

        return "<tool_calls>\n" + "\n".join(function_texts) + "\n</tool_calls>"

    @override
    @staticmethod
    def tool_extractor(content: str) -> Union[str, list["FunctionCall"]]:
        regex = re.compile(r"<tool_calls>\s*(.+?)\s*</tool_calls>", re.DOTALL)
        tool_match = re.search(regex, content)
        if not tool_match:
            return content

        tool_calls_content = tool_match.group(1)
        results = []
        for line in tool_calls_content.split("\n"):
            line = line.strip()
            if not line:
                continue

            try:
                tool_call = json.loads(line)
                results.append(FunctionCall(tool_call["name"], json.dumps(tool_call["arguments"], ensure_ascii=False)))
            except json.JSONDecodeError:
                continue

        return results


class MiniMaxM2ToolUtils(ToolUtils):
    r"""MiniMax-M2 tool using template."""

    @override
    @staticmethod
    def tool_formatter(tools: list[dict[str, Any]]) -> str:
        tool_text = ""
        for tool in tools:
            tool = tool.get("function", "") if tool.get("type") == "function" else tool
            tool_text += "<tool>" + json.dumps(tool, ensure_ascii=False) + "</tool>\n"

        return MINIMAX_M2_TOOL_PROMPT.format(tool_text=tool_text)

    @override
    @staticmethod
    def function_formatter(functions: list["FunctionCall"]) -> str:
        function_texts = []
        for func in functions:
            name, arguments = func.name, json.loads(func.arguments)
            prompt = f'<invoke name="{name}">'
            for key, value in arguments.items():
                prompt += f'\n<parameter name="{key}">'
                if not isinstance(value, str):
                    value = json.dumps(value, ensure_ascii=False)
                prompt += value + "</parameter>"
            prompt += "\n</invoke>"
            function_texts.append(prompt)

    @override
    @staticmethod
    def tool_extractor(content: str) -> Union[str, list["FunctionCall"]]:
        regex = re.compile(r"<minimax:tool_call>\s*(.+?)\s*</minimax:tool_call>", re.DOTALL)
        tool_match = re.search(regex, content)
        if not tool_match:
            return content

        tool_calls_content = tool_match.group(1)
        invoke_regex = re.compile(r"<invoke name=\"(.*?)\">(.*?)</invoke>", re.DOTALL)
        results = []

        for func_name, params_block in re.findall(invoke_regex, tool_calls_content):
            args_dict = {}
            param_pattern = re.compile(r"<parameter name=\"(.*?)\">(.*?)</parameter>", re.DOTALL)
            for key, raw_value in re.findall(param_pattern, params_block):
                value = raw_value.strip()
                try:
                    parsed_value = json.loads(value)
                except json.JSONDecodeError:
                    parsed_value = raw_value
                args_dict[key] = parsed_value

            results.append(FunctionCall(func_name.strip(), json.dumps(args_dict, ensure_ascii=False)))

        return results


luopl's avatar
luopl committed
374
class MistralToolUtils(ToolUtils):
chenych's avatar
chenych committed
375
    r"""Mistral v0.3 tool using template."""
luopl's avatar
luopl committed
376
377
378

    @override
    @staticmethod
chenych's avatar
chenych committed
379
    def tool_formatter(tools: list[dict[str, Any]]) -> str:
luopl's avatar
luopl committed
380
381
        wrapped_tools = []
        for tool in tools:
chenych's avatar
chenych committed
382
            wrapped_tools.append(tool if tool.get("type") == "function" else {"type": "function", "function": tool})
luopl's avatar
luopl committed
383
384
385
386
387

        return "[AVAILABLE_TOOLS] " + json.dumps(wrapped_tools, ensure_ascii=False) + "[/AVAILABLE_TOOLS]"

    @override
    @staticmethod
chenych's avatar
chenych committed
388
    def function_formatter(functions: list["FunctionCall"]) -> str:
chenych's avatar
chenych committed
389
390
391
        return json.dumps(
            [{"name": name, "arguments": json.loads(arguments)} for name, arguments in functions], ensure_ascii=False
        )
luopl's avatar
luopl committed
392
393
394

    @override
    @staticmethod
chenych's avatar
chenych committed
395
    def tool_extractor(content: str) -> Union[str, list["FunctionCall"]]:
luopl's avatar
luopl committed
396
397
398
399
400
        try:
            tools = json.loads(content.strip())
        except json.JSONDecodeError:
            return content

chenych's avatar
chenych committed
401
402
403
404
405
        tools = [tools] if not isinstance(tools, list) else tools
        try:
            return [FunctionCall(tool["name"], json.dumps(tool["arguments"], ensure_ascii=False)) for tool in tools]
        except KeyError:
            return content
luopl's avatar
luopl committed
406
407
408


class QwenToolUtils(ToolUtils):
chenych's avatar
chenych committed
409
    r"""Qwen 2.5 tool using template."""
luopl's avatar
luopl committed
410
411
412

    @override
    @staticmethod
chenych's avatar
chenych committed
413
    def tool_formatter(tools: list[dict[str, Any]]) -> str:
luopl's avatar
luopl committed
414
415
        tool_text = ""
        for tool in tools:
chenych's avatar
chenych committed
416
            wrapped_tool = tool if tool.get("type") == "function" else {"type": "function", "function": tool}
luopl's avatar
luopl committed
417
418
419
420
421
422
            tool_text += "\n" + json.dumps(wrapped_tool, ensure_ascii=False)

        return QWEN_TOOL_PROMPT.format(tool_text=tool_text)

    @override
    @staticmethod
chenych's avatar
chenych committed
423
    def function_formatter(functions: list["FunctionCall"]) -> str:
chenych's avatar
chenych committed
424
425
426
427
428
        function_texts = [
            json.dumps({"name": name, "arguments": json.loads(arguments)}, ensure_ascii=False)
            for name, arguments in functions
        ]
        return "\n".join([f"<tool_call>\n{text}\n</tool_call>" for text in function_texts])
luopl's avatar
luopl committed
429
430
431

    @override
    @staticmethod
chenych's avatar
chenych committed
432
    def tool_extractor(content: str) -> Union[str, list["FunctionCall"]]:
luopl's avatar
luopl committed
433
        regex = re.compile(r"<tool_call>(.+?)</tool_call>(?=\s*<tool_call>|\s*$)", re.DOTALL)
chenych's avatar
chenych committed
434
        tool_match: list[str] = re.findall(regex, content)
luopl's avatar
luopl committed
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
        if not tool_match:
            return content

        results = []
        for tool in tool_match:
            try:
                tool = json.loads(tool.strip())
            except json.JSONDecodeError:
                return content

            if "name" not in tool or "arguments" not in tool:
                return content

            results.append(FunctionCall(tool["name"], json.dumps(tool["arguments"], ensure_ascii=False)))

        return results
luopl's avatar
luopl committed
451
452


shihm's avatar
uodata  
shihm committed
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
class GLM4MOEToolUtils(QwenToolUtils):
    r"""GLM-4-MOE tool using template."""

    @override
    @staticmethod
    def tool_formatter(tools: list[dict[str, Any]]) -> str:
        tool_text = ""
        for tool in tools:
            wrapped_tool = tool if tool.get("type") == "function" else {"type": "function", "function": tool}
            tool_text += "\n" + json.dumps(wrapped_tool, ensure_ascii=False)

        return GLM4_MOE_TOOL_PROMPT.format(tool_text=tool_text)

    @override
    @staticmethod
    def function_formatter(functions: list["FunctionCall"]) -> str:
        function_json = [
            {"func_name": name, "func_key_values": json.loads(arguments)} for name, arguments in functions
        ]
        function_texts = []
        for func in function_json:
            prompt = "\n<tool_call>" + func["func_name"]
            for key, value in func["func_key_values"].items():
                prompt += "\n<arg_key>" + key + "</arg_key>"
                if not isinstance(value, str):
                    value = json.dumps(value, ensure_ascii=False)
                prompt += "\n<arg_value>" + value + "</arg_value>"
            function_texts.append(prompt)

        return "\n".join(function_texts)


class SeedToolUtils(ToolUtils):
    r"""Seed tool using template."""

    @override
    @staticmethod
    def tool_formatter(tools: list[dict[str, Any]]) -> str:
        return SEED_TOOL_PROMPT.format(tool_text="\n" + json.dumps(tools, ensure_ascii=False))

    @override
    @staticmethod
    def function_formatter(functions: list["FunctionCall"]) -> str:
        function_json = [
            {"func_name": name, "func_key_values": json.loads(arguments)} for name, arguments in functions
        ]
        function_texts = []
        for func in function_json:
            prompt = "\n<seed:tool_call>\n<function=" + func["func_name"]
            for key, value in func["func_key_values"].items():
                prompt += "\n<parameter=" + key + ">"
                if not isinstance(value, str):
                    value = json.dumps(value, ensure_ascii=False)
                prompt += value + "</parameter>"
            prompt += "\n</function>\n</seed:tool_call>"
            function_texts.append(prompt)

        return "\n".join(function_texts)

    @override
    @staticmethod
    def tool_extractor(content: str) -> Union[str, list["FunctionCall"]]:
        results = []
        regex = re.compile(
            r"<seed:tool_call>\s*<function=\s*([^\s<]+)\s*(.*?)\s*</function>\s*</seed:tool_call>", re.DOTALL
        )
        for func_name, params_block in re.findall(regex, content):
            args_dict = {}
            param_pattern = re.compile(r"<parameter=(.*?)>(.*?)</parameter>", re.DOTALL)
            for key, raw_value in re.findall(param_pattern, params_block.strip()):
                value = raw_value.strip()
                try:
                    parsed_value = json.loads(value)
                except json.JSONDecodeError:
                    parsed_value = raw_value
                args_dict[key] = parsed_value

            results.append(FunctionCall(func_name.strip(), json.dumps(args_dict, ensure_ascii=False)))

        return results


class LingToolUtils(QwenToolUtils):
    r"""Ling v2 tool using template."""

    @override
    @staticmethod
    def tool_formatter(tools: list[dict[str, Any]]) -> str:
        tool_text = ""
        for tool in tools:
            wrapped_tool = tool if tool.get("type") == "function" else {"type": "function", "function": tool}
            tool_text += "\n" + json.dumps(wrapped_tool, ensure_ascii=False)

        return LING_TOOL_PROMPT.format(tool_text=tool_text) + "\n" + "detailed thinking off"


luopl's avatar
luopl committed
549
550
551
TOOLS = {
    "default": DefaultToolUtils(),
    "glm4": GLM4ToolUtils(),
luopl's avatar
luopl committed
552
    "llama3": Llama3ToolUtils(),
shihm's avatar
uodata  
shihm committed
553
554
    "minimax1": MiniMaxM1ToolUtils(),
    "minimax2": MiniMaxM2ToolUtils(),
luopl's avatar
luopl committed
555
556
    "mistral": MistralToolUtils(),
    "qwen": QwenToolUtils(),
shihm's avatar
uodata  
shihm committed
557
558
559
    "glm4_moe": GLM4MOEToolUtils(),
    "seed_oss": SeedToolUtils(),
    "ling": LingToolUtils(),
luopl's avatar
luopl committed
560
561
562
563
564
565
}


def get_tool_utils(name: str) -> "ToolUtils":
    tool_utils = TOOLS.get(name, None)
    if tool_utils is None:
luopl's avatar
luopl committed
566
        raise ValueError(f"Tool utils `{name}` not found.")
luopl's avatar
luopl committed
567
568

    return tool_utils