|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | +import logging |
| 4 | +from abc import ABC, abstractmethod |
| 5 | + |
| 6 | +from openai_harmony import Message, Role, StreamState |
| 7 | + |
| 8 | +from vllm.entrypoints.harmony_utils import ( |
| 9 | + get_encoding, get_streamable_parser_for_assistant, render_for_completion) |
| 10 | +from vllm.entrypoints.tool import Tool |
| 11 | +from vllm.outputs import RequestOutput |
| 12 | + |
| 13 | +logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | + |
| 16 | +class ConversationContext(ABC): |
| 17 | + |
| 18 | + @abstractmethod |
| 19 | + def append_output(self, output) -> None: |
| 20 | + pass |
| 21 | + |
| 22 | + @abstractmethod |
| 23 | + async def call_tool(self) -> list[Message]: |
| 24 | + pass |
| 25 | + |
| 26 | + @abstractmethod |
| 27 | + def need_builtin_tool_call(self) -> bool: |
| 28 | + pass |
| 29 | + |
| 30 | + @abstractmethod |
| 31 | + def render_for_completion(self) -> list[int]: |
| 32 | + pass |
| 33 | + |
| 34 | + |
| 35 | +class SimpleContext(ConversationContext): |
| 36 | + |
| 37 | + def __init__(self): |
| 38 | + self.last_output = None |
| 39 | + |
| 40 | + def append_output(self, output) -> None: |
| 41 | + self.last_output = output |
| 42 | + |
| 43 | + def need_builtin_tool_call(self) -> bool: |
| 44 | + return False |
| 45 | + |
| 46 | + async def call_tool(self) -> list[Message]: |
| 47 | + raise NotImplementedError("Should not be called.") |
| 48 | + |
| 49 | + def render_for_completion(self) -> list[int]: |
| 50 | + raise NotImplementedError("Should not be called.") |
| 51 | + |
| 52 | + |
| 53 | +class HarmonyContext(ConversationContext): |
| 54 | + |
| 55 | + def __init__( |
| 56 | + self, |
| 57 | + messages: list, |
| 58 | + tool_sessions: dict[str, Tool], |
| 59 | + ): |
| 60 | + self._messages = messages |
| 61 | + self.tool_sessions = tool_sessions |
| 62 | + |
| 63 | + self.parser = get_streamable_parser_for_assistant() |
| 64 | + self.num_init_messages = len(messages) |
| 65 | + # TODO(woosuk): Implement the following fields. |
| 66 | + self.num_prompt_tokens = 0 |
| 67 | + self.num_cached_tokens = 0 |
| 68 | + self.num_output_tokens = 0 |
| 69 | + self.num_reasoning_tokens = 0 |
| 70 | + |
| 71 | + def append_output(self, output) -> None: |
| 72 | + if isinstance(output, RequestOutput): |
| 73 | + output_token_ids = output.outputs[0].token_ids |
| 74 | + for token_id in output_token_ids: |
| 75 | + self.parser.process(token_id) |
| 76 | + output_msgs = self.parser.messages |
| 77 | + else: |
| 78 | + # Tool output. |
| 79 | + output_msgs = output |
| 80 | + self._messages.extend(output_msgs) |
| 81 | + |
| 82 | + @property |
| 83 | + def messages(self) -> list: |
| 84 | + return self._messages |
| 85 | + |
| 86 | + def need_builtin_tool_call(self) -> bool: |
| 87 | + last_msg = self.messages[-1] |
| 88 | + recipient = last_msg.recipient |
| 89 | + return recipient is not None and (recipient.startswith("browser.") |
| 90 | + or recipient.startswith("python")) |
| 91 | + |
| 92 | + async def call_tool(self) -> list[Message]: |
| 93 | + if not self.messages: |
| 94 | + return [] |
| 95 | + last_msg = self.messages[-1] |
| 96 | + recipient = last_msg.recipient |
| 97 | + if recipient is not None: |
| 98 | + if recipient.startswith("browser."): |
| 99 | + return await self.call_search_tool( |
| 100 | + self.tool_sessions["browser"], last_msg) |
| 101 | + elif recipient.startswith("python"): |
| 102 | + return await self.call_python_tool( |
| 103 | + self.tool_sessions["python"], last_msg) |
| 104 | + raise ValueError("No tool call found") |
| 105 | + |
| 106 | + def render_for_completion(self) -> list[int]: |
| 107 | + return render_for_completion(self.messages) |
| 108 | + |
| 109 | + async def call_search_tool( |
| 110 | + self, |
| 111 | + tool_session: Tool, |
| 112 | + last_msg: Message, |
| 113 | + ) -> list[Message]: |
| 114 | + return await tool_session.get_result(self) |
| 115 | + |
| 116 | + async def call_python_tool( |
| 117 | + self, |
| 118 | + tool_session: Tool, |
| 119 | + last_msg: Message, |
| 120 | + ) -> list[Message]: |
| 121 | + return await tool_session.get_result(self) |
| 122 | + |
| 123 | + |
| 124 | +class StreamingHarmonyContext(HarmonyContext): |
| 125 | + |
| 126 | + def __init__(self, *args, **kwargs): |
| 127 | + super().__init__(*args, **kwargs) |
| 128 | + self.last_output = None |
| 129 | + |
| 130 | + self.parser = get_streamable_parser_for_assistant() |
| 131 | + self.encoding = get_encoding() |
| 132 | + self.last_tok = None |
| 133 | + |
| 134 | + @property |
| 135 | + def messages(self) -> list: |
| 136 | + return self.parser.messages |
| 137 | + |
| 138 | + def append_output(self, output) -> None: |
| 139 | + if isinstance(output, RequestOutput): |
| 140 | + tok = output.outputs[0].token_ids[0] |
| 141 | + self.parser.process(tok) |
| 142 | + self.last_tok = tok |
| 143 | + else: |
| 144 | + # Handle the case of tool output in direct message format |
| 145 | + assert len(output) == 1, "Tool output should be a single message" |
| 146 | + msg = output[0] |
| 147 | + # Sometimes the recipient is not set for tool messages, |
| 148 | + # so we set it to "assistant" |
| 149 | + if msg.author.role == Role.TOOL and msg.recipient is None: |
| 150 | + msg.recipient = "assistant" |
| 151 | + toks = self.encoding.render(msg) |
| 152 | + for tok in toks: |
| 153 | + self.parser.process(tok) |
| 154 | + self.last_tok = toks[-1] |
| 155 | + |
| 156 | + def is_expecting_start(self) -> bool: |
| 157 | + return self.parser.state == StreamState.EXPECT_START |
| 158 | + |
| 159 | + def is_assistant_action_turn(self) -> bool: |
| 160 | + return self.last_tok in self.encoding.stop_tokens_for_assistant_actions( |
| 161 | + ) |
| 162 | + |
| 163 | + def render_for_completion(self) -> list[int]: |
| 164 | + # now this list of tokens as next turn's starting tokens |
| 165 | + # `<|start|>assistant``, |
| 166 | + # we need to process them in parser. |
| 167 | + rendered_tokens = super().render_for_completion() |
| 168 | + |
| 169 | + last_n = -1 |
| 170 | + to_process = [] |
| 171 | + while rendered_tokens[last_n] != self.last_tok: |
| 172 | + to_process.append(rendered_tokens[last_n]) |
| 173 | + last_n -= 1 |
| 174 | + for tok in reversed(to_process): |
| 175 | + self.parser.process(tok) |
| 176 | + |
| 177 | + return rendered_tokens |
0 commit comments