如何使用vLLM运行gpt-oss

发布于:2025-08-08 ⋅ 阅读:(21) ⋅ 点赞:(0)

vLLM 是一款开源的高吞吐量推理引擎,旨在通过优化内存使用和处理速度来高效服务大型语言模型(LLM)。本指南将逐步介绍如何使用 vLLM 在服务器上部署 gpt-oss-20b 或 gpt-oss-120b,将其作为 API 为您的应用程序提供 gpt-oss 服务,甚至将其连接到 Agents SDK。

请注意,本指南适用于配备专用 GPU(如英伟达 H100)的服务器应用程序。

选择模型

vLLM支持两种规模的gpt-oss模型:

  • openai/gpt-oss-20b
    • 较小模型
    • 仅需约16GB显存
  • openai/gpt-oss-120b
    • 完整规模大模型
    • 建议≥60GB显存
    • 可单张H100显卡或多GPU配置运行

两个模型均默认采用MXFP4量化格式。

快速配置

  1. 安装vLLM
    vLLM推荐使用uv管理Python环境,能根据运行环境自动选择最佳实现。详见其快速入门指南。执行以下命令创建虚拟环境并安装vLLM:
uv venv --python 3.12 --seed
source .venv/bin/activate
uv pip install --pre vllm==0.10.1+gptoss \
    --extra-index-url https://wheels.vllm.ai/gpt-oss/ \
    --extra-index-url https://download.pytorch.org/whl/nightly/cu128 \
    --index-strategy unsafe-best-match
  1. 启动服务器并下载模型
    vLLM 提供了一个 serve 命令,该命令会自动从 HuggingFace 下载模型,并在本地主机(localhost:8000)上启动一个与 OpenAI 兼容的服务器。根据您所需的模型大小,在服务器的终端会话中运行以下命令。
# For 20B
vllm serve openai/gpt-oss-20b
 
# For 120B
vllm serve openai/gpt-oss-120b

使用API

vLLM提供了兼容Chat Completions的API和兼容Responses的API,因此您无需做太多修改即可使用OpenAI SDK。以下是一个Python示例:

from openai import OpenAI
 
client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"
)
 
result = client.chat.completions.create(
    model="openai/gpt-oss-20b",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Explain what MXFP4 quantization is."}
    ]
)
 
print(result.choices[0].message.content)
 
response = client.responses.create(
    model="openai/gpt-oss-120b",
    instructions="You are a helfpul assistant.",
    input="Explain what MXFP4 quantization is."
)
 
print(response.output_text)

如果您之前使用过OpenAI SDK,那么这一切会立刻感到熟悉,只需更改基础URL,您现有的代码就能正常运行。

使用工具(函数调用)

vLLM支持函数调用功能,并赋予模型浏览能力。

函数调用可通过响应API和聊天补全API两种方式实现。

以下是通过聊天补全调用函数的示例:

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get current weather in a given city",
            "parameters": {
                "type": "object",
                "properties": {"city": {"type": "string"}},
                "required": ["city"]
            },
        },
    }
]
 
response = client.chat.completions.create(
    model="openai/gpt-oss-120b",
    messages=[{"role": "user", "content": "What's the weather in Berlin right now?"}],
    tools=tools
)
 
print(response.choices[0].message)

由于模型能够将工具调用作为思维链(CoT)的一部分执行,因此您需要将API返回的推理结果反馈到后续的工具调用中,直到模型得出最终答案为止。

Agents SDK集成

想将gpt-oss与OpenAI的Agents SDK结合使用吗?

两种Agents SDK都允许您覆盖OpenAI的基础客户端,将其指向vLLM以使用自托管模型。另外,对于Python SDK,您还可以使用LiteLLM集成来代理到vLLM。

以下是一个Python Agents SDK的示例:

uv pip install openai-agents
import asyncio
from openai import AsyncOpenAI
from agents import Agent, Runner, function_tool, OpenAIResponsesModel, set_tracing_disabled
 
set_tracing_disabled(True)
 
@function_tool
def get_weather(city: str):
    print(f"[debug] getting weather for {city}")
    return f"The weather in {city} is sunny."
 
 
async def main(model: str, api_key: str):
    agent = Agent(
        name="Assistant",
        instructions="You only respond in haikus.",
        model=OpenAIResponsesModel(
            model="openai/gpt-oss-120b",
            openai_client=AsyncOpenAI(
                base_url="http://localhost:8000/v1",
                api_key="EMPTY",
            ),
        )
        tools=[get_weather],
    )
 
    result = await Runner.run(agent, "What's the weather in Tokyo?")
    print(result.final_output)
 
if __name__ == "__main__":
    asyncio.run(main())

使用vLLM进行直接采样

除了通过vllm serve将vLLM作为API服务器运行外,您还可以直接使用vLLM的Python库来控制推理过程。

若直接使用vLLM进行采样,必须确保输入提示遵循和谐响应格式,否则模型将无法正常运行。为此您可以使用openai-harmony SDK

uv pip install openai-harmony

安装完成后,您可以使用harmony工具对vLLM生成函数输出的token进行编码和解析。

import json
from openai_harmony import (
    HarmonyEncodingName,
    load_harmony_encoding,
    Conversation,
    Message,
    Role,
    SystemContent,
    DeveloperContent,
)
 
from vllm import LLM, SamplingParams
 
# --- 1) Render the prefill with Harmony ---
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
 
convo = Conversation.from_messages(
    [
        Message.from_role_and_content(Role.SYSTEM, SystemContent.new()),
        Message.from_role_and_content(
            Role.DEVELOPER,
            DeveloperContent.new().with_instructions("Always respond in riddles"),
        ),
        Message.from_role_and_content(Role.USER, "What is the weather like in SF?"),
    ]
)
 
prefill_ids = encoding.render_conversation_for_completion(convo, Role.ASSISTANT)
 
# Harmony stop tokens (pass to sampler so they won't be included in output)
stop_token_ids = encoding.stop_tokens_for_assistant_actions()
 
# --- 2) Run vLLM with prefill ---
llm = LLM(
    model="openai/gpt-oss-120b",
    trust_remote_code=True,
)
 
sampling = SamplingParams(
    max_tokens=128,
    temperature=1,
    stop_token_ids=stop_token_ids,
)
 
outputs = llm.generate(
    prompt_token_ids=[prefill_ids],   # batch of size 1
    sampling_params=sampling,
)
 
# vLLM gives you both text and token IDs
gen = outputs[0].outputs[0]
text = gen.text
output_tokens = gen.token_ids  # <-- these are the completion token IDs (no prefill)
 
# --- 3) Parse the completion token IDs back into structured Harmony messages ---
entries = encoding.parse_messages_from_completion_tokens(output_tokens, Role.ASSISTANT)
 
# 'entries' is a sequence of structured conversation entries (assistant messages, tool calls, etc.).
for message in entries:
    print(f"{json.dumps(message.to_dict())}")

网站公告

今日签到

点亮在社区的每一天
去签到