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

4
import importlib
5
import os
6
from collections.abc import Callable, Sequence
7
from functools import cached_property
8

9
from openai.types.responses import (
10
    ResponseFormatTextJSONSchemaConfig,
11
    ResponseTextConfig,
12
)
13
from openai.types.responses.function_tool import FunctionTool
14

15
16
from vllm.entrypoints.openai.chat_completion.protocol import (
    ChatCompletionRequest,
17
    ChatCompletionToolsParam,
18
)
19
from vllm.entrypoints.openai.engine.protocol import (
20
21
    DeltaMessage,
    ExtractedToolCallInformation,
22
23
)
from vllm.entrypoints.openai.responses.protocol import (
24
    ResponsesRequest,
25
)
26
from vllm.logger import init_logger
27
28
29
from vllm.sampling_params import (
    StructuredOutputsParams,
)
30
from vllm.tokenizers import TokenizerLike
31
from vllm.tool_parsers.utils import Tool, get_json_schema_from_tools
32
from vllm.utils.collection_utils import is_list_of
33
from vllm.utils.import_utils import import_from_path
34

35
__all__ = ["Tool"]
36

37
logger = init_logger(__name__)
38

39
40
41
42
43
44
45
46

class ToolParser:
    """
    Abstract ToolParser class that should not be used directly. Provided
    properties and methods should be used in
    derived classes.
    """

47
48
49
50
51
52
53
54
55
56
57
    # When True (default), the serving layer uses the standard JSON-based
    # parsing for tool_choice="required" and named function tool_choice,
    # which works for models where guided decoding produces well-formed
    # JSON output (e.g. Hermes).
    # Subclasses set False when the standard parsing does not work for
    # their model's output format (e.g. GLM models that use XML).  When
    # False, the serving layer falls back to the tool_parser's
    # extract_tool_calls / extract_tool_calls_streaming methods for
    # required/named tool_choice, treating them the same as "auto".
    supports_required_and_named: bool = True

58
59
60
61
62
    def __init__(
        self,
        tokenizer: TokenizerLike,
        tools: list[Tool] | None = None,
    ):
63
        self.prev_tool_call_arr: list[dict] = []
64
65
66
        # the index of the tool call that is currently being parsed
        self.current_tool_id: int = -1
        self.current_tool_name_sent: bool = False
67
        self.streamed_args_for_tool: list[str] = []
68
69

        self.model_tokenizer = tokenizer
70
71
72
73
74
75
76
77
        if tools:
            self.tools: list[ChatCompletionToolsParam | FunctionTool] = [
                tool
                for tool in tools
                if isinstance(tool, (ChatCompletionToolsParam, FunctionTool))
            ]
        else:
            self.tools = []
78

79
    @cached_property
80
    def vocab(self) -> dict[str, int]:
81
82
83
84
        # NOTE: Only PreTrainedTokenizerFast is guaranteed to have .vocab
        # whereas all tokenizers have .get_vocab()
        return self.model_tokenizer.get_vocab()

85
86
87
    def adjust_request(
        self, request: ChatCompletionRequest | ResponsesRequest
    ) -> ChatCompletionRequest | ResponsesRequest:
88
89
90
        """
        Static method that used to adjust the request parameters.
        """
91
92
93
94
95
96
97
        if not request.tools:
            return request
        json_schema_from_tool = get_json_schema_from_tools(
            tool_choice=request.tool_choice, tools=request.tools
        )
        # Set structured output params for tool calling
        if json_schema_from_tool is not None:
98
99
100
            if isinstance(request, ChatCompletionRequest):
                # tool_choice: "Forced Function" or "required" will override
                # structured output json settings to make tool calling work correctly
101
                request.structured_outputs = StructuredOutputsParams(
102
                    json=json_schema_from_tool  # type: ignore[call-arg]
103
                )
104
                request.response_format = None
105
            if isinstance(request, ResponsesRequest):
106
107
108
109
110
111
112
113
114
115
116
117
118
119
                # Single-shot construction so Pydantic v2 tracks `format`
                # in __fields_set__ — assigning to `.format` after the bare
                # `ResponseTextConfig()` constructor does not, which can
                # drop the nested config from `model_dump`. Also drop the
                # `description` kwarg: it is not a field on
                # ResponseFormatTextJSONSchemaConfig and was being silently
                # passed through as extra.
                request.text = ResponseTextConfig(
                    format=ResponseFormatTextJSONSchemaConfig(
                        type="json_schema",
                        name="tool_calling_response",
                        schema=json_schema_from_tool,
                        strict=True,
                    )
120
121
                )

122
123
124
        return request

    def extract_tool_calls(
125
126
        self, model_output: str, request: ChatCompletionRequest
    ) -> ExtractedToolCallInformation:
127
128
129
130
131
132
133
134
        """
        Static method that should be implemented for extracting tool calls from
        a complete model-generated string.
        Used for non-streaming responses where we have the entire model response
        available before sending to the client.
        Static because it's stateless.
        """
        raise NotImplementedError(
135
136
            "AbstractToolParser.extract_tool_calls has not been implemented!"
        )
137
138
139
140
141
142
143
144
145

    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],
146
        request: ChatCompletionRequest,
147
    ) -> DeltaMessage | None:
148
149
150
151
152
153
154
155
        """
        Instance method that should be implemented for extracting tool calls
        from an incomplete response; for use when handling tool calls and
        streaming. Has to be an instance method because  it requires state -
        the current tokens/diffs, but also the information about what has
        previously been parsed and extracted (see constructor)
        """
        raise NotImplementedError(
156
157
            "AbstractToolParser.extract_tool_calls_streaming has not been implemented!"
        )
158
159
160


class ToolParserManager:
161
162
163
164
165
166
167
168
169
170
    """
    Central registry for ToolParser implementations.

    Supports two modes:
      - Eager (immediate) registration via `register_module`
      - Lazy registration via `register_lazy_module`
    """

    tool_parsers: dict[str, type[ToolParser]] = {}
    lazy_parsers: dict[str, tuple[str, str]] = {}  # name -> (module_path, class_name)
171
172

    @classmethod
173
    def get_tool_parser(cls, name: str) -> type[ToolParser]:
174
        """
175
        Retrieve a registered or lazily registered ToolParser class.
176

177
178
179
        If the parser is lazily registered,
        it will be imported and cached on first access.
        Raises KeyError if not found.
180
181
182
183
        """
        if name in cls.tool_parsers:
            return cls.tool_parsers[name]

184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
        if name in cls.lazy_parsers:
            return cls._load_lazy_parser(name)

        raise KeyError(f"Tool parser '{name}' not found.")

    @classmethod
    def _load_lazy_parser(cls, name: str) -> type[ToolParser]:
        """Import and register a lazily loaded parser."""
        module_path, class_name = cls.lazy_parsers[name]
        try:
            mod = importlib.import_module(module_path)
            parser_cls = getattr(mod, class_name)
            if not issubclass(parser_cls, ToolParser):
                raise TypeError(
                    f"{class_name} in {module_path} is not a ToolParser subclass."
                )
            cls.tool_parsers[name] = parser_cls  # cache
            return parser_cls
        except Exception as e:
            logger.exception(
                "Failed to import lazy tool parser '%s' from %s: %s",
                name,
                module_path,
                e,
            )
            raise
210
211

    @classmethod
212
213
    def _register_module(
        cls,
214
        module: type[ToolParser],
215
        module_name: str | list[str] | None = None,
216
217
        force: bool = True,
    ) -> None:
218
        """Register a ToolParser class immediately."""
219
220
        if not issubclass(module, ToolParser):
            raise TypeError(
221
                f"module must be subclass of ToolParser, but got {type(module)}"
222
            )
223

224
225
        if module_name is None:
            module_name = module.__name__
226

227
        if isinstance(module_name, str):
228
229
230
231
232
233
234
            module_names = [module_name]
        elif is_list_of(module_name, str):
            module_names = module_name
        else:
            raise TypeError("module_name must be str, list[str], or None.")

        for name in module_names:
235
            if not force and name in cls.tool_parsers:
236
237
                existed = cls.tool_parsers[name]
                raise KeyError(f"{name} is already registered at {existed.__module__}")
238
239
            cls.tool_parsers[name] = module

240
241
242
243
244
245
246
247
    @classmethod
    def register_lazy_module(cls, name: str, module_path: str, class_name: str) -> None:
        """
        Register a lazy module mapping.

        Example:
            ToolParserManager.register_lazy_module(
                name="kimi_k2",
248
                module_path="vllm.tool_parsers.kimi_k2_parser",
249
250
251
252
253
                class_name="KimiK2ToolParser",
            )
        """
        cls.lazy_parsers[name] = (module_path, class_name)

254
255
    @classmethod
    def register_module(
256
        cls,
257
        name: str | list[str] | None = None,
258
        force: bool = True,
259
260
        module: type[ToolParser] | None = None,
    ) -> type[ToolParser] | Callable[[type[ToolParser]], type[ToolParser]]:
261
        """
262
263
264
265
266
267
268
269
270
        Register module immediately or lazily (as a decorator).

        Usage:
            @ToolParserManager.register_module("kimi_k2")
            class KimiK2ToolParser(ToolParser):
                ...

        Or:
            ToolParserManager.register_module(module=SomeToolParser)
271
272
        """
        if not isinstance(force, bool):
273
            raise TypeError(f"force must be a boolean, but got {type(force)}")
274

275
        # Immediate registration
276
277
278
279
        if module is not None:
            cls._register_module(module=module, module_name=name, force=force)
            return module

280
281
282
283
        # Decorator usage
        def _decorator(obj: type[ToolParser]) -> type[ToolParser]:
            module_path = obj.__module__
            class_name = obj.__name__
284

285
286
            if isinstance(name, str):
                names = [name]
287
            elif name is not None and is_list_of(name, str):
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
                names = name
            else:
                names = [class_name]

            for n in names:
                # Lazy mapping only: do not import now
                cls.lazy_parsers[n] = (module_path, class_name)

            return obj

        return _decorator

    @classmethod
    def list_registered(cls) -> list[str]:
        """Return names of all eagerly and lazily registered tool parsers."""
        return sorted(set(cls.tool_parsers.keys()) | set(cls.lazy_parsers.keys()))
304
305
306

    @classmethod
    def import_tool_parser(cls, plugin_path: str) -> None:
307
        """Import a user-defined parser file from arbitrary path."""
308

309
        module_name = os.path.splitext(os.path.basename(plugin_path))[0]
310
311
312
        try:
            import_from_path(module_name, plugin_path)
        except Exception:
313
314
315
            logger.exception(
                "Failed to load module '%s' from %s.", module_name, plugin_path
            )