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

4
import json
5
from collections.abc import Sequence
6
7
8
9

import partial_json_parser
from partial_json_parser.core.options import Allow

10
from vllm.entrypoints.chat_utils import make_tool_call_id
11
12
13
14
15
16
17
18
19
from vllm.entrypoints.openai.protocol import (
    ChatCompletionRequest,
    DeltaFunctionCall,
    DeltaMessage,
    DeltaToolCall,
    ExtractedToolCallInformation,
    FunctionCall,
    ToolCall,
)
20
from vllm.logger import init_logger
21
from vllm.tokenizers import TokenizerLike
22
23
24
25
from vllm.tool_parsers.abstract_tool_parser import (
    ToolParser,
)
from vllm.tool_parsers.utils import extract_intermediate_diff
26
27
28
29
30

logger = init_logger(__name__)


class Internlm2ToolParser(ToolParser):
31
    def __init__(self, tokenizer: TokenizerLike):
32
33
34
        super().__init__(tokenizer)
        self.position = 0

35
    def adjust_request(self, request: ChatCompletionRequest) -> ChatCompletionRequest:
36
        request = super().adjust_request(request)
37
        if request.tools and request.tool_choice != "none":
38
            # do not skip special tokens because internlm use the special
39
            # tokens to indicate the start and end of the tool calls
40
41
42
43
            # information.
            request.skip_special_tokens = False
        return request

44
    def get_arguments(self, obj):
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
        if "parameters" in obj:
            return obj.get("parameters")
        elif "arguments" in obj:
            return obj.get("arguments")
        return None

    def extract_tool_calls_streaming(
        self,
        previous_text: str,
        current_text: str,
        delta_text: str,
        previous_token_ids: Sequence[int],
        current_token_ids: Sequence[int],
        delta_token_ids: Sequence[int],
        request: ChatCompletionRequest,
60
    ) -> DeltaMessage | None:
61
        if "<|action_start|>" not in current_text:
62
63
            self.position = len(current_text)
            return DeltaMessage(content=delta_text)
64
        # if the tool call is sent, return an empty delta message
65
        # to make sure the finish_reason will be sent correctly.
66
        if self.current_tool_id > 0:
67
            return DeltaMessage(content="")
68
69

        last_pos = self.position
70
        if "<|action_start|><|plugin|>" not in current_text[last_pos:]:
71
72
73
            return None

        new_delta = current_text[last_pos:]
74
        text, action = new_delta.split("<|action_start|><|plugin|>")
75
76
77
78
79
80

        if len(text) > 0:
            self.position = self.position + len(text)
            return DeltaMessage(content=text)

        action = action.strip()
81
        action = action.split("<|action_end|>".strip())[0]
82
83
84
85
86

        # bit mask flags for partial JSON parsing. If the name hasn't been
        # sent yet, don't allow sending
        # an incomplete string since OpenAI only ever (as far as I have
        # seen) allows sending the entire tool/ function name at once.
87
        flags = Allow.ALL if self.current_tool_name_sent else Allow.ALL & ~Allow.STR
88
89
90
91

        try:
            parsable_arr = action

co63oc's avatar
co63oc committed
92
            # tool calls are generated in an object in internlm2
93
94
            # it's not support parallel tool calls
            try:
95
                tool_call_arr: dict = partial_json_parser.loads(parsable_arr, flags)
96
            except partial_json_parser.core.exceptions.MalformedJSON:
97
                logger.debug("not enough tokens to parse into JSON yet")
98
99
100
101
102
103
104
105
                return None

            # if the current tool name hasn't been sent, send if available
            # - otherwise send nothing
            if not self.current_tool_name_sent:
                function_name = tool_call_arr.get("name")
                if function_name:
                    self.current_tool_id = self.current_tool_id + 1
106
107
108
109
110
111
112
113
114
115
116
117
                    delta = DeltaMessage(
                        tool_calls=[
                            DeltaToolCall(
                                index=self.current_tool_id,
                                type="function",
                                id=make_tool_call_id(),
                                function=DeltaFunctionCall(
                                    name=function_name
                                ).model_dump(exclude_none=True),
                            )
                        ]
                    )
118
119
120
121
122
123
124
                    self.current_tool_name_sent = True
                    self.streamed_args_for_tool.append("")
                else:
                    delta = None
            # now we know we're on the same tool call and we're streaming
            # arguments
            else:
125
                prev_arguments = self.get_arguments(
126
127
                    self.prev_tool_call_arr[self.current_tool_id]
                )
128
                cur_arguments = self.get_arguments(tool_call_arr)
129
130
131
132
133
134
135

                # not arguments generated
                if not cur_arguments and not prev_arguments:
                    delta = None
                # will never happen
                elif not cur_arguments and prev_arguments:
                    logger.error(
136
137
                        "INVARIANT - impossible to have arguments reset mid-arguments"
                    )
138
139
140
                    delta = None
                # first time to get parameters
                elif cur_arguments and not prev_arguments:
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
                    cur_arguments_json = json.dumps(cur_arguments, ensure_ascii=False)

                    arguments_delta = cur_arguments_json[
                        : cur_arguments_json.index(delta_text) + len(delta_text)
                    ]
                    delta = DeltaMessage(
                        tool_calls=[
                            DeltaToolCall(
                                index=self.current_tool_id,
                                function=DeltaFunctionCall(
                                    arguments=arguments_delta
                                ).model_dump(exclude_none=True),
                            )
                        ]
                    )
                    self.streamed_args_for_tool[self.current_tool_id] += arguments_delta
157
158
                # both prev and cur parameters, send the increase parameters
                elif cur_arguments and prev_arguments:
159
160
                    cur_args_json = json.dumps(cur_arguments, ensure_ascii=False)
                    prev_args_json = json.dumps(prev_arguments, ensure_ascii=False)
161
162

                    argument_diff = extract_intermediate_diff(
163
164
165
166
167
168
169
170
171
172
173
174
175
176
                        cur_args_json, prev_args_json
                    )

                    delta = DeltaMessage(
                        tool_calls=[
                            DeltaToolCall(
                                index=self.current_tool_id,
                                function=DeltaFunctionCall(
                                    arguments=argument_diff
                                ).model_dump(exclude_none=True),
                            )
                        ]
                    )
                    self.streamed_args_for_tool[self.current_tool_id] += argument_diff
177
178
179
180

            # check to see if the name is defined and has been sent. if so,
            # stream the name - otherwise keep waiting
            # finish by setting old and returning None as base case
181
            tool_call_arr["arguments"] = self.get_arguments(tool_call_arr)
182
183
            self.prev_tool_call_arr = [tool_call_arr]
            return delta
184
185
        except Exception:
            logger.exception("Error trying to handle streaming tool call.")
186
            logger.debug(
187
188
                "Skipping chunk as a result of tool streaming extraction error"
            )
189
190
191
192
193
194
195
196
197
            return None

    def extract_tool_calls(
        self,
        model_output: str,
        request: ChatCompletionRequest,
    ) -> ExtractedToolCallInformation:
        text = model_output
        tools = request.tools
198
199
200
201
        if "<|action_start|><|plugin|>" in text:
            text, action = text.split("<|action_start|><|plugin|>")
            action = action.split("<|action_end|>".strip())[0]
            action = action[action.find("{") :]
202
            action_dict = json.loads(action)
203
204
205
206
207
208
209
            name, parameters = (
                action_dict["name"],
                json.dumps(
                    action_dict.get("parameters", action_dict.get("arguments", {})),
                    ensure_ascii=False,
                ),
            )
210
211

            if not tools or name not in [t.function.name for t in tools]:
212
213
214
                ExtractedToolCallInformation(
                    tools_called=False, tool_calls=[], content=text
                )
215
216

            tool_calls = [
217
                ToolCall(function=FunctionCall(name=name, arguments=parameters))
218
219
220
221
            ]
            return ExtractedToolCallInformation(
                tools_called=True,
                tool_calls=tool_calls,
222
223
                content=text if len(text) > 0 else None,
            )
224

225
226
227
        return ExtractedToolCallInformation(
            tools_called=False, tool_calls=[], content=text
        )