推理输出¶
vLLM 支持推理模型如 DeepSeek R1,这类模型专门设计用于生成包含推理步骤和最终结论的输出内容。
推理模型在其输出中会返回一个额外的reasoning_content字段,该字段包含导致最终结论的推理步骤。其他模型的输出中不存在此字段。
支持的模型¶
vLLM目前支持以下推理模型:
| 模型系列 | 解析器名称 | 结构化输出支持 | 工具调用 |
|---|---|---|---|
| DeepSeek R1 series | deepseek_r1 | guided_json, guided_regex | ❌ |
| QwQ-32B | deepseek_r1 | guided_json, guided_regex | ✅ |
| IBM Granite 3.2 language models | granite | ❌ | ❌ |
| Qwen3 series | qwen3 | guided_json, guided_regex | ✅ |
| Hunyuan A13B series | hunyuan_a13b | guided_json, guided_regex | ✅ |
注意
IBM Granite 3.2的推理功能默认是禁用的;要启用它,您还必须在chat_template_kwargs中传递thinking=True。Qwen3系列的推理功能默认是启用的。要禁用它,您必须在chat_template_kwargs中传递enable_thinking=False。
快速入门¶
要使用推理模型,您需要在向聊天补全端点发送请求时指定--reasoning-parser标志。--reasoning-parser标志用于指定从模型输出中提取推理内容所使用的解析器。
接下来,向模型发起一个请求,该请求应在响应中返回推理内容。
Code
from openai import OpenAI
# Modify OpenAI's API key and API base to use vLLM's API server.
openai_api_key = "EMPTY"
openai_api_base = "http://localhost:8000/v1"
client = OpenAI(
api_key=openai_api_key,
base_url=openai_api_base,
)
models = client.models.list()
model = models.data[0].id
# Round 1
messages = [{"role": "user", "content": "9.11 and 9.8, which is greater?"}]
# For granite, add: `extra_body={"chat_template_kwargs": {"thinking": True}}`
# For Qwen3 series, if you want to disable thinking in reasoning mode, add:
# extra_body={"chat_template_kwargs": {"enable_thinking": False}}
response = client.chat.completions.create(model=model, messages=messages)
reasoning_content = response.choices[0].message.reasoning_content
content = response.choices[0].message.content
print("reasoning_content:", reasoning_content)
print("content:", content)
reasoning_content字段包含导致最终结论的推理步骤,而content字段包含最终结论。
流式聊天补全¶
推理模型也支持流式聊天补全功能。reasoning_content字段可在聊天补全响应块的delta字段中使用。
Json
{
"id": "chatcmpl-123",
"object": "chat.completion.chunk",
"created": 1694268190,
"model": "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B",
"system_fingerprint": "fp_44709d6fcb",
"choices": [
{
"index": 0,
"delta": {
"role": "assistant",
"reasoning_content": "is",
},
"logprobs": null,
"finish_reason": null
}
]
}
OpenAI Python客户端库官方不支持流式输出中的reasoning_content属性。但该客户端支持响应中的额外属性。您可以使用hasattr来检查响应中是否存在reasoning_content属性。例如:
Code
from openai import OpenAI
# Modify OpenAI's API key and API base to use vLLM's API server.
openai_api_key = "EMPTY"
openai_api_base = "http://localhost:8000/v1"
client = OpenAI(
api_key=openai_api_key,
base_url=openai_api_base,
)
models = client.models.list()
model = models.data[0].id
messages = [{"role": "user", "content": "9.11 and 9.8, which is greater?"}]
# For granite, add: `extra_body={"chat_template_kwargs": {"thinking": True}}`
# For Qwen3 series, if you want to disable thinking in reasoning mode, add:
# extra_body={"chat_template_kwargs": {"enable_thinking": False}}
stream = client.chat.completions.create(model=model,
messages=messages,
stream=True)
print("client: Start streaming chat completions...")
printed_reasoning_content = False
printed_content = False
for chunk in stream:
# Safely extract reasoning_content and content from delta,
# defaulting to None if attributes don't exist or are empty strings
reasoning_content = (
getattr(chunk.choices[0].delta, "reasoning_content", None) or None
)
content = getattr(chunk.choices[0].delta, "content", None) or None
if reasoning_content is not None:
if not printed_reasoning_content:
printed_reasoning_content = True
print("reasoning_content:", end="", flush=True)
print(reasoning_content, end="", flush=True)
elif content is not None:
if not printed_content:
printed_content = True
print("\ncontent:", end="", flush=True)
# Extract and print the content
print(content, end="", flush=True)
在访问前请记得检查响应中是否存在reasoning_content。您可以查看示例。
工具调用¶
当同时启用工具调用和推理解析器时,推理内容也可用。此外,工具调用仅解析content字段中的函数,而不解析reasoning_content中的函数。
Code
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="dummy")
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City and state, e.g., 'San Francisco, CA'"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["location", "unit"]
}
}
}]
response = client.chat.completions.create(
model=client.models.list().data[0].id,
messages=[{"role": "user", "content": "What's the weather like in San Francisco?"}],
tools=tools,
tool_choice="auto"
)
print(response)
tool_call = response.choices[0].message.tool_calls[0].function
print(f"reasoning_content: {response.choices[0].message.reasoning_content}")
print(f"Function called: {tool_call.name}")
print(f"Arguments: {tool_call.arguments}")
更多示例请参考 examples/online_serving/openai_chat_completion_tool_calls_with_reasoning.py。
限制¶
- 推理内容仅适用于在线服务的聊天补全端点 (
/v1/chat/completions)。
如何支持新的推理模型¶
您可以添加一个新的ReasoningParser,类似于 vllm/reasoning/deepseek_r1_reasoning_parser.py。
Code
# import the required packages
from vllm.reasoning import ReasoningParser, ReasoningParserManager
from vllm.entrypoints.openai.protocol import (ChatCompletionRequest,
DeltaMessage)
# define a reasoning parser and register it to vllm
# the name list in register_module can be used
# in --reasoning-parser.
@ReasoningParserManager.register_module(["example"])
class ExampleParser(ReasoningParser):
def __init__(self, tokenizer: AnyTokenizer):
super().__init__(tokenizer)
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)
"""
def extract_reasoning_content(
self, model_output: str, request: ChatCompletionRequest
) -> tuple[Optional[str], Optional[str]]:
"""
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:
tuple[Optional[str], Optional[str]]
A tuple containing the reasoning content and the content.
"""
此外,要启用结构化输出,你需要创建一个新的Reasoner,类似于 vllm/reasoning/deepseek_r1_reasoning_parser.py中的实现。
Code
@dataclass
class DeepSeekReasoner(Reasoner):
"""
Reasoner for DeepSeek R series models.
"""
start_token_id: int
end_token_id: int
start_token: str = "<think>"
end_token: str = "</think>"
@classmethod
def from_tokenizer(cls, tokenizer: PreTrainedTokenizer) -> Reasoner:
return cls(start_token_id=tokenizer.encode(
"<think>", add_special_tokens=False)[0],
end_token_id=tokenizer.encode("</think>",
add_special_tokens=False)[0])
def is_reasoning_end(self, input_ids: list[int]) -> bool:
return self.end_token_id in input_ids
...
类似xgrammar的结构化输出引擎会使用end_token_id来检查模型输出中是否存在推理内容,如果存在则跳过结构化输出。
最后,您可以通过使用--reasoning-parser标志来启用模型的推理功能。