tool_utils.py 5.72 KB
Newer Older
chenych's avatar
chenych committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Copyright 2024 the LlamaFactory team.
#
# 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
luopl's avatar
luopl committed
18
from collections import namedtuple
chenych's avatar
chenych committed
19
20
21
from dataclasses import dataclass
from typing import Any, Dict, List, Tuple, Union

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

chenych's avatar
chenych committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from .data_utils import SLOTS


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 = (
    "你是一个名为 ChatGLM 的人工智能助手。你是基于智谱AI训练的语言模型 GLM-4 模型开发的,"
    "你的任务是针对用户的问题和要求提供适当的答复和支持。# 可用工具{tool_text}"
)


luopl's avatar
luopl committed
44
45
46
FunctionCall = namedtuple("FunctionCall", ["name", "arguments"])


chenych's avatar
chenych committed
47
48
@dataclass
class ToolUtils(ABC):
luopl's avatar
luopl committed
49
50
51
52
    """
    Base class for tool utilities.
    """

chenych's avatar
chenych committed
53
54
    @staticmethod
    @abstractmethod
luopl's avatar
luopl committed
55
56
57
58
59
    def get_function_slots() -> SLOTS:
        r"""
        Gets a list of slots corresponding to a single function call.
        """
        ...
chenych's avatar
chenych committed
60
61
62

    @staticmethod
    @abstractmethod
luopl's avatar
luopl committed
63
64
65
66
67
    def tool_formatter(tools: List[Dict[str, Any]]) -> str:
        r"""
        Generates the system message describing all the available tools.
        """
        ...
chenych's avatar
chenych committed
68
69
70

    @staticmethod
    @abstractmethod
luopl's avatar
luopl committed
71
72
73
74
75
    def tool_extractor(content: str) -> Union[str, List["FunctionCall"]]:
        r"""
        Extracts all the function calls from the response message.
        """
        ...
chenych's avatar
chenych committed
76
77
78


class DefaultToolUtils(ToolUtils):
luopl's avatar
luopl committed
79
    @override
chenych's avatar
chenych committed
80
81
82
83
    @staticmethod
    def get_function_slots() -> SLOTS:
        return ["Action: {{name}}\nAction Input: {{arguments}}\n"]

luopl's avatar
luopl committed
84
    @override
chenych's avatar
chenych committed
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
    @staticmethod
    def tool_formatter(tools: List[Dict[str, Any]]) -> str:
        tool_text = ""
        tool_names = []
        for tool in tools:
            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
118
    @override
chenych's avatar
chenych committed
119
    @staticmethod
luopl's avatar
luopl committed
120
    def tool_extractor(content: str) -> Union[str, List["FunctionCall"]]:
chenych's avatar
chenych committed
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
        regex = re.compile(r"Action:\s*([a-zA-Z0-9_]+)\s*Action Input:\s*(.+?)(?=\s*Action:|\s*$)", re.DOTALL)
        action_match: List[Tuple[str, str]] = re.findall(regex, content)
        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)
                results.append((tool_name, json.dumps(arguments, ensure_ascii=False)))
            except json.JSONDecodeError:
                return content

        return results


class GLM4ToolUtils(ToolUtils):
luopl's avatar
luopl committed
140
    @override
chenych's avatar
chenych committed
141
142
143
144
    @staticmethod
    def get_function_slots() -> SLOTS:
        return ["{{name}}\n{{arguments}}"]

luopl's avatar
luopl committed
145
    @override
chenych's avatar
chenych committed
146
147
148
149
150
151
152
153
154
155
    @staticmethod
    def tool_formatter(tools: List[Dict[str, Any]]) -> str:
        tool_text = ""
        for tool in tools:
            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
156
    @override
chenych's avatar
chenych committed
157
    @staticmethod
luopl's avatar
luopl committed
158
    def tool_extractor(content: str) -> Union[str, List["FunctionCall"]]:
chenych's avatar
chenych committed
159
160
161
162
163
164
165
166
167
168
        if "\n" not in content:
            return content

        tool_name, tool_input = content.split("\n", maxsplit=1)
        try:
            arguments = json.loads(tool_input)
        except json.JSONDecodeError:
            return content

        return [(tool_name, json.dumps(arguments, ensure_ascii=False))]
luopl's avatar
luopl committed
169
170
171
172
173
174
175
176
177
178
179
180
181
182


TOOLS = {
    "default": DefaultToolUtils(),
    "glm4": GLM4ToolUtils(),
}


def get_tool_utils(name: str) -> "ToolUtils":
    tool_utils = TOOLS.get(name, None)
    if tool_utils is None:
        raise ValueError("Tool utils `{}` not found.".format(name))

    return tool_utils