jamba_tool_parser.py 13.4 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

import partial_json_parser
8
import regex as re
9
10
from partial_json_parser.core.options import Allow

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

logger = init_logger(__name__)


class JambaToolParser(ToolParser):
31
    def __init__(self, tokenizer: TokenizerLike):
32
33
34
35
36
37
38
39
        super().__init__(tokenizer)

        if isinstance(self.model_tokenizer, MistralTokenizer):
            raise ValueError(
                "Detected a MistralTokenizer tokenizer when using a Jamba model"
            )

        self.current_tool_name_sent: bool = False
40
        self.prev_tool_call_arr: list[dict] = []
41
        self.current_tool_id: int = -1
42
43
44
        self.streamed_args_for_tool: list[
            str
        ] = []  # map what has been streamed for each tool so far to a list
45
46
47
48
49

        self.tool_calls_start_token: str = "<tool_calls>"
        self.tool_calls_end_token: str = "</tool_calls>"

        self.tool_calls_regex = re.compile(
50
51
            rf"{self.tool_calls_start_token}(.*?){self.tool_calls_end_token}", re.DOTALL
        )
52
53
54
55

        if not self.model_tokenizer:
            raise ValueError(
                "The model tokenizer must be passed to the ToolParser "
56
57
58
59
60
61
62
63
                "constructor during construction."
            )
        self.tool_calls_start_token_id = self.vocab.get(self.tool_calls_start_token)
        self.tool_calls_end_token_id = self.vocab.get(self.tool_calls_end_token)
        if (
            self.tool_calls_start_token_id is None
            or self.tool_calls_end_token_id is None
        ):
64
65
            raise RuntimeError(
                "Jamba Tool parser could not locate tool calls start/end "
66
67
                "tokens in the tokenizer!"
            )
68

69
    def adjust_request(self, request: ChatCompletionRequest) -> ChatCompletionRequest:
70
        request = super().adjust_request(request)
71
        if request.tools and request.tool_choice != "none":
72
73
74
75
76
77
78
            # do not skip special tokens because jamba use the special
            # tokens to indicate the start and end of the tool calls
            # information.
            request.skip_special_tokens = False
        return request

    def extract_tool_calls(
79
80
        self, model_output: str, request: ChatCompletionRequest
    ) -> ExtractedToolCallInformation:
81
82
        # sanity check; avoid unnecessary processing
        if self.tool_calls_start_token not in model_output:
83
84
85
            return ExtractedToolCallInformation(
                tools_called=False, tool_calls=[], content=model_output
            )
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100

        else:
            try:
                # use a regex to find the tool call between the tags
                function_calls = self.tool_calls_regex.findall(model_output)[0]

                # load the JSON, and then use it to build the Function and
                # Tool Call
                raw_function_calls = json.loads(function_calls)
                tool_calls = [
                    ToolCall(
                        type="function",
                        function=FunctionCall(
                            name=function_call["name"],
                            # function call args are JSON but as a string
101
102
103
104
105
106
                            arguments=json.dumps(
                                function_call["arguments"], ensure_ascii=False
                            ),
                        ),
                    )
                    for function_call in raw_function_calls
107
108
                ]

109
                content = model_output[: model_output.find(self.tool_calls_start_token)]
110
111
112
                return ExtractedToolCallInformation(
                    tools_called=True,
                    tool_calls=tool_calls,
113
114
                    content=content if (len(content) > 0 and content != " ") else None,
                )
115
116

            except Exception:
117
118
119
120
                logger.exception("Error in extracting tool call from response.")
                return ExtractedToolCallInformation(
                    tools_called=False, tool_calls=[], content=model_output
                )
121
122
123
124
125
126
127
128
129
130

    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,
131
    ) -> DeltaMessage | None:
132
133
134
135
136
137
138
139
140
141
        # if the tool call token is not in the tokens generated so far, append
        # output to contents since it's not a tool
        if self.tool_calls_start_token not in current_text:
            return DeltaMessage(content=delta_text)

        # if the tool call token ID IS in the tokens generated so far, that
        # means we're parsing as tool calls now

        # handle if we detected the start of tool calls token which means
        # the start of tool calling
142
143
144
145
        if (
            self.tool_calls_start_token_id in delta_token_ids
            and len(delta_token_ids) == 1
        ):
146
147
148
149
150
151
152
153
            # if it's the only token, return None, so we don't send a chat
            # completion and don't send a control token
            return None

        # 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.
154
        flags = Allow.ALL if self.current_tool_name_sent else Allow.ALL & ~Allow.STR
155
156
        try:
            # Extract the tool calls between the special tool call tokens
157
158
159
            parsable_arr = current_text.split(self.tool_calls_start_token)[-1].split(
                self.tool_calls_end_token
            )[0]
160
161
162
163

            # tool calls are generated in an array, so do partial JSON
            # parsing on the entire array
            try:
164
                tool_call_arr: list[dict] = partial_json_parser.loads(
165
166
                    parsable_arr, flags
                )
167
            except partial_json_parser.core.exceptions.MalformedJSON:
168
                logger.debug("not enough tokens to parse into JSON yet")
169
170
171
172
                return None

            # select as the current tool call the one we're on the state at

173
174
175
            current_tool_call: dict = (
                tool_call_arr[self.current_tool_id] if len(tool_call_arr) > 0 else {}
            )
176
177
178
179
180
181
182
183

            # case -- if no tokens have been streamed for the tool, e.g.
            #   only the array brackets, stream nothing
            if len(tool_call_arr) == 0:
                return None

            # case: we are starting a new tool in the array
            #   -> array has > 0 length AND length has moved past cursor
184
185
186
            elif (
                len(tool_call_arr) > 0 and len(tool_call_arr) > self.current_tool_id + 1
            ):
187
188
189
190
191
                # if we're moving on to a new call, first make sure we
                # haven't missed anything in the previous one that was
                # auto-generated due to JSON completions, but wasn't
                # streamed to the client yet.
                if self.current_tool_id >= 0:
192
                    diff: str | None = current_tool_call.get("arguments")
193
194

                    if diff:
195
                        diff = json.dumps(diff, ensure_ascii=False).replace(
196
197
198
199
200
201
202
203
204
205
206
207
208
                            self.streamed_args_for_tool[self.current_tool_id], ""
                        )
                        delta = DeltaMessage(
                            tool_calls=[
                                DeltaToolCall(
                                    index=self.current_tool_id,
                                    function=DeltaFunctionCall(
                                        arguments=diff
                                    ).model_dump(exclude_none=True),
                                )
                            ]
                        )
                        self.streamed_args_for_tool[self.current_tool_id] += diff
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
                    else:
                        delta = None
                else:
                    delta = None
                # re-set stuff pertaining to progress in the current tool
                self.current_tool_id = len(tool_call_arr) - 1
                self.current_tool_name_sent = False
                self.streamed_args_for_tool.append("")
                logger.debug("starting on new tool %d", self.current_tool_id)
                return delta

            # case: update an existing tool - this is handled below

            # if the current tool name hasn't been sent, send if available
            # - otherwise send nothing
            if not self.current_tool_name_sent:
                function_name = current_tool_call.get("name")
                if function_name:
227
228
229
230
231
232
233
234
235
236
237
238
                    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),
                            )
                        ]
                    )
239
240
241
242
243
244
245
                    self.current_tool_name_sent = True
                else:
                    delta = None

            # now we know we're on the same tool call and we're streaming
            # arguments
            else:
246
247
248
                prev_arguments = self.prev_tool_call_arr[self.current_tool_id].get(
                    "arguments"
                )
249
250
                cur_arguments = current_tool_call.get("arguments")

251
                new_text = delta_text.replace("'", '"')
252
253
254
255
256

                if not cur_arguments and not prev_arguments:
                    delta = None
                elif not cur_arguments and prev_arguments:
                    logger.error(
257
258
                        "INVARIANT - impossible to have arguments reset mid-arguments"
                    )
259
260
                    delta = None
                elif cur_arguments and not prev_arguments:
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
                    cur_arguments_json = json.dumps(cur_arguments, ensure_ascii=False)
                    logger.debug("finding %s in %s", new_text, cur_arguments_json)

                    arguments_delta = cur_arguments_json[
                        : cur_arguments_json.index(new_text) + len(new_text)
                    ]
                    logger.debug(
                        "First tokens in arguments received: %s", arguments_delta
                    )
                    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
281
282

                elif cur_arguments and prev_arguments:
283
284
285
286
287
288
289
                    cur_args_json = json.dumps(cur_arguments, ensure_ascii=False)
                    prev_args_json = json.dumps(prev_arguments, ensure_ascii=False)
                    logger.debug(
                        "Searching for diff between \n%s\n%s",
                        cur_args_json,
                        prev_args_json,
                    )
290
291

                    argument_diff = extract_intermediate_diff(
292
293
                        cur_args_json, prev_args_json
                    )
294
                    logger.debug("got arguments diff: %s", argument_diff)
295
296
297
298
299
300
301
302
303
304
305
                    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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
                else:
                    # try parsing it with regular JSON - if it works we're
                    # at the end, and we need to send the difference between
                    # tokens streamed so far and the valid JSON
                    delta = None

            # 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
            self.prev_tool_call_arr = tool_call_arr
            return delta

        except Exception:
            logger.exception("Error trying to handle streaming tool call.")
            logger.debug(
321
322
                "Skipping chunk as a result of tool streaming extraction error"
            )
323
            return None