test_formatter.py 11.5 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
#
# 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
luopl's avatar
luopl committed
16
from datetime import datetime
chenych's avatar
chenych committed
17

shihm's avatar
uodata  
shihm committed
18
19
import pytest

chenych's avatar
chenych committed
20
21
22
from llamafactory.data.formatter import EmptyFormatter, FunctionFormatter, StringFormatter, ToolFormatter


luopl's avatar
luopl committed
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
FUNCTION = {"name": "tool_name", "arguments": {"foo": "bar", "size": 10}}

TOOLS = [
    {
        "name": "test_tool",
        "description": "tool_desc",
        "parameters": {
            "type": "object",
            "properties": {
                "foo": {"type": "string", "description": "foo_desc"},
                "bar": {"type": "number", "description": "bar_desc"},
            },
            "required": ["foo"],
        },
    }
]


shihm's avatar
uodata  
shihm committed
41
@pytest.mark.runs_on(["cpu", "mps"])
chenych's avatar
chenych committed
42
43
44
45
46
def test_empty_formatter():
    formatter = EmptyFormatter(slots=["\n"])
    assert formatter.apply() == ["\n"]


shihm's avatar
uodata  
shihm committed
47
@pytest.mark.runs_on(["cpu", "mps"])
chenych's avatar
chenych committed
48
49
50
51
52
def test_string_formatter():
    formatter = StringFormatter(slots=["<s>", "Human: {{content}}\nAssistant:"])
    assert formatter.apply(content="Hi") == ["<s>", "Human: Hi\nAssistant:"]


shihm's avatar
uodata  
shihm committed
53
@pytest.mark.runs_on(["cpu", "mps"])
chenych's avatar
chenych committed
54
def test_function_formatter():
luopl's avatar
luopl committed
55
56
    formatter = FunctionFormatter(slots=["{{content}}", "</s>"], tool_format="default")
    tool_calls = json.dumps(FUNCTION)
chenych's avatar
chenych committed
57
    assert formatter.apply(content=tool_calls) == [
chenych's avatar
chenych committed
58
        """Action: tool_name\nAction Input: {"foo": "bar", "size": 10}""",
luopl's avatar
luopl committed
59
        "</s>",
chenych's avatar
chenych committed
60
61
62
    ]


shihm's avatar
uodata  
shihm committed
63
@pytest.mark.runs_on(["cpu", "mps"])
chenych's avatar
chenych committed
64
def test_multi_function_formatter():
luopl's avatar
luopl committed
65
66
    formatter = FunctionFormatter(slots=["{{content}}", "</s>"], tool_format="default")
    tool_calls = json.dumps([FUNCTION] * 2)
chenych's avatar
chenych committed
67
    assert formatter.apply(content=tool_calls) == [
luopl's avatar
luopl committed
68
        """Action: tool_name\nAction Input: {"foo": "bar", "size": 10}\n"""
chenych's avatar
chenych committed
69
        """Action: tool_name\nAction Input: {"foo": "bar", "size": 10}""",
luopl's avatar
luopl committed
70
        "</s>",
chenych's avatar
chenych committed
71
72
73
    ]


shihm's avatar
uodata  
shihm committed
74
@pytest.mark.runs_on(["cpu", "mps"])
chenych's avatar
chenych committed
75
76
def test_default_tool_formatter():
    formatter = ToolFormatter(tool_format="default")
luopl's avatar
luopl committed
77
    assert formatter.apply(content=json.dumps(TOOLS)) == [
chenych's avatar
chenych committed
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
        "You have access to the following tools:\n"
        "> Tool Name: test_tool\n"
        "Tool Description: tool_desc\n"
        "Tool Args:\n"
        "  - foo (string, required): foo_desc\n"
        "  - bar (number): bar_desc\n\n"
        "Use the following format if using a tool:\n"
        "```\n"
        "Action: tool name (one of [test_tool])\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"
    ]


shihm's avatar
uodata  
shihm committed
93
@pytest.mark.runs_on(["cpu", "mps"])
chenych's avatar
chenych committed
94
95
def test_default_tool_extractor():
    formatter = ToolFormatter(tool_format="default")
chenych's avatar
chenych committed
96
    result = """Action: test_tool\nAction Input: {"foo": "bar", "size": 10}"""
chenych's avatar
chenych committed
97
98
99
    assert formatter.extract(result) == [("test_tool", """{"foo": "bar", "size": 10}""")]


shihm's avatar
uodata  
shihm committed
100
@pytest.mark.runs_on(["cpu", "mps"])
chenych's avatar
chenych committed
101
102
103
104
def test_default_multi_tool_extractor():
    formatter = ToolFormatter(tool_format="default")
    result = (
        """Action: test_tool\nAction Input: {"foo": "bar", "size": 10}\n"""
chenych's avatar
chenych committed
105
        """Action: another_tool\nAction Input: {"foo": "job", "size": 2}"""
chenych's avatar
chenych committed
106
107
108
109
110
111
112
    )
    assert formatter.extract(result) == [
        ("test_tool", """{"foo": "bar", "size": 10}"""),
        ("another_tool", """{"foo": "job", "size": 2}"""),
    ]


shihm's avatar
uodata  
shihm committed
113
@pytest.mark.runs_on(["cpu", "mps"])
luopl's avatar
luopl committed
114
115
116
117
118
119
def test_glm4_function_formatter():
    formatter = FunctionFormatter(slots=["{{content}}"], tool_format="glm4")
    tool_calls = json.dumps(FUNCTION)
    assert formatter.apply(content=tool_calls) == ["""tool_name\n{"foo": "bar", "size": 10}"""]


shihm's avatar
uodata  
shihm committed
120
@pytest.mark.runs_on(["cpu", "mps"])
chenych's avatar
chenych committed
121
122
def test_glm4_tool_formatter():
    formatter = ToolFormatter(tool_format="glm4")
luopl's avatar
luopl committed
123
    assert formatter.apply(content=json.dumps(TOOLS)) == [
chenych's avatar
chenych committed
124
125
        "你是一个名为 ChatGLM 的人工智能助手。你是基于智谱 AI 公司训练的语言模型 GLM-4 模型开发的,"
        "你的任务是针对用户的问题和要求提供适当的答复和支持。\n\n# 可用工具\n\n"
chenych's avatar
chenych committed
126
127
        f"## test_tool\n\n{json.dumps(TOOLS[0], indent=4, ensure_ascii=False)}\n"
        "在调用上述函数时,请使用 Json 格式表示调用的参数。"
chenych's avatar
chenych committed
128
129
130
    ]


shihm's avatar
uodata  
shihm committed
131
@pytest.mark.runs_on(["cpu", "mps"])
chenych's avatar
chenych committed
132
133
134
135
def test_glm4_tool_extractor():
    formatter = ToolFormatter(tool_format="glm4")
    result = """test_tool\n{"foo": "bar", "size": 10}\n"""
    assert formatter.extract(result) == [("test_tool", """{"foo": "bar", "size": 10}""")]
luopl's avatar
luopl committed
136
137


shihm's avatar
uodata  
shihm committed
138
@pytest.mark.runs_on(["cpu", "mps"])
luopl's avatar
luopl committed
139
def test_llama3_function_formatter():
chenych's avatar
chenych committed
140
    formatter = FunctionFormatter(slots=["{{content}}<|eot_id|>"], tool_format="llama3")
chenych's avatar
chenych committed
141
    tool_calls = json.dumps(FUNCTION)
luopl's avatar
luopl committed
142
    assert formatter.apply(content=tool_calls) == [
chenych's avatar
chenych committed
143
        """{"name": "tool_name", "parameters": {"foo": "bar", "size": 10}}<|eot_id|>"""
luopl's avatar
luopl committed
144
145
146
    ]


shihm's avatar
uodata  
shihm committed
147
@pytest.mark.runs_on(["cpu", "mps"])
chenych's avatar
chenych committed
148
149
150
151
152
153
154
155
156
157
def test_llama3_multi_function_formatter():
    formatter = FunctionFormatter(slots=["{{content}}<|eot_id|>"], tool_format="llama3")
    tool_calls = json.dumps([FUNCTION] * 2)
    assert formatter.apply(content=tool_calls) == [
        """[{"name": "tool_name", "parameters": {"foo": "bar", "size": 10}}, """
        """{"name": "tool_name", "parameters": {"foo": "bar", "size": 10}}]"""
        """<|eot_id|>"""
    ]


shihm's avatar
uodata  
shihm committed
158
@pytest.mark.runs_on(["cpu", "mps"])
luopl's avatar
luopl committed
159
160
161
162
163
164
def test_llama3_tool_formatter():
    formatter = ToolFormatter(tool_format="llama3")
    date = datetime.now().strftime("%d %b %Y")
    wrapped_tool = {"type": "function", "function": TOOLS[0]}
    assert formatter.apply(content=json.dumps(TOOLS)) == [
        f"Cutting Knowledge Date: December 2023\nToday Date: {date}\n\n"
chenych's avatar
chenych committed
165
166
        "You have access to the following functions. "
        "To call a function, please respond with JSON for a function call. "
luopl's avatar
luopl committed
167
168
169
170
171
        """Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}. """
        f"Do not use variables.\n\n{json.dumps(wrapped_tool, indent=4, ensure_ascii=False)}\n\n"
    ]


shihm's avatar
uodata  
shihm committed
172
@pytest.mark.runs_on(["cpu", "mps"])
luopl's avatar
luopl committed
173
174
175
176
177
178
def test_llama3_tool_extractor():
    formatter = ToolFormatter(tool_format="llama3")
    result = """{"name": "test_tool", "parameters": {"foo": "bar", "size": 10}}\n"""
    assert formatter.extract(result) == [("test_tool", """{"foo": "bar", "size": 10}""")]


shihm's avatar
uodata  
shihm committed
179
@pytest.mark.runs_on(["cpu", "mps"])
chenych's avatar
chenych committed
180
181
182
183
184
185
186
187
188
189
190
191
def test_llama3_multi_tool_extractor():
    formatter = ToolFormatter(tool_format="llama3")
    result = (
        """[{"name": "test_tool", "parameters": {"foo": "bar", "size": 10}}, """
        """{"name": "another_tool", "parameters": {"foo": "job", "size": 2}}]"""
    )
    assert formatter.extract(result) == [
        ("test_tool", """{"foo": "bar", "size": 10}"""),
        ("another_tool", """{"foo": "job", "size": 2}"""),
    ]


shihm's avatar
uodata  
shihm committed
192
@pytest.mark.runs_on(["cpu", "mps"])
luopl's avatar
luopl committed
193
def test_mistral_function_formatter():
chenych's avatar
chenych committed
194
    formatter = FunctionFormatter(slots=["[TOOL_CALLS] {{content}}", "</s>"], tool_format="mistral")
luopl's avatar
luopl committed
195
196
    tool_calls = json.dumps(FUNCTION)
    assert formatter.apply(content=tool_calls) == [
chenych's avatar
chenych committed
197
        "[TOOL_CALLS] " """[{"name": "tool_name", "arguments": {"foo": "bar", "size": 10}}]""",
luopl's avatar
luopl committed
198
199
200
201
        "</s>",
    ]


shihm's avatar
uodata  
shihm committed
202
@pytest.mark.runs_on(["cpu", "mps"])
luopl's avatar
luopl committed
203
def test_mistral_multi_function_formatter():
chenych's avatar
chenych committed
204
    formatter = FunctionFormatter(slots=["[TOOL_CALLS] {{content}}", "</s>"], tool_format="mistral")
luopl's avatar
luopl committed
205
206
    tool_calls = json.dumps([FUNCTION] * 2)
    assert formatter.apply(content=tool_calls) == [
chenych's avatar
chenych committed
207
        "[TOOL_CALLS] "
luopl's avatar
luopl committed
208
209
210
211
212
213
        """[{"name": "tool_name", "arguments": {"foo": "bar", "size": 10}}, """
        """{"name": "tool_name", "arguments": {"foo": "bar", "size": 10}}]""",
        "</s>",
    ]


shihm's avatar
uodata  
shihm committed
214
@pytest.mark.runs_on(["cpu", "mps"])
luopl's avatar
luopl committed
215
216
217
218
219
220
221
222
def test_mistral_tool_formatter():
    formatter = ToolFormatter(tool_format="mistral")
    wrapped_tool = {"type": "function", "function": TOOLS[0]}
    assert formatter.apply(content=json.dumps(TOOLS)) == [
        "[AVAILABLE_TOOLS] " + json.dumps([wrapped_tool], ensure_ascii=False) + "[/AVAILABLE_TOOLS]"
    ]


shihm's avatar
uodata  
shihm committed
223
@pytest.mark.runs_on(["cpu", "mps"])
luopl's avatar
luopl committed
224
225
226
227
228
229
def test_mistral_tool_extractor():
    formatter = ToolFormatter(tool_format="mistral")
    result = """{"name": "test_tool", "arguments": {"foo": "bar", "size": 10}}"""
    assert formatter.extract(result) == [("test_tool", """{"foo": "bar", "size": 10}""")]


shihm's avatar
uodata  
shihm committed
230
@pytest.mark.runs_on(["cpu", "mps"])
luopl's avatar
luopl committed
231
232
233
234
235
236
237
238
239
240
241
242
def test_mistral_multi_tool_extractor():
    formatter = ToolFormatter(tool_format="mistral")
    result = (
        """[{"name": "test_tool", "arguments": {"foo": "bar", "size": 10}}, """
        """{"name": "another_tool", "arguments": {"foo": "job", "size": 2}}]"""
    )
    assert formatter.extract(result) == [
        ("test_tool", """{"foo": "bar", "size": 10}"""),
        ("another_tool", """{"foo": "job", "size": 2}"""),
    ]


shihm's avatar
uodata  
shihm committed
243
@pytest.mark.runs_on(["cpu", "mps"])
luopl's avatar
luopl committed
244
def test_qwen_function_formatter():
chenych's avatar
chenych committed
245
    formatter = FunctionFormatter(slots=["{{content}}<|im_end|>\n"], tool_format="qwen")
luopl's avatar
luopl committed
246
247
    tool_calls = json.dumps(FUNCTION)
    assert formatter.apply(content=tool_calls) == [
chenych's avatar
chenych committed
248
        """<tool_call>\n{"name": "tool_name", "arguments": {"foo": "bar", "size": 10}}\n</tool_call><|im_end|>\n"""
luopl's avatar
luopl committed
249
250
251
    ]


shihm's avatar
uodata  
shihm committed
252
@pytest.mark.runs_on(["cpu", "mps"])
luopl's avatar
luopl committed
253
def test_qwen_multi_function_formatter():
chenych's avatar
chenych committed
254
    formatter = FunctionFormatter(slots=["{{content}}<|im_end|>\n"], tool_format="qwen")
luopl's avatar
luopl committed
255
256
257
    tool_calls = json.dumps([FUNCTION] * 2)
    assert formatter.apply(content=tool_calls) == [
        """<tool_call>\n{"name": "tool_name", "arguments": {"foo": "bar", "size": 10}}\n</tool_call>\n"""
chenych's avatar
chenych committed
258
259
        """<tool_call>\n{"name": "tool_name", "arguments": {"foo": "bar", "size": 10}}\n</tool_call>"""
        "<|im_end|>\n"
luopl's avatar
luopl committed
260
261
262
    ]


shihm's avatar
uodata  
shihm committed
263
@pytest.mark.runs_on(["cpu", "mps"])
luopl's avatar
luopl committed
264
265
266
267
268
269
270
271
272
def test_qwen_tool_formatter():
    formatter = ToolFormatter(tool_format="qwen")
    wrapped_tool = {"type": "function", "function": TOOLS[0]}
    assert formatter.apply(content=json.dumps(TOOLS)) == [
        "\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>"
        f"\n{json.dumps(wrapped_tool, ensure_ascii=False)}"
        "\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
273
        """"arguments": <args-json-object>}\n</tool_call>"""
luopl's avatar
luopl committed
274
275
276
    ]


shihm's avatar
uodata  
shihm committed
277
@pytest.mark.runs_on(["cpu", "mps"])
luopl's avatar
luopl committed
278
279
280
281
282
283
def test_qwen_tool_extractor():
    formatter = ToolFormatter(tool_format="qwen")
    result = """<tool_call>\n{"name": "test_tool", "arguments": {"foo": "bar", "size": 10}}\n</tool_call>"""
    assert formatter.extract(result) == [("test_tool", """{"foo": "bar", "size": 10}""")]


shihm's avatar
uodata  
shihm committed
284
@pytest.mark.runs_on(["cpu", "mps"])
luopl's avatar
luopl committed
285
286
287
288
289
290
291
292
293
294
def test_qwen_multi_tool_extractor():
    formatter = ToolFormatter(tool_format="qwen")
    result = (
        """<tool_call>\n{"name": "test_tool", "arguments": {"foo": "bar", "size": 10}}\n</tool_call>\n"""
        """<tool_call>\n{"name": "another_tool", "arguments": {"foo": "job", "size": 2}}\n</tool_call>"""
    )
    assert formatter.extract(result) == [
        ("test_tool", """{"foo": "bar", "size": 10}"""),
        ("another_tool", """{"foo": "job", "size": 2}"""),
    ]