main
py 268 lines 9.65 KB
Raw
1 # SPDX-License-Identifier: Apache-2.0
2 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3 # ruff: noqa: E501
4 """Tests for the GLM-4.7 tool call parser."""
5
6 import json
7 from unittest.mock import Mock
8
9 import pytest
10 from openai.types.responses import ResponseFunctionToolCall
11
12 from vllm.entrypoints.generate.base.protocol import FunctionCall
13 from vllm.entrypoints.openai.chat_completion.protocol import (
14 ChatCompletionRequest,
15 ChatCompletionToolsParam,
16 FunctionDefinition,
17 )
18 from vllm.entrypoints.openai.responses.protocol import ResponsesRequest
19 from vllm.entrypoints.openai.responses.utils import build_response_output_items
20 from vllm.tokenizers import get_tokenizer
21 from vllm.tool_parsers.glm47_moe_tool_parser import Glm47MoeModelToolParser
22
23 MODEL = "zai-org/GLM-4.7"
24
25
26 @pytest.fixture(scope="module")
27 def glm47_tokenizer():
28 return get_tokenizer(tokenizer_name=MODEL)
29
30
31 @pytest.fixture
32 def sample_tools():
33 return [
34 ChatCompletionToolsParam(
35 function=FunctionDefinition(name="get_current_date", parameters={}),
36 ),
37 ChatCompletionToolsParam(
38 function=FunctionDefinition(
39 name="get_weather",
40 parameters={
41 "type": "object",
42 "properties": {
43 "city": {"type": "string"},
44 "date": {"type": "string"},
45 },
46 },
47 ),
48 ),
49 ]
50
51
52 @pytest.fixture
53 def glm47_tool_parser(glm47_tokenizer, sample_tools):
54 return Glm47MoeModelToolParser(glm47_tokenizer, tools=sample_tools)
55
56
57 @pytest.fixture
58 def mock_request(sample_tools) -> ChatCompletionRequest:
59 request = Mock(spec=ChatCompletionRequest)
60 request.tools = sample_tools
61 request.tool_choice = "auto"
62 return request
63
64
65 @pytest.fixture
66 def namespace_tool_request() -> ResponsesRequest:
67 return ResponsesRequest.model_validate(
68 {
69 "input": "hi",
70 "tools": [
71 {
72 "type": "namespace",
73 "name": "mcp__computer_use",
74 "description": "Computer use tools.",
75 "tools": [
76 {
77 "type": "function",
78 "name": "get_app_state",
79 "description": "Get app state.",
80 "parameters": {
81 "type": "object",
82 "properties": {
83 "app": {"type": "string"},
84 },
85 },
86 }
87 ],
88 }
89 ],
90 }
91 )
92
93
94 class TestGlm47ExtractToolCalls:
95 def test_namespace_tool_call_round_trip_to_responses_output(
96 self, glm47_tokenizer, namespace_tool_request
97 ):
98 parser = Glm47MoeModelToolParser(
99 glm47_tokenizer, tools=namespace_tool_request.tools
100 )
101 out = (
102 "<tool_call>mcp__computer_use__get_app_state"
103 "<arg_key>app</arg_key>"
104 "<arg_value>Google Chrome</arg_value>"
105 "</tool_call>"
106 )
107
108 result = parser.extract_tool_calls(out, request=namespace_tool_request)
109
110 assert result.tools_called
111 tool_call = result.tool_calls[0].function
112 assert tool_call == FunctionCall(
113 name="mcp__computer_use__get_app_state",
114 arguments='{"app": "Google Chrome"}',
115 )
116
117 output_items = build_response_output_items(
118 reasoning=None,
119 content=None,
120 tool_calls=[tool_call],
121 tools=namespace_tool_request.tools,
122 )
123 output_tool_call = output_items[0]
124 assert isinstance(output_tool_call, ResponseFunctionToolCall)
125 assert output_tool_call.name == "get_app_state"
126 assert output_tool_call.namespace == "mcp__computer_use"
127
128 def test_no_tool_call(self, glm47_tool_parser, mock_request):
129 out = "This is a plain response."
130 r = glm47_tool_parser.extract_tool_calls(out, request=mock_request)
131 assert not r.tools_called
132 assert r.content == out
133
134 def test_zero_arg_inline(self, glm47_tool_parser, mock_request):
135 out = "<tool_call>get_current_date</tool_call>"
136 r = glm47_tool_parser.extract_tool_calls(out, request=mock_request)
137 assert r.tools_called
138 assert r.tool_calls[0].function.name == "get_current_date"
139 assert json.loads(r.tool_calls[0].function.arguments) == {}
140 assert r.content is None
141
142 def test_zero_arg_newline(self, glm47_tool_parser, mock_request):
143 out = "<tool_call>get_current_date\n</tool_call>"
144 r = glm47_tool_parser.extract_tool_calls(out, request=mock_request)
145 assert r.tools_called
146 assert r.tool_calls[0].function.name == "get_current_date"
147
148 def test_args_same_line(self, glm47_tool_parser, mock_request):
149 out = "<tool_call>get_weather<arg_key>city</arg_key><arg_value>Beijing</arg_value></tool_call>"
150 r = glm47_tool_parser.extract_tool_calls(out, request=mock_request)
151 assert r.tools_called
152 assert json.loads(r.tool_calls[0].function.arguments) == {"city": "Beijing"}
153
154 def test_args_with_newlines(self, glm47_tool_parser, mock_request):
155 out = "<tool_call>get_weather\n<arg_key>city</arg_key>\n<arg_value>Beijing</arg_value>\n</tool_call>"
156 r = glm47_tool_parser.extract_tool_calls(out, request=mock_request)
157 assert r.tools_called
158 assert json.loads(r.tool_calls[0].function.arguments) == {"city": "Beijing"}
159
160 def test_whitespace_preserved_in_arg_values(self, glm47_tool_parser, mock_request):
161 out = "<tool_call>get_weather<arg_key>city</arg_key><arg_value> Beijing </arg_value></tool_call>"
162 r = glm47_tool_parser.extract_tool_calls(out, request=mock_request)
163 assert r.tools_called
164 assert json.loads(r.tool_calls[0].function.arguments) == {"city": " Beijing "}
165
166 def test_content_before(self, glm47_tool_parser, mock_request):
167 out = "Checking.<tool_call>get_current_date</tool_call>"
168 r = glm47_tool_parser.extract_tool_calls(out, request=mock_request)
169 assert r.tools_called
170 assert r.content == "Checking."
171
172 def test_multiple(self, glm47_tool_parser, mock_request):
173 out = (
174 "<tool_call>get_weather<arg_key>city</arg_key><arg_value>Beijing</arg_value></tool_call>"
175 "<tool_call>get_weather<arg_key>city</arg_key><arg_value>Shanghai</arg_value></tool_call>"
176 )
177 r = glm47_tool_parser.extract_tool_calls(out, request=mock_request)
178 assert len(r.tool_calls) == 2
179
180 def test_empty_content_none(self, glm47_tool_parser, mock_request):
181 out = "<tool_call>get_current_date</tool_call>"
182 r = glm47_tool_parser.extract_tool_calls(out, request=mock_request)
183 assert r.content is None
184
185 def test_whitespace_content_none(self, glm47_tool_parser, mock_request):
186 out = " \n <tool_call>get_current_date</tool_call>"
187 r = glm47_tool_parser.extract_tool_calls(out, request=mock_request)
188 assert r.content is None
189
190
191 def _reset(parser):
192 parser.current_tool_name_sent = False
193 parser.prev_tool_call_arr = []
194 parser.current_tool_id = -1
195 parser.streamed_args_for_tool = []
196 parser._tool_call_ids = []
197 parser._sent_content_idx = 0
198
199
200 class TestGlm47Streaming:
201 def test_no_args(self, glm47_tool_parser, mock_request):
202 _reset(glm47_tool_parser)
203 chunks = ["<tool_call>", "get_current_date", "</tool_call>"]
204 current_text = ""
205 deltas = []
206 for chunk in chunks:
207 current_text += chunk
208 delta = glm47_tool_parser.extract_tool_calls_streaming(
209 previous_text="",
210 current_text=current_text,
211 delta_text=chunk,
212 previous_token_ids=[],
213 current_token_ids=[],
214 delta_token_ids=[],
215 request=mock_request,
216 )
217 if delta:
218 deltas.append(delta)
219 tool_calls = [
220 tool_call for delta in deltas for tool_call in (delta.tool_calls or [])
221 ]
222 names = [
223 tool_call.function.name
224 for tool_call in tool_calls
225 if tool_call.function and tool_call.function.name
226 ]
227 arguments = [
228 tool_call.function.arguments
229 for tool_call in tool_calls
230 if tool_call.function and tool_call.function.arguments
231 ]
232 assert names == ["get_current_date"]
233 assert "".join(arguments) == "{}"
234
235 def test_with_args(self, glm47_tool_parser, mock_request):
236 _reset(glm47_tool_parser)
237 chunks = [
238 "<tool_call>",
239 "get_weather\n",
240 "<arg_key>city</arg_key>",
241 "<arg_value>",
242 "Beijing",
243 "</arg_value>",
244 "</tool_call>",
245 ]
246 current_text = ""
247 deltas = []
248 for chunk in chunks:
249 current_text += chunk
250 delta = glm47_tool_parser.extract_tool_calls_streaming(
251 previous_text="",
252 current_text=current_text,
253 delta_text=chunk,
254 previous_token_ids=[],
255 current_token_ids=[],
256 delta_token_ids=[],
257 request=mock_request,
258 )
259 if delta:
260 deltas.append(delta)
261 arguments = [
262 tool_call.function.arguments
263 for delta in deltas
264 for tool_call in (delta.tool_calls or [])
265 if tool_call.function and tool_call.function.arguments
266 ]
267 args = json.loads("".join(arguments))
268 assert args["city"] == "Beijing"