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


5
from vllm.entrypoints.openai.protocol import ChatCompletionRequest, ResponsesRequest
6
from vllm.reasoning.basic_parsers import BaseThinkingReasoningParser
7
8


9
class Qwen3ReasoningParser(BaseThinkingReasoningParser):
10
11
12
13
14
15
16
17
18
19
    """
    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.
    """

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

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

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

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

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

43
44
45
46
        Returns:
            tuple[Optional[str], Optional[str]]: reasoning content and content
        """

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

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

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

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

        final_content = content or None
67
        return reasoning, final_content