responses_parser.py 7.63 KB
Newer Older
1
2
3
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import logging
4
from typing import Any
5

6
7
8
9
10
from openai.types.responses import ResponseFunctionToolCall, ResponseOutputItem
from openai.types.responses.response_function_tool_call_output_item import (
    ResponseFunctionToolCallOutputItem,
)
from openai.types.responses.response_output_item import McpCall
11
12
13
14
15
16
17
from openai.types.responses.response_output_message import ResponseOutputMessage
from openai.types.responses.response_output_text import ResponseOutputText
from openai.types.responses.response_reasoning_item import (
    Content,
    ResponseReasoningItem,
)

18
from vllm.entrypoints.chat_utils import ChatTemplateContentFormatOption
19
from vllm.entrypoints.constants import MCP_PREFIX
20
from vllm.entrypoints.openai.responses.protocol import (
21
22
23
    ResponseInputOutputItem,
    ResponsesRequest,
)
24
25
from vllm.outputs import CompletionOutput
from vllm.reasoning.abs_reasoning_parsers import ReasoningParser
26
from vllm.tokenizers import TokenizerLike
27
from vllm.tool_parsers.abstract_tool_parser import ToolParser
28
29
30
31
32
33
34
35
36
37
38
from vllm.utils import random_uuid

logger = logging.getLogger(__name__)


class ResponsesParser:
    """Incremental parser over completion tokens with reasoning support."""

    def __init__(
        self,
        *,
39
        tokenizer: TokenizerLike,
40
        reasoning_parser_cls: type[ReasoningParser],
41
42
        response_messages: list[ResponseInputOutputItem],
        request: ResponsesRequest,
43
        tool_parser_cls: type[ToolParser] | None,
44
45
        chat_template: str | None,
        chat_template_content_format: ChatTemplateContentFormatOption,
46
47
48
49
50
51
52
53
54
    ):
        self.response_messages: list[ResponseInputOutputItem] = (
            # TODO: initial messages may not be properly typed
            response_messages
        )
        self.num_init_messages = len(response_messages)
        self.tokenizer = tokenizer
        self.request = request

55
56
57
58
59
60
61
62
        self.reasoning_parser_instance = reasoning_parser_cls(
            tokenizer,
            chat_template_kwargs=_effective_chat_template_kwargs(
                request,
                chat_template=chat_template,
                chat_template_content_format=chat_template_content_format,
            ),
        )
63
64
        self.tool_parser_instance = None
        if tool_parser_cls is not None:
65
            self.tool_parser_instance = tool_parser_cls(tokenizer, request.tools)
66

67
68
69
        # Store the last finish_reason to determine response status
        self.finish_reason: str | None = None

70
    def process(self, output: CompletionOutput) -> "ResponsesParser":
71
72
73
        # Store the finish_reason from the output
        self.finish_reason = output.finish_reason

74
        reasoning, content = self.reasoning_parser_instance.extract_reasoning(
75
76
            output.text, request=self.request
        )
77
        if reasoning:
78
79
80
81
82
83
84
85
            self.response_messages.append(
                ResponseReasoningItem(
                    type="reasoning",
                    id=f"rs_{random_uuid()}",
                    summary=[],
                    content=[
                        Content(
                            type="reasoning_text",
86
                            text=reasoning,
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
        function_calls: list[ResponseFunctionToolCall] = []
        if self.tool_parser_instance is not None:
            tool_call_info = self.tool_parser_instance.extract_tool_calls(
                content if content is not None else "",
                request=self.request,  # type: ignore
            )
            if tool_call_info is not None and tool_call_info.tools_called:
                # extract_tool_calls() returns a list of tool calls.
                function_calls.extend(
                    ResponseFunctionToolCall(
                        id=f"fc_{random_uuid()}",
                        call_id=f"call_{random_uuid()}",
                        type="function_call",
                        status="completed",
                        name=tool_call.function.name,
                        arguments=tool_call.function.arguments,
                    )
                    for tool_call in tool_call_info.tool_calls
                )
                content = tool_call_info.content
                if content and content.strip() == "":
                    content = None

115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
        if content:
            self.response_messages.append(
                ResponseOutputMessage(
                    type="message",
                    id=f"msg_{random_uuid()}",
                    status="completed",
                    role="assistant",
                    content=[
                        ResponseOutputText(
                            annotations=[],  # TODO
                            type="output_text",
                            text=content,
                            logprobs=None,  # TODO
                        )
                    ],
                )
            )
132
133
        if len(function_calls) > 0:
            self.response_messages.extend(function_calls)
134
135
136

        return self

137
138
139
140
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
    def make_response_output_items_from_parsable_context(
        self,
    ) -> list[ResponseOutputItem]:
        """Given a list of sentences, construct ResponseOutput Items."""
        response_messages = self.response_messages[self.num_init_messages :]
        output_messages: list[ResponseOutputItem] = []
        for message in response_messages:
            if not isinstance(message, ResponseFunctionToolCallOutputItem):
                output_messages.append(message)
            else:
                if len(output_messages) == 0:
                    raise ValueError(
                        "Cannot have a FunctionToolCallOutput before FunctionToolCall."
                    )
                if isinstance(output_messages[-1], ResponseFunctionToolCall):
                    mcp_message = McpCall(
                        id=f"{MCP_PREFIX}{random_uuid()}",
                        arguments=output_messages[-1].arguments,
                        name=output_messages[-1].name,
                        server_label=output_messages[
                            -1
                        ].name,  # TODO: store the server label
                        type="mcp_call",
                        status="completed",
                        output=message.output,
                        # TODO: support error output
                    )
                    output_messages[-1] = mcp_message

        return output_messages

168
169
170

def get_responses_parser_for_simple_context(
    *,
171
    tokenizer: TokenizerLike,
172
    reasoning_parser_cls: type[ReasoningParser],
173
174
    response_messages: list[ResponseInputOutputItem],
    request: ResponsesRequest,
175
    tool_parser_cls,
176
177
    chat_template: str | None,
    chat_template_content_format: ChatTemplateContentFormatOption,
178
179
180
181
182
183
184
185
186
187
188
189
) -> ResponsesParser:
    """Factory function to create a ResponsesParser with
    optional reasoning parser.

    Returns:
        ResponsesParser instance configured with the provided parser
    """
    return ResponsesParser(
        tokenizer=tokenizer,
        reasoning_parser_cls=reasoning_parser_cls,
        response_messages=response_messages,
        request=request,
190
        tool_parser_cls=tool_parser_cls,
191
192
        chat_template=chat_template,
        chat_template_content_format=chat_template_content_format,
193
    )
194
195
196
197
198
199
200
201
202
203
204


def _effective_chat_template_kwargs(
    request: ResponsesRequest,
    chat_template: str | None,
    chat_template_content_format: ChatTemplateContentFormatOption,
) -> dict[str, Any]:
    return request.build_chat_params(
        default_template=chat_template,
        default_template_content_format=chat_template_content_format,
    ).chat_template_kwargs