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

from typing import Optional, Union

6
from vllm.entrypoints.openai.protocol import ChatCompletionRequest, ResponsesRequest
7
8
from vllm.reasoning.abs_reasoning_parsers import ReasoningParserManager
from vllm.reasoning.basic_parsers import BaseThinkingReasoningParser
9
10
11


@ReasoningParserManager.register_module("qwen3")
12
class Qwen3ReasoningParser(BaseThinkingReasoningParser):
13
14
15
16
17
18
19
20
21
22
    """
    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.
    """

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

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

    def extract_reasoning_content(
34
        self, model_output: str, request: Union[ChatCompletionRequest, ResponsesRequest]
35
    ) -> tuple[Optional[str], Optional[str]]:
36
37
        """
        Extract reasoning content from the model output.
38

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

        For text <think>abc</think>xyz:
        - 'abc' goes to reasoning_content
        - 'xyz' goes to content
45

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

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

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

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

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

        final_content = content or None
        return reasoning_content, final_content