context.py 10.7 KB
Newer Older
1
2
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
import json
4
5
import logging
from abc import ABC, abstractmethod
6
from collections.abc import Sequence
7
8
from contextlib import AsyncExitStack
from typing import TYPE_CHECKING, Optional, Union
9

10
from openai_harmony import Author, Message, Role, StreamState, TextContent
11
12
13
14

from vllm.entrypoints.harmony_utils import (
    get_encoding, get_streamable_parser_for_assistant, render_for_completion)
from vllm.entrypoints.tool import Tool
15
from vllm.entrypoints.tool_server import ToolServer
16
17
from vllm.outputs import RequestOutput

18
19
20
if TYPE_CHECKING:
    from mcp.client import ClientSession

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
logger = logging.getLogger(__name__)


class ConversationContext(ABC):

    @abstractmethod
    def append_output(self, output) -> None:
        pass

    @abstractmethod
    async def call_tool(self) -> list[Message]:
        pass

    @abstractmethod
    def need_builtin_tool_call(self) -> bool:
        pass

    @abstractmethod
    def render_for_completion(self) -> list[int]:
        pass

42
43
44
45
46
    @abstractmethod
    async def init_tool_sessions(self, tool_server: Optional[ToolServer],
                                 exit_stack: AsyncExitStack) -> None:
        pass

47
48
49
50
51

class SimpleContext(ConversationContext):

    def __init__(self):
        self.last_output = None
52
53
54
55
56
        self.num_prompt_tokens = 0
        self.num_output_tokens = 0
        self.num_cached_tokens = 0
        # todo num_reasoning_tokens is not implemented yet.
        self.num_reasoning_tokens = 0
57
58
59

    def append_output(self, output) -> None:
        self.last_output = output
60
61
62
63
64
        if not isinstance(output, RequestOutput):
            raise ValueError("SimpleContext only supports RequestOutput.")
        self.num_prompt_tokens = len(output.prompt_token_ids or [])
        self.num_cached_tokens = output.num_cached_tokens or 0
        self.num_output_tokens += len(output.outputs[0].token_ids or [])
65
66
67
68
69
70
71
72
73
74

    def need_builtin_tool_call(self) -> bool:
        return False

    async def call_tool(self) -> list[Message]:
        raise NotImplementedError("Should not be called.")

    def render_for_completion(self) -> list[int]:
        raise NotImplementedError("Should not be called.")

75
76
77
78
    async def init_tool_sessions(self, tool_server: Optional[ToolServer],
                                 exit_stack: AsyncExitStack) -> None:
        pass

79
80
81
82
83
84

class HarmonyContext(ConversationContext):

    def __init__(
        self,
        messages: list,
85
        available_tools: list[str],
86
87
    ):
        self._messages = messages
88
89
        self.available_tools = available_tools
        self._tool_sessions: dict[str, Union[ClientSession, Tool]] = {}
90
91
92
93
94

        self.parser = get_streamable_parser_for_assistant()
        self.num_init_messages = len(messages)
        self.num_prompt_tokens = 0
        self.num_output_tokens = 0
95
96
        # TODO(woosuk): Implement the following fields.
        self.num_cached_tokens = 0
97
98
        self.num_reasoning_tokens = 0

99
100
101
102
103
104
105
    def _update_num_prompt_tokens(self, output: RequestOutput):
        if output.prompt_token_ids and len(output.prompt_token_ids) > 0:
            # NOTE: with built-in tools, there might be multiple rounds in
            # the conversation, with the full conversation being resent
            # as new prompt each time. Hence the sum.
            self.num_prompt_tokens += len(output.prompt_token_ids)

106
107
108
109
110
    def _update_num_cached_tokens(self, output: RequestOutput):
        if output.num_cached_tokens is not None:
            #Similar to num_prompt_tokens
            self.num_cached_tokens += output.num_cached_tokens

111
112
113
    def _update_num_output_tokens(self, token_ids: Sequence[int]):
        self.num_output_tokens += len(token_ids)

114
115
116
117
118
119
120
121
122
123
    def _update_num_reasoning_tokens(self, token_ids: Sequence[int]):
        # Count tokens that are part of reasoning content (analysis channel
        # or tool-directed messages like python/browser calls)
        is_analysis = self.parser.current_channel == "analysis"
        is_tool_call = (self.parser.current_recipient is not None and
                        (self.parser.current_recipient.startswith("python") or
                         self.parser.current_recipient.startswith("browser.")))
        if is_analysis or is_tool_call:
            self.num_reasoning_tokens += len(token_ids)

124
125
    def append_output(self, output) -> None:
        if isinstance(output, RequestOutput):
126
            self._update_num_prompt_tokens(output)
127
            self._update_num_cached_tokens(output)
128
            output_token_ids = output.outputs[0].token_ids
129
            self._update_num_output_tokens(output_token_ids)
130
            self.parser = get_streamable_parser_for_assistant()
131
132
            for token_id in output_token_ids:
                self.parser.process(token_id)
133
134
                # Check if the current token is part of reasoning content
                self._update_num_reasoning_tokens([token_id])
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
            output_msgs = self.parser.messages
        else:
            # Tool output.
            output_msgs = output
        self._messages.extend(output_msgs)

    @property
    def messages(self) -> list:
        return self._messages

    def need_builtin_tool_call(self) -> bool:
        last_msg = self.messages[-1]
        recipient = last_msg.recipient
        return recipient is not None and (recipient.startswith("browser.")
                                          or recipient.startswith("python"))

    async def call_tool(self) -> list[Message]:
        if not self.messages:
            return []
        last_msg = self.messages[-1]
        recipient = last_msg.recipient
        if recipient is not None:
            if recipient.startswith("browser."):
                return await self.call_search_tool(
159
                    self._tool_sessions["browser"], last_msg)
160
161
            elif recipient.startswith("python"):
                return await self.call_python_tool(
162
                    self._tool_sessions["python"], last_msg)
163
164
165
166
167
        raise ValueError("No tool call found")

    def render_for_completion(self) -> list[int]:
        return render_for_completion(self.messages)

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
    async def call_search_tool(self, tool_session: Union["ClientSession",
                                                         Tool],
                               last_msg: Message) -> list[Message]:
        if isinstance(tool_session, Tool):
            return await tool_session.get_result(self)
        tool_name = last_msg.recipient.split(".")[1]
        args = json.loads(last_msg.content[0].text)
        result = await tool_session.call_tool(tool_name, args)
        result_str = result.content[0].text
        content = TextContent(text=result_str)
        author = Author(role=Role.TOOL, name=last_msg.recipient)
        return [
            Message(author=author, content=[content], recipient=Role.ASSISTANT)
        ]

    async def call_python_tool(self, tool_session: Union["ClientSession",
                                                         Tool],
                               last_msg: Message) -> list[Message]:
        if isinstance(tool_session, Tool):
            return await tool_session.get_result(self)
        param = {
            "code": last_msg.content[0].text,
        }
        result = await tool_session.call_tool("python", param)
        result_str = result.content[0].text

        content = TextContent(text=result_str)
        author = Author(role=Role.TOOL, name="python")

        return [
            Message(author=author,
                    content=[content],
                    channel=last_msg.channel,
                    recipient=Role.ASSISTANT)
        ]
203

204
205
206
207
208
209
210
211
212
    async def init_tool_sessions(self, tool_server: Optional[ToolServer],
                                 exit_stack: AsyncExitStack) -> None:
        if tool_server:
            for tool_name in self.available_tools:
                if tool_name not in self._tool_sessions:
                    self._tool_sessions[
                        tool_name] = await exit_stack.enter_async_context(
                            tool_server.new_session(tool_name))

213
214
215
216
217
218
219
220
221
222

class StreamingHarmonyContext(HarmonyContext):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.last_output = None

        self.parser = get_streamable_parser_for_assistant()
        self.encoding = get_encoding()
        self.last_tok = None
223
        self.first_tok_of_message = True
224
225
226
227
228
229
230

    @property
    def messages(self) -> list:
        return self.parser.messages

    def append_output(self, output) -> None:
        if isinstance(output, RequestOutput):
231
232
233
234
            # append_output is called for each output token in streaming case,
            # so we only want to add the prompt tokens once for each message.
            if self.first_tok_of_message:
                self._update_num_prompt_tokens(output)
235
                self._update_num_cached_tokens(output)
236
237
238
239
240
            # Reset self.first_tok_of_message if needed:
            # if the current token is the last one of the current message
            # (finished=True), then the next token processed will mark the
            # beginning of a new message
            self.first_tok_of_message = output.finished
241
242
            for tok in output.outputs[0].token_ids:
                self.parser.process(tok)
243
            self._update_num_output_tokens(output.outputs[0].token_ids)
244
            # Check if the current token is part of reasoning content
245
            self._update_num_reasoning_tokens(output.outputs[0].token_ids)
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
281
            self.last_tok = tok
        else:
            # Handle the case of tool output in direct message format
            assert len(output) == 1, "Tool output should be a single message"
            msg = output[0]
            # Sometimes the recipient is not set for tool messages,
            # so we set it to "assistant"
            if msg.author.role == Role.TOOL and msg.recipient is None:
                msg.recipient = "assistant"
            toks = self.encoding.render(msg)
            for tok in toks:
                self.parser.process(tok)
            self.last_tok = toks[-1]

    def is_expecting_start(self) -> bool:
        return self.parser.state == StreamState.EXPECT_START

    def is_assistant_action_turn(self) -> bool:
        return self.last_tok in self.encoding.stop_tokens_for_assistant_actions(
        )

    def render_for_completion(self) -> list[int]:
        # now this list of tokens as next turn's starting tokens
        # `<|start|>assistant``,
        # we need to process them in parser.
        rendered_tokens = super().render_for_completion()

        last_n = -1
        to_process = []
        while rendered_tokens[last_n] != self.last_tok:
            to_process.append(rendered_tokens[last_n])
            last_n -= 1
        for tok in reversed(to_process):
            self.parser.process(tok)

        return rendered_tokens