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

4
5
from __future__ import annotations

6
import os
7
from abc import abstractmethod
8
from collections.abc import Sequence
9
from functools import cached_property
10
from typing import TYPE_CHECKING, Any, Callable, Union
11
12
13
14

from vllm.logger import init_logger
from vllm.utils import import_from_path, is_list_of

15
if TYPE_CHECKING:
16
17
18
19
20
    from vllm.entrypoints.openai.protocol import (
        ChatCompletionRequest,
        DeltaMessage,
        ResponsesRequest,
    )
21
22
23
24
25
26
27
    from vllm.transformers_utils.tokenizer import AnyTokenizer
else:
    ChatCompletionRequest = Any
    DeltaMessage = Any
    ResponsesRequest = Any
    AnyTokenizer = Any

28
29
30
31
32
logger = init_logger(__name__)


class ReasoningParser:
    """
33
    Abstract reasoning parser class that should not be used directly.
34
35
36
37
38
    Provided and methods should be used in derived classes.

    It is used to extract reasoning content from the model output.
    """

39
    def __init__(self, tokenizer: AnyTokenizer, *args, **kwargs):
40
41
42
        self.model_tokenizer = tokenizer

    @cached_property
43
    def vocab(self) -> dict[str, int]:
44
45
46
47
        # NOTE: Only PreTrainedTokenizerFast is guaranteed to have .vocab
        # whereas all tokenizers have .get_vocab()
        return self.model_tokenizer.get_vocab()

48
    @abstractmethod
49
    def is_reasoning_end(self, input_ids: list[int]) -> bool:
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
        """
        Check if the reasoning content ends in the input_ids.

        It is used in structured engines like `xgrammar` to check if the
        reasoning content ends in the model output.

        Parameters:
        input_ids: list[int]
            The input_ids of the model output.

        Returns:
        bool
            True if the reasoning content ends in the input_ids.
        """

    @abstractmethod
    def extract_content_ids(self, input_ids: list[int]) -> list[int]:
        """
        Extract content token ids from the input_ids.
        Parameters:
        input_ids: list[int]
            The input_ids of the model output.
        Returns:
        list[int]
            The extracted content from the input_ids.
        """

    @abstractmethod
78
    def extract_reasoning_content(
79
80
81
        self,
        model_output: str,
        request: Union[ChatCompletionRequest, ResponsesRequest],
82
    ) -> tuple[str | None, str | None]:
83
84
85
86
87
88
89
90
91
92
93
94
95
96
        """
        Extract reasoning content from a complete model-generated string.

        Used for non-streaming responses where we have the entire model response
        available before sending to the client.

        Parameters:
        model_output: str
            The model-generated string to extract reasoning content from.

        request: ChatCompletionRequest
            The request object that was used to generate the model_output.

        Returns:
97
        tuple[Optional[str], Optional[str]]
98
99
100
            A tuple containing the reasoning content and the content.
        """

101
    @abstractmethod
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
    def extract_reasoning_content_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],
    ) -> Union[DeltaMessage, None]:
        """
        Instance method that should be implemented for extracting reasoning
        from an incomplete response; for use when handling reasoning 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)
        """
118

119
120

class ReasoningParserManager:
121
    reasoning_parsers: dict[str, type] = {}
122
123

    @classmethod
124
    def get_reasoning_parser(cls, name: str | None) -> type[ReasoningParser]:
125
126
127
128
129
130
131
132
        """
        Get reasoning parser by name which is registered by `register_module`.

        Raise a KeyError exception if the name is not registered.
        """
        if name in cls.reasoning_parsers:
            return cls.reasoning_parsers[name]

133
        raise KeyError(f"reasoning helper: '{name}' not found in reasoning_parsers")
134
135

    @classmethod
136
137
138
    def _register_module(
        cls,
        module: type,
139
        module_name: Union[str, list[str]] | None = None,
140
141
        force: bool = True,
    ) -> None:
142
        if not issubclass(module, ReasoningParser):
143
144
145
            raise TypeError(
                f"module must be subclass of ReasoningParser, but got {type(module)}"
            )
146
147
148
149
150
151
152
        if module_name is None:
            module_name = module.__name__
        if isinstance(module_name, str):
            module_name = [module_name]
        for name in module_name:
            if not force and name in cls.reasoning_parsers:
                existed_module = cls.reasoning_parsers[name]
153
154
155
                raise KeyError(
                    f"{name} is already registered at {existed_module.__module__}"
                )
156
157
158
159
            cls.reasoning_parsers[name] = module

    @classmethod
    def register_module(
160
        cls,
161
        name: Union[str, list[str]] | None = None,
162
163
164
        force: bool = True,
        module: Union[type, None] = None,
    ) -> Union[type, Callable]:
165
166
        """
        Register module with the given name or name list. it can be used as a
167
        decoder(with module as None) or normal function(with module as not
168
169
170
171
172
173
        None).
        """
        if not isinstance(force, bool):
            raise TypeError(f"force must be a boolean, but got {type(force)}")

        # raise the error ahead of time
174
        if not (name is None or isinstance(name, str) or is_list_of(name, str)):
175
176
            raise TypeError(
                "name must be None, an instance of str, or a sequence of str, "
177
178
                f"but got {type(name)}"
            )
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194

        # use it as a normal method: x.register_module(module=SomeClass)
        if module is not None:
            cls._register_module(module=module, module_name=name, force=force)
            return module

        # use it as a decorator: @x.register_module()
        def _register(module):
            cls._register_module(module=module, module_name=name, force=force)
            return module

        return _register

    @classmethod
    def import_reasoning_parser(cls, plugin_path: str) -> None:
        """
195
        Import a user-defined reasoning parser by the path
196
197
198
199
200
201
202
        of the reasoning parser define file.
        """
        module_name = os.path.splitext(os.path.basename(plugin_path))[0]

        try:
            import_from_path(module_name, plugin_path)
        except Exception:
203
204
205
            logger.exception(
                "Failed to load module '%s' from %s.", module_name, plugin_path
            )
206
            return