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

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


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

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

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

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

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

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

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

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

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

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

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

        final_content = content or None
71
        return reasoning, final_content