test_responses_utils.py 9.87 KB
Newer Older
1
2
3
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project

4
import pytest
5
from openai.types.chat import ChatCompletionMessageParam
6
from openai.types.responses.response_function_tool_call import ResponseFunctionToolCall
7
8
9
from openai.types.responses.response_function_tool_call_output_item import (
    ResponseFunctionToolCallOutputItem,
)
10
11
from openai.types.responses.response_output_message import ResponseOutputMessage
from openai.types.responses.response_output_text import ResponseOutputText
12
13
14
15
16
17
from openai.types.responses.response_reasoning_item import (
    Content,
    ResponseReasoningItem,
    Summary,
)

18
from vllm.entrypoints.constants import MCP_PREFIX
19
from vllm.entrypoints.responses_utils import (
20
    _construct_single_message_from_response_item,
21
    _maybe_combine_reasoning_and_tool_call,
22
    construct_chat_messages_with_tool_call,
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
    convert_tool_responses_to_completions_format,
)


class TestResponsesUtils:
    """Tests for convert_tool_responses_to_completions_format function."""

    def test_convert_tool_responses_to_completions_format(self):
        """Test basic conversion of a flat tool schema to nested format."""
        input_tool = {
            "type": "function",
            "name": "get_weather",
            "description": "Get the current weather in a given location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string"},
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                },
                "required": ["location", "unit"],
            },
        }

        result = convert_tool_responses_to_completions_format(input_tool)

        assert result == {"type": "function", "function": input_tool}
49

50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
    def test_construct_chat_messages_with_tool_call(self):
        """Test construction of chat messages with tool calls."""
        reasoning_item = ResponseReasoningItem(
            id="lol",
            summary=[],
            type="reasoning",
            content=[
                Content(
                    text="Leroy Jenkins",
                    type="reasoning_text",
                )
            ],
            encrypted_content=None,
            status=None,
        )
        mcp_tool_item = ResponseFunctionToolCall(
            id="mcp_123",
            call_id="call_123",
            type="function_call",
            status="completed",
            name="python",
            arguments='{"code": "123+456"}',
        )
        input_items = [reasoning_item, mcp_tool_item]
        messages = construct_chat_messages_with_tool_call(input_items)

        assert len(messages) == 1
        message = messages[0]
        assert message["role"] == "assistant"
        assert message["reasoning"] == "Leroy Jenkins"
        assert message["tool_calls"][0]["id"] == "call_123"
        assert message["tool_calls"][0]["function"]["name"] == "python"
        assert (
            message["tool_calls"][0]["function"]["arguments"] == '{"code": "123+456"}'
        )

    def test_construct_single_message_from_response_item(self):
87
88
89
90
91
92
93
94
95
96
97
98
99
        item = ResponseReasoningItem(
            id="lol",
            summary=[],
            type="reasoning",
            content=[
                Content(
                    text="Leroy Jenkins",
                    type="reasoning_text",
                )
            ],
            encrypted_content=None,
            status=None,
        )
100
        formatted_item = _construct_single_message_from_response_item(item)
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
        assert formatted_item["role"] == "assistant"
        assert formatted_item["reasoning"] == "Leroy Jenkins"

        item = ResponseReasoningItem(
            id="lol",
            summary=[
                Summary(
                    text='Hmm, the user has just started with a simple "Hello,"',
                    type="summary_text",
                )
            ],
            type="reasoning",
            content=None,
            encrypted_content=None,
            status=None,
        )

118
        formatted_item = _construct_single_message_from_response_item(item)
119
120
121
122
123
124
        assert formatted_item["role"] == "assistant"
        assert (
            formatted_item["reasoning"]
            == 'Hmm, the user has just started with a simple "Hello,"'
        )

125
126
127
128
129
130
131
        tool_call_output = ResponseFunctionToolCallOutputItem(
            id="temp_id",
            type="function_call_output",
            call_id="temp",
            output="1234",
            status="completed",
        )
132
        formatted_item = _construct_single_message_from_response_item(tool_call_output)
133
134
135
136
        assert formatted_item["role"] == "tool"
        assert formatted_item["content"] == "1234"
        assert formatted_item["tool_call_id"] == "temp"

137
138
139
140
141
142
143
144
145
        item = ResponseReasoningItem(
            id="lol",
            summary=[],
            type="reasoning",
            content=None,
            encrypted_content="TOP_SECRET_MESSAGE",
            status=None,
        )
        with pytest.raises(ValueError):
146
            _construct_single_message_from_response_item(item)
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162

        output_item = ResponseOutputMessage(
            id="msg_bf585bbbe3d500e0",
            content=[
                ResponseOutputText(
                    annotations=[],
                    text="dongyi",
                    type="output_text",
                    logprobs=None,
                )
            ],
            role="assistant",
            status="completed",
            type="message",
        )

163
        formatted_item = _construct_single_message_from_response_item(output_item)
164
165
        assert formatted_item["role"] == "assistant"
        assert formatted_item["content"] == "dongyi"
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280


class TestMaybeCombineReasoningAndToolCall:
    """Tests for _maybe_combine_reasoning_and_tool_call function."""

    def test_returns_none_when_item_id_is_none(self):
        """
        Test fix from PR #31999: when item.id is None, should return None
        instead of raising TypeError on startswith().
        """
        item = ResponseFunctionToolCall(
            type="function_call",
            id=None,  # This was causing TypeError before the fix
            call_id="call_123",
            name="test_function",
            arguments="{}",
        )
        messages: list[ChatCompletionMessageParam] = []

        result = _maybe_combine_reasoning_and_tool_call(item, messages)

        assert result is None

    def test_returns_none_when_id_does_not_start_with_mcp_prefix(self):
        """Test that non-MCP tool calls are not combined."""
        item = ResponseFunctionToolCall(
            type="function_call",
            id="regular_id",  # Does not start with MCP_PREFIX
            call_id="call_123",
            name="test_function",
            arguments="{}",
        )
        messages = [{"role": "assistant", "reasoning": "some reasoning"}]

        result = _maybe_combine_reasoning_and_tool_call(item, messages)

        assert result is None

    def test_returns_none_when_last_message_is_not_assistant(self):
        """Test that non-assistant last message returns None."""
        item = ResponseFunctionToolCall(
            type="function_call",
            id=f"{MCP_PREFIX}tool_id",
            call_id="call_123",
            name="test_function",
            arguments="{}",
        )
        messages = [{"role": "user", "content": "hello"}]

        result = _maybe_combine_reasoning_and_tool_call(item, messages)

        assert result is None

    def test_returns_none_when_last_message_has_no_reasoning(self):
        """Test that assistant message without reasoning returns None."""
        item = ResponseFunctionToolCall(
            type="function_call",
            id=f"{MCP_PREFIX}tool_id",
            call_id="call_123",
            name="test_function",
            arguments="{}",
        )
        messages = [{"role": "assistant", "content": "some content"}]

        result = _maybe_combine_reasoning_and_tool_call(item, messages)

        assert result is None

    def test_combines_reasoning_and_mcp_tool_call(self):
        """Test successful combination of reasoning message and MCP tool call."""
        item = ResponseFunctionToolCall(
            type="function_call",
            id=f"{MCP_PREFIX}tool_id",
            call_id="call_123",
            name="test_function",
            arguments='{"arg": "value"}',
        )
        messages = [{"role": "assistant", "reasoning": "I need to call this tool"}]

        result = _maybe_combine_reasoning_and_tool_call(item, messages)

        assert result is not None
        assert result["role"] == "assistant"
        assert result["reasoning"] == "I need to call this tool"
        assert "tool_calls" in result
        assert len(result["tool_calls"]) == 1
        assert result["tool_calls"][0]["id"] == "call_123"
        assert result["tool_calls"][0]["function"]["name"] == "test_function"
        assert result["tool_calls"][0]["function"]["arguments"] == '{"arg": "value"}'
        assert result["tool_calls"][0]["type"] == "function"

    def test_returns_none_for_non_function_tool_call_type(self):
        """Test that non-ResponseFunctionToolCall items return None."""
        # Pass a dict instead of ResponseFunctionToolCall
        item = {"type": "message", "content": "hello"}
        messages = [{"role": "assistant", "reasoning": "some reasoning"}]

        result = _maybe_combine_reasoning_and_tool_call(item, messages)

        assert result is None

    def test_returns_none_when_id_is_empty_string(self):
        """Test that empty string id returns None (falsy check)."""
        item = ResponseFunctionToolCall(
            type="function_call",
            id="",  # Empty string is falsy
            call_id="call_123",
            name="test_function",
            arguments="{}",
        )
        messages = [{"role": "assistant", "reasoning": "some reasoning"}]

        result = _maybe_combine_reasoning_and_tool_call(item, messages)

        assert result is None