"vllm/config/__init__.py" did not exist on "cde384cd92c811c2237cf21681166fd41437c8a3"
qwen3_reasoning_parser.py 2.5 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
5
6
7
from vllm.entrypoints.openai.chat_completion.protocol import (
    ChatCompletionRequest,
)
from vllm.entrypoints.openai.engine.protocol import ResponsesRequest
8
from vllm.reasoning.basic_parsers import BaseThinkingReasoningParser
9
10


11
class Qwen3ReasoningParser(BaseThinkingReasoningParser):
12
13
14
15
16
17
18
19
20
21
    """
    Reasoning parser for the Qwen3 model.

    The Qwen3 model uses <think>...</think> tokens to denote reasoning text
    within its output. The model provides a strict switch to disable reasoning
    output via the 'enable_thinking=False' parameter. This parser extracts the
    reasoning content enclosed by <think> and </think> tokens from the model's
    output.
    """

22
23
24
25
    @property
    def start_token(self) -> str:
        """The token that starts reasoning content."""
        return "<think>"
26

27
28
29
30
    @property
    def end_token(self) -> str:
        """The token that ends reasoning content."""
        return "</think>"
31

32
    def extract_reasoning(
33
34
        self, model_output: str, request: ChatCompletionRequest | ResponsesRequest
    ) -> tuple[str | None, str | None]:
35
36
        """
        Extract reasoning content from the model output.
37

38
39
        Qwen3 has stricter requirements - it needs both start and end tokens
        to be present, unlike other models that work with just the end token.
40
41

        For text <think>abc</think>xyz:
42
        - 'abc' goes to reasoning
43
        - 'xyz' goes to content
44

45
46
47
48
        Returns:
            tuple[Optional[str], Optional[str]]: reasoning content and content
        """

49
        # Check if the model output contains both <think> and </think> tokens.
50
        if self.start_token not in model_output or self.end_token not in model_output:
51
            return None, model_output
52

53
54
        # Check if the <think> is present in the model output, remove it
        # if it is present.
55
        model_output_parts = model_output.partition(self.start_token)
56
57
58
        model_output = (
            model_output_parts[2] if model_output_parts[1] else model_output_parts[0]
        )
59

60
61
        # Check if the model output contains the </think> tokens.
        # If the end token is not found, return the model output as is.
62
        if self.end_token not in model_output:
63
64
65
            return None, model_output

        # Extract reasoning content from the model output.
66
        reasoning, _, content = model_output.partition(self.end_token)
67
68

        final_content = content or None
69
        return reasoning, final_content