deepseekv31_tool_parser.py 16 KB
Newer Older
1
2
3
4
5
6
7
8
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project

from collections.abc import Sequence

import regex as re

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

logger = init_logger(__name__)


class DeepSeekV31ToolParser(ToolParser):
26
    def __init__(self, tokenizer: TokenizerLike):
27
28
29
30
31
        super().__init__(tokenizer)

        self.current_tool_name_sent: bool = False
        self.prev_tool_call_arr: list[dict] = []
        self.current_tool_id: int = -1
32
33
34
        self.streamed_args_for_tool: list[
            str
        ] = []  # map what has been streamed for each tool so far to a list
35
36
37
38
39
40
41
42

        self.tool_calls_start_token: str = "<|tool▁calls▁begin|>"
        self.tool_calls_end_token: str = "<|tool▁calls▁end|>"

        self.tool_call_start_token: str = "<|tool▁call▁begin|>"
        self.tool_call_end_token: str = "<|tool▁call▁end|>"

        self.tool_call_regex = re.compile(
43
            r"<|tool▁call▁begin|>(?P<function_name>.*?)<|tool▁sep|>(?P<function_arguments>.*?)<|tool▁call▁end|>"
44
45
46
        )

        self.stream_tool_call_portion_regex = re.compile(
47
48
            r"(?P<function_name>.*)<|tool▁sep|>(?P<function_arguments>.*)"
        )
49
50

        self.stream_tool_call_name_regex = re.compile(
51
52
            r"(?P<function_name>.*)<|tool▁sep|>"
        )
53
54
55
56

        if not self.model_tokenizer:
            raise ValueError(
                "The model tokenizer must be passed to the ToolParser "
57
58
59
60
61
62
                "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)

        self.tool_call_start_token_id = self.vocab.get(self.tool_call_start_token)
63
64
        self.tool_call_end_token_id = self.vocab.get(self.tool_call_end_token)

65
66
67
68
        if (
            self.tool_calls_start_token_id is None
            or self.tool_calls_end_token_id is None
        ):
69
            raise RuntimeError(
70
                "DeepSeek-V3.1 Tool parser could not locate tool call "
71
72
                "start/end tokens in the tokenizer!"
            )
73
74
75
76
77
78
79
80

    def extract_tool_calls(
        self,
        model_output: str,
        request: ChatCompletionRequest,
    ) -> ExtractedToolCallInformation:
        # sanity check; avoid unnecessary processing
        if self.tool_calls_start_token not in model_output:
81
82
83
            return ExtractedToolCallInformation(
                tools_called=False, tool_calls=[], content=model_output
            )
84
85
86
87
88
89
90

        else:
            try:
                # there are two possible captures - between tags, or between a
                # tag and end-of-string so the result of
                # findall is an array of tuples where one is a function call and
                # the other is None
91
                function_call_tuples = self.tool_call_regex.findall(model_output)
92
93
94
95
96
97
98

                tool_calls = []
                for match in function_call_tuples:
                    function_name, function_args = match
                    tool_calls.append(
                        ToolCall(
                            type="function",
99
100
101
102
103
                            function=FunctionCall(
                                name=function_name, arguments=function_args
                            ),
                        )
                    )
104

105
                content = model_output[: model_output.find(self.tool_calls_start_token)]
106
107
108
109
110
111
112
                return ExtractedToolCallInformation(
                    tools_called=True,
                    tool_calls=tool_calls,
                    content=content if content else None,
                )

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

    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,
127
    ) -> DeltaMessage | None:
128
129
130
131
132
133
        logger.debug("delta_text: %s", delta_text)
        logger.debug("delta_token_ids: %s", delta_token_ids)
        # check to see if we should be streaming a tool call - is there a
        if self.tool_calls_start_token_id not in current_token_ids:
            logger.debug("No tool call tokens found!")
            return DeltaMessage(content=delta_text)
134
135
136
        delta_text = delta_text.replace(self.tool_calls_start_token, "").replace(
            self.tool_calls_end_token, ""
        )
137
138
139
140
        try:
            # figure out where we are in the parsing by counting tool call
            # start & end tags
            prev_tool_start_count = previous_token_ids.count(
141
142
143
                self.tool_call_start_token_id
            )
            prev_tool_end_count = previous_token_ids.count(self.tool_call_end_token_id)
144
            cur_tool_start_count = current_token_ids.count(
145
146
147
                self.tool_call_start_token_id
            )
            cur_tool_end_count = current_token_ids.count(self.tool_call_end_token_id)
148
149
150
151
            tool_call_portion = None
            text_portion = None

            # case: if we're generating text, OR rounding out a tool call
152
153
154
155
156
            if (
                cur_tool_start_count == cur_tool_end_count
                and prev_tool_end_count == cur_tool_end_count
                and self.tool_call_end_token not in delta_text
            ):
157
158
159
160
161
162
                logger.debug("Generating text content! skipping tool parsing.")
                return DeltaMessage(content=delta_text)

            if self.tool_call_end_token in delta_text:
                logger.debug("tool_call_end_token in delta_text")
                full_text = current_text + delta_text
163
164
165
166
167
168
169
                tool_call_portion = (
                    full_text.split(self.tool_call_start_token)[-1]
                    .split(self.tool_call_end_token)[0]
                    .rstrip()
                )
                delta_text = delta_text.split(self.tool_call_end_token)[0].rstrip()
                text_portion = delta_text.split(self.tool_call_end_token)[-1].lstrip()
170
171

            # case -- we're starting a new tool call
172
173
174
175
            if (
                cur_tool_start_count > cur_tool_end_count
                and cur_tool_start_count > prev_tool_start_count
            ):
176
                if len(delta_token_ids) > 1:
177
178
179
                    tool_call_portion = current_text.split(self.tool_call_start_token)[
                        -1
                    ]
180
181
182
183
184
185
186
187
188
189
190
191
192
                else:
                    tool_call_portion = None
                    delta = None

                text_portion = None

                # set cursors and state appropriately
                self.current_tool_id += 1
                self.current_tool_name_sent = False
                self.streamed_args_for_tool.append("")
                logger.debug("Starting on a new tool %s", self.current_tool_id)

            # case -- we're updating an existing tool call
193
194
195
196
            elif (
                cur_tool_start_count > cur_tool_end_count
                and cur_tool_start_count == prev_tool_start_count
            ):
197
                # get the portion of the text that's the tool call
198
                tool_call_portion = current_text.split(self.tool_call_start_token)[-1]
199
200
201
                text_portion = None

            # case -- the current tool call is being closed.
202
203
204
205
206
207
            elif (
                cur_tool_start_count == cur_tool_end_count
                and cur_tool_end_count >= prev_tool_end_count
            ):
                if self.prev_tool_call_arr is None or len(self.prev_tool_call_arr) == 0:
                    logger.debug("attempting to close tool call, but no tool call")
208
                    return None
209
                diff = self.prev_tool_call_arr[self.current_tool_id].get("arguments")
210
                if diff:
211
212
213
214
215
                    diff = (
                        diff.encode("utf-8").decode("unicode_escape")
                        if diff is str
                        else diff
                    )
216
217
218
219
220
221
222
223
224
225
                    if '"}' not in delta_text:
                        return None
                    end_loc = delta_text.rindex('"}')
                    diff = delta_text[:end_loc] + '"}'
                    logger.debug(
                        "Finishing tool and found diff that had not "
                        "been streamed yet: %s",
                        diff,
                    )
                    self.streamed_args_for_tool[self.current_tool_id] += diff
226
227
228
229
230
231
232
233
234
235
                    return DeltaMessage(
                        tool_calls=[
                            DeltaToolCall(
                                index=self.current_tool_id,
                                function=DeltaFunctionCall(arguments=diff).model_dump(
                                    exclude_none=True
                                ),
                            )
                        ]
                    )
236
237
238
239
240
241
242
243
244
245

            # case -- otherwise we're just generating text
            else:
                text = delta_text.replace(self.tool_call_start_token, "")
                text = text.replace(self.tool_call_end_token, "")
                delta = DeltaMessage(tool_calls=[], content=text)
                return delta

            current_tool_call = dict()
            if tool_call_portion:
246
247
248
                current_tool_call_matches = self.stream_tool_call_portion_regex.match(
                    tool_call_portion
                )
249
250
251
252
253
254
                if current_tool_call_matches:
                    tool_name, tool_args = current_tool_call_matches.groups()
                    current_tool_call["name"] = tool_name
                    current_tool_call["arguments"] = tool_args
                else:
                    current_tool_call_name_matches = (
255
256
                        self.stream_tool_call_name_regex.match(tool_call_portion)
                    )
257
258
259
260
261
262
263
264
265
266
267
268
269
                    if current_tool_call_name_matches:
                        tool_name = current_tool_call_name_matches.groups()
                        current_tool_call["name"] = tool_name
                        current_tool_call["arguments"] = ""
                    else:
                        logger.debug("Not enough token")
                        return None

            # case - we haven't sent the tool name yet. If it's available, send
            #   it. otherwise, wait until it's available.
            if not self.current_tool_name_sent:
                if current_tool_call is None:
                    return None
270
                function_name: str | None = current_tool_call.get("name")
271
272
                if function_name:
                    self.current_tool_name_sent = True
273
274
275
276
277
278
279
280
281
282
283
284
                    return 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),
                            )
                        ]
                    )
285
286
287
288
289
290
291
292
293
                else:
                    return None

            # case -- otherwise, send the tool call delta

            # if the tool call portion is None, send the delta as text
            if tool_call_portion is None:
                # if there's text but not tool calls, send that -
                # otherwise None to skip chunk
294
295
296
297
298
                delta = (
                    DeltaMessage(content=delta_text)
                    if text_portion is not None
                    else None
                )
299
300
301
302
303
                return delta

            # now, the nitty-gritty of tool calls
            # now we have the portion to parse as tool call.

304
305
306
            logger.debug(
                "Trying to parse current tool call with ID %s", self.current_tool_id
            )
307
308
309
310
311
312
313
314
315

            # if we're starting a new tool call, push an empty object in as
            #   a placeholder for the arguments
            if len(self.prev_tool_call_arr) <= self.current_tool_id:
                self.prev_tool_call_arr.append({})

            # main logic for tool parsing here - compare prev. partially-parsed
            #   JSON to the current partially-parsed JSON
            prev_arguments = self.prev_tool_call_arr[self.current_tool_id].get(
316
317
                "arguments"
            )
318
319
320
321
322
323
324
325
326
327
328
329
330
            cur_arguments = current_tool_call.get("arguments")

            logger.debug("diffing old arguments: %s", prev_arguments)
            logger.debug("against new ones: %s", cur_arguments)

            # case -- no arguments have been created yet. skip sending a delta.
            if not cur_arguments and not prev_arguments:
                logger.debug("Skipping text %s - no arguments", delta_text)
                delta = None

            # case -- prev arguments are defined, but non are now.
            #   probably impossible, but not a fatal error - just keep going
            elif not cur_arguments and prev_arguments:
331
332
333
334
                logger.error(
                    "should be impossible to have arguments reset "
                    "mid-call. skipping streaming anything."
                )
335
336
337
338
339
                delta = None

            # case -- we now have the first info about arguments available from
            #   autocompleting the JSON
            elif cur_arguments and not prev_arguments:
340
341
342
343
344
345
346
347
348
349
350
                delta = DeltaMessage(
                    tool_calls=[
                        DeltaToolCall(
                            index=self.current_tool_id,
                            function=DeltaFunctionCall(
                                arguments=cur_arguments
                            ).model_dump(exclude_none=True),
                        )
                    ]
                )
                self.streamed_args_for_tool[self.current_tool_id] = cur_arguments
351
352
353

            # last case -- we have an update to existing arguments.
            elif cur_arguments and prev_arguments:
354
355
356
357
358
359
360
                if (
                    isinstance(delta_text, str)
                    and cur_arguments != prev_arguments
                    and len(cur_arguments) > len(prev_arguments)
                    and cur_arguments.startswith(prev_arguments)
                ):
                    delta_arguments = cur_arguments[len(prev_arguments) :]
361
362
                    logger.debug("got diff %s", delta_text)

363
364
365
366
367
368
369
370
371
372
373
                    delta = DeltaMessage(
                        tool_calls=[
                            DeltaToolCall(
                                index=self.current_tool_id,
                                function=DeltaFunctionCall(
                                    arguments=delta_arguments
                                ).model_dump(exclude_none=True),
                            )
                        ]
                    )
                    self.streamed_args_for_tool[self.current_tool_id] = cur_arguments
374
375
376
377
378
379
                else:
                    delta = None

            # handle saving the state for the current tool into
            # the "prev" list for use in diffing for the next iteration
            if self.current_tool_id == len(self.prev_tool_call_arr) - 1:
380
                self.prev_tool_call_arr[self.current_tool_id] = current_tool_call
381
382
383
384
385
386
387
388
            else:
                self.prev_tool_call_arr.append(current_tool_call)

            return delta

        except Exception:
            logger.exception("Error trying to handle streaming tool call.")
            return None  # do not stream a delta. skip this token ID.