hermes_tool_parser.py 21 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
from vllm.entrypoints.openai.chat_completion.protocol import (
13
    ChatCompletionRequest,
14
15
)
from vllm.entrypoints.openai.engine.protocol import (
16
17
18
19
20
21
22
    DeltaFunctionCall,
    DeltaMessage,
    DeltaToolCall,
    ExtractedToolCallInformation,
    FunctionCall,
    ToolCall,
)
23
from vllm.logger import init_logger
24
from vllm.tokenizers import TokenizerLike
25
from vllm.tool_parsers.abstract_tool_parser import (
26
    Tool,
27
28
    ToolParser,
)
29
from vllm.utils.mistral import is_mistral_tokenizer
30
31
32
33
34

logger = init_logger(__name__)


class Hermes2ProToolParser(ToolParser):
35
36
    def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):
        super().__init__(tokenizer, tools)
37

38
        if is_mistral_tokenizer(tokenizer):
39
            logger.error("Detected Mistral tokenizer when using a Hermes model")
40
            self.model_tokenizer = tokenizer.tokenizer
41
42

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

        self.tool_call_start_token: str = "<tool_call>"
        self.tool_call_end_token: str = "</tool_call>"

        self.tool_call_regex = re.compile(
53
54
            r"<tool_call>(.*?)</tool_call>|<tool_call>(.*)", re.DOTALL
        )
55
        self.scratch_pad_regex = re.compile(
56
57
            r"<scratch_pad>(.*?)</scratch_pad>", re.DOTALL
        )
58
59
60
61

        if not self.model_tokenizer:
            raise ValueError(
                "The model tokenizer must be passed to the ToolParser "
62
63
                "constructor during construction."
            )
64
        self.tool_call_start_token_ids = self.model_tokenizer.encode(
65
66
            self.tool_call_start_token, add_special_tokens=False
        )
67
        self.tool_call_end_token_ids = self.model_tokenizer.encode(
68
69
            self.tool_call_end_token, add_special_tokens=False
        )
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90

        self.tool_call_start_token_array = [
            self.model_tokenizer.decode([token_id])
            for token_id in self.tool_call_start_token_ids
        ]

        self.tool_call_end_token_array = [
            self.model_tokenizer.decode([token_id])
            for token_id in self.tool_call_end_token_ids
        ]

        self.buffered_delta_text = ""

    # Very simple idea: when encountering tokens like <, tool, _call, >,
    # <, /, tool, _call, >, store them in a buffer.
    # When the last token is encountered, empty the buffer and return it.
    # If a token appears in an incorrect sequence while storing in the buffer,
    # return the preceding buffer along with the token.
    def tool_call_delta_buffer(self, delta_text: str):
        # If the sequence of tool_call_start or tool_call_end tokens is not yet
        # complete, fill the buffer with the token and return "".
91
92
93
94
        if (
            delta_text in self.tool_call_start_token_array
            or delta_text in self.tool_call_end_token_array
        ):
95
96
97
            # If delta_text is the last token of tool_call_start_token or
            # tool_call_end_token, empty the buffer and return
            # the buffered text + delta_text.
98
99
100
101
            if (
                delta_text == self.tool_call_start_token_array[-1]
                or delta_text == self.tool_call_end_token_array[-1]
            ):
102
103
104
105
106
107
108
109
110
111
112
113
114
                buffered_text = self.buffered_delta_text
                self.buffered_delta_text = ""
                return buffered_text + delta_text
            else:
                self.buffered_delta_text = self.buffered_delta_text + delta_text
                return ""
        else:
            if self.buffered_delta_text:
                buffered_text = self.buffered_delta_text
                self.buffered_delta_text = ""
                return buffered_text + delta_text
            else:
                return delta_text
115

116
    def adjust_request(self, request: ChatCompletionRequest) -> ChatCompletionRequest:
117
        request = super().adjust_request(request)
118
        if request.tools and request.tool_choice != "none":
119
120
121
122
123
124
            # do not skip special tokens because the tool_call tokens are
            # marked "special" in some models. Since they are skipped
            # prior to the call to the tool parser, it breaks tool calling.
            request.skip_special_tokens = False
        return request

125
126
127
128
129
    def extract_tool_calls(
        self,
        model_output: str,
        request: ChatCompletionRequest,
    ) -> ExtractedToolCallInformation:
130
131
        # sanity check; avoid unnecessary processing
        if self.tool_call_start_token not in model_output:
132
133
134
            return ExtractedToolCallInformation(
                tools_called=False, tool_calls=[], content=model_output
            )
135
136
137
138
139
140
141

        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
142
                function_call_tuples = self.tool_call_regex.findall(model_output)
143
144
145
146
147
148
149
150
151
152
153
154
155

                # load the JSON, and then use it to build the Function and
                # Tool Call
                raw_function_calls = [
                    json.loads(match[0] if match[0] else match[1])
                    for match in function_call_tuples
                ]
                tool_calls = [
                    ToolCall(
                        type="function",
                        function=FunctionCall(
                            name=function_call["name"],
                            # function call args are JSON but as a string
156
157
158
159
160
                            arguments=json.dumps(
                                function_call["arguments"], ensure_ascii=False
                            ),
                        ),
                    )
161
162
163
                    for function_call in raw_function_calls
                ]

164
                content = model_output[: model_output.find(self.tool_call_start_token)]
165
166
167
                return ExtractedToolCallInformation(
                    tools_called=True,
                    tool_calls=tool_calls,
168
169
                    content=content if content else None,
                )
170

171
            except Exception:
172
173
174
175
                logger.exception("Error in extracting tool call from response.")
                return ExtractedToolCallInformation(
                    tools_called=False, tool_calls=[], content=model_output
                )
176
177
178
179
180
181
182
183
184

    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],
185
        request: ChatCompletionRequest,
186
    ) -> DeltaMessage | None:
187
188
189
190
191
192
193
        # 1. All tokens are parsed based on _text, not token_ids.
        # 2. All incoming text data is processed by the tool_call_delta_buffer
        #    function for buffering before being used for parsing.

        delta_text = self.tool_call_delta_buffer(delta_text)
        # If the last characters of previous_text
        # match self.buffered_delta_text, remove only the matching part.
194
195
196
197
198
199
        if (
            len(previous_text) >= len(self.buffered_delta_text)
            and previous_text[-len(self.buffered_delta_text) :]
            == self.buffered_delta_text
        ):
            previous_text = previous_text[: -len(self.buffered_delta_text)]
200
            current_text = previous_text + delta_text
201
202
203
204

        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
205
        if self.tool_call_start_token not in current_text:
206
207
208
209
210
211
            logger.debug("No tool call tokens found!")
            return DeltaMessage(content=delta_text)

        try:
            # figure out where we are in the parsing by counting tool call
            # start & end tags
212
            prev_tool_start_count = previous_text.count(self.tool_call_start_token)
213
            prev_tool_end_count = previous_text.count(self.tool_call_end_token)
214
            cur_tool_start_count = current_text.count(self.tool_call_start_token)
215
            cur_tool_end_count = current_text.count(self.tool_call_end_token)
216
217
            tool_call_portion = None
            text_portion = None
218
219

            # case: if we're generating text, OR rounding out a tool call
220
221
222
223
224
            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
            ):
225
                logger.debug("Generating text content! skipping tool parsing.")
226
227
228
229
230
                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
231
232
233
234
235
236
237
                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()
238
239
240
241
242
243

            # case: if tool open & close tag counts don't match, we're doing
            # imaginary "else" block here
            # something with tools with this diff.
            # flags for partial JSON parting. exported constants from
            # "Allow" are handled via BIT MASK
244
            flags = Allow.ALL if self.current_tool_name_sent else Allow.ALL & ~Allow.STR
245
246

            # case -- we're starting a new tool call
247
248
249
250
            if (
                cur_tool_start_count > cur_tool_end_count
                and cur_tool_start_count > prev_tool_start_count
            ):
251
                if len(delta_token_ids) > 1:
252
253
254
                    tool_call_portion = current_text.split(self.tool_call_start_token)[
                        -1
                    ]
255
256
257
258
259
260
261
262
263
264
265
266
267
                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
268
269
270
271
            elif (
                cur_tool_start_count > cur_tool_end_count
                and cur_tool_start_count == prev_tool_start_count
            ):
272
                # get the portion of the text that's the tool call
273
                tool_call_portion = current_text.split(self.tool_call_start_token)[-1]
274
275
276
                text_portion = None

            # case -- the current tool call is being closed.
277
278
279
280
281
282
            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")
283
                    return None
284
                diff = self.prev_tool_call_arr[self.current_tool_id].get("arguments")
285
                if diff:
286
287
288
289
290
291
                    diff = (
                        diff.encode("utf-8").decode("unicode_escape")
                        if diff is str
                        else diff
                    )
                    if '"}' not in delta_text:
292
293
294
                        return None
                    end_loc = delta_text.rindex('"}')
                    diff = delta_text[:end_loc] + '"}'
295
296
                    logger.debug(
                        "Finishing tool and found diff that had not "
297
298
299
300
301
302
303
304
305
306
307
308
309
310
                        "been streamed yet: %s",
                        diff,
                    )
                    self.streamed_args_for_tool[self.current_tool_id] += diff
                    return DeltaMessage(
                        tool_calls=[
                            DeltaToolCall(
                                index=self.current_tool_id,
                                function=DeltaFunctionCall(arguments=diff).model_dump(
                                    exclude_none=True
                                ),
                            )
                        ]
                    )
311
312
313
314
315
316
317
318
319

            # 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

            try:
320
321
322
323
324
                current_tool_call = (
                    partial_json_parser.loads(tool_call_portion or "{}", flags)
                    if tool_call_portion
                    else None
                )
325
326
                logger.debug("Parsed tool call %s", current_tool_call)
            except partial_json_parser.core.exceptions.MalformedJSON:
327
                logger.debug("not enough tokens to parse into JSON yet")
328
                return None
329
330
331
            except json.decoder.JSONDecodeError:
                logger.debug("unable to parse JSON")
                return None
332

333
334
335
            if current_tool_call is None:
                return None

336
337
            # case - we haven't sent the tool name yet. If it's available, send
            #   it. otherwise, wait until it's available.
338
            if not self.current_tool_name_sent:
339
                function_name: str | None = current_tool_call.get("name")
340
341
                if function_name:
                    self.current_tool_name_sent = True
342
343
344
345
346
347
348
349
350
351
352
353
                    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),
                            )
                        ]
                    )
354
355
356
357
358
359
360
361
                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
362
363
364
365
366
                delta = (
                    DeltaMessage(content=delta_text)
                    if text_portion is not None
                    else None
                )
367
368
369
370
371
                return delta

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

372
373
374
            if current_tool_call is None:
                return None

375
376
377
            logger.debug(
                "Trying to parse current tool call with ID %s", self.current_tool_id
            )
378
379
380
381
382
383
384
385

            # 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
386
387
388
            prev_arguments = self.prev_tool_call_arr[self.current_tool_id].get(
                "arguments"
            )
389
            assert current_tool_call is not None
390
391
392
393
394
395
396
397
398
399
400
401
402
            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:
403
404
405
406
                logger.error(
                    "should be impossible to have arguments reset "
                    "mid-call. skipping streaming anything."
                )
407
408
409
410
411
                delta = None

            # case -- we now have the first info about arguments available from
            #   autocompleting the JSON
            elif cur_arguments and not prev_arguments:
412
413
414
415
416
417
418
419
420
421
                # extract the content after {"name": ..., "arguments":
                #   directly from tool_call_portion as cur_arguments_json,
                #   since cur_arguments may differ from the original text
                #   due to partial JSON parsing
                #   for example, tool_call_portion =
                #     {"name": "search", "arguments": {"search_request": {"
                #   but cur_arguments =
                #     {"search_request": {}}
                function_name = current_tool_call.get("name")
                match = re.search(
422
423
424
425
426
427
                    r'\{"name":\s*"'
                    + re.escape(function_name)
                    + r'"\s*,\s*"arguments":\s*(.*)',
                    tool_call_portion.strip(),
                    re.DOTALL,
                )
428
429
430
                if match:
                    cur_arguments_json = match.group(1)
                else:
431
                    cur_arguments_json = json.dumps(cur_arguments, ensure_ascii=False)
432

433
                logger.debug("finding %s in %s", delta_text, cur_arguments_json)
434

435
                # get the location where previous args differ from current.
436
                if delta_text not in cur_arguments_json:
437
                    return None
438
439
440
                args_delta_start_loc = cur_arguments_json.rindex(delta_text) + len(
                    delta_text
                )
441
442
443

                # use that to find the actual delta
                arguments_delta = cur_arguments_json[:args_delta_start_loc]
444
445
446
447
448
449
450
451
452
453
454
455
456
                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
457
458
459

            # last case -- we have an update to existing arguments.
            elif cur_arguments and prev_arguments:
460
461
462
463
464
465
466
467
468
469
                # judge whether the tool_call_portion is a complete JSON
                try:
                    json.loads(tool_call_portion)
                    is_complete_json = True
                except Exception:
                    is_complete_json = False

                # if the delta_text ends with a '}' and tool_call_portion is a
                #   complete JSON, then the last '}' does not belong to the
                #   arguments, so we should trim it off
470
471
472
473
474
475
                if (
                    isinstance(delta_text, str)
                    and len(delta_text.rstrip()) >= 1
                    and delta_text.rstrip()[-1] == "}"
                    and is_complete_json
                ):
476
477
478
                    delta_text = delta_text.rstrip()[:-1]

                logger.debug("got diff %s", delta_text)
479

480
481
482
483
484
485
486
487
488
489
490
                delta = DeltaMessage(
                    tool_calls=[
                        DeltaToolCall(
                            index=self.current_tool_id,
                            function=DeltaFunctionCall(arguments=delta_text).model_dump(
                                exclude_none=True
                            ),
                        )
                    ]
                )
                self.streamed_args_for_tool[self.current_tool_id] += delta_text
491
492
493

            # handle saving the state for the current tool into
            # the "prev" list for use in diffing for the next iteration
494
            assert isinstance(current_tool_call, dict)
495
            if self.current_tool_id == len(self.prev_tool_call_arr) - 1:
496
                self.prev_tool_call_arr[self.current_tool_id] = current_tool_call
497
498
499
500
501
            else:
                self.prev_tool_call_arr.append(current_tool_call)

            return delta

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