推理提供商文档

如何使用 OpenAI 的 GPT OSS

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

如何使用 OpenAI 的 GPT OSS

本指南将引导您使用 Hugging Face 推理提供商的 OpenAI 最新 GPT OSS 模型。GPT OSS 是一个开放权重系列,专为强大的推理、代理工作流和多功能开发人员用例而构建,它有两种大小:一个具有 120B 参数 (gpt-oss-120b),另一个较小,具有 20B 参数 (gpt-oss-20b)。

这两个模型都支持推理提供商,并且可以通过与 OpenAI 兼容的聊天完成 API,或更高级的响应 API 进行访问。

快速入门

  1. 您将需要您的 Hugging Face 令牌。从您的设置页面获取一个。然后,将其设置为环境变量。
export HF_TOKEN="your_token_here"

💡 专家提示:免费套餐每月提供推理积分,供您开始构建和实验。升级到Hugging Face PRO 可获得更大的灵活性,每月 2 美元的积分以及所有提供商的按需付费访问权限!

  1. 安装官方 OpenAI SDK。
python
javascript
pip install openai

聊天完成

在推理提供商上使用 GPT OSS 模型非常简单。与 OpenAI 兼容的聊天完成 API 支持工具调用、结构化输出、流式传输和推理工作量控制等功能。

以下是一个使用快速的 Cerebras 提供商通过gpt-oss-120b 的基本示例

python
javascript
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://router.huggingface.co/v1",
    api_key=os.getenv("HF_TOKEN"),
)

response = client.chat.completions.create(
    model="openai/gpt-oss-120b:cerebras",
    messages=[{"role": "user", "content": "Tell me a fun fact about the Eiffel Tower."}],
)

print(response.choices[0].message.content)

您还可以授予模型访问工具的权限。下面,我们定义了一个 `get_current_weather` 函数,并让模型决定是否调用它

python
javascript
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://router.huggingface.co/v1",
    api_key=os.getenv("HF_TOKEN"),
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "Get the current weather in a given location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA",
                    },
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                },
                "required": ["location"],
            },
        },
    }
]

response = client.chat.completions.create(
    model="openai/gpt-oss-120b:cerebras",
    messages=[{"role": "user", "content": "What is the weather in Paris in Celsius?"}],
    tools=tools,
    tool_choice="auto",
)

# The response will contain the tool_calls object if the model decides to use the tool
print(response.choices[0].message)

对于数据提取等结构化任务,您可以使用 `response_format` 参数强制模型返回有效的 JSON 对象。我们使用 Fireworks AI 提供商。

python
javascript
import json
import os

from openai import OpenAI


client = OpenAI(
    base_url="https://router.huggingface.co/v1",
    api_key=os.getenv("HF_TOKEN"),
)

# Force the model to output a JSON object
response = client.chat.completions.create(
    model="openai/gpt-oss-120b:fireworks-ai",
    messages=[
        {
            "role": "system",
            "content": "You are a helpful assistant designed to output JSON.",
        },
        {
            "role": "user",
            "content": "Extract the name, city, and profession from the following sentence: 'Amélie is a chef who lives in Paris.'",
        },
    ],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "person",
            "schema": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "city": {"type": "string"},
                    "profession": {"type": "string"},
                },
                "required": ["name", "city", "profession"],
            },
        },
    },
)

# The output is a valid JSON string that can be easily parsed
output_json_string = response.choices[0].message.content
parsed_output = json.loads(output_json_string)

print(parsed_output)

只需几行代码,您就可以开始使用 Hugging Face 推理提供商的 GPT OSS 模型,它们完全兼容 OpenAI API,易于集成,开箱即用!

响应 API

推理提供商实现了**与 OpenAI 兼容的响应 API**,这是基于聊天的模型最先进的接口。它支持流式传输、结构化输出、工具调用、推理工作量控制(低、中、高)以及将任务委派给外部服务的远程 MCP 调用。

主要优势

  • 以代理为中心的设计:API 专为简化代理任务的工作流而构建。它具有用于集成复杂工具使用(例如远程 MCP 调用)的本机框架。
  • 有状态、事件驱动的架构:具有有状态、事件驱动的架构。它不是在每次更新时重新发送整个文本,而是流式传输描述精确更改(“增量”)的语义事件。这消除了手动状态跟踪的需要。
  • 简化复杂逻辑的开发:事件驱动模型使构建具有多步逻辑的可靠应用程序变得更容易。您的代码只需侦听特定事件,从而实现更简洁、更强大的集成。

此实现基于开源项目 huggingface/responses.js

流式响应

与传统的文本流式传输不同,响应 API 使用语义事件系统进行流式传输。这意味着流不仅仅是原始文本,而是一系列结构化事件对象。每个事件都有一个类型,因此您可以侦听您关心的特定事件,例如添加内容(`output_text.delta`)或消息完成(`completed`)。下面的示例演示如何迭代这些事件并打印到达的内容。

python
javascript
import os
from openai import OpenAI


client = OpenAI(
    base_url="https://router.huggingface.co/v1",
    api_key=os.getenv("HF_TOKEN"),
)

# Set stream=True to receive a stream of semantic events
stream = client.responses.create(
    model="openai/gpt-oss-120b:fireworks-ai",
    input="Tell me a short story about a robot who discovers music.",
    stream=True,
)

# Iterate over the events in the stream
for event in stream:
    print(event)

工具调用

您可以通过工具扩展模型以访问外部数据。以下示例定义了一个 `get_current_weather` 函数,模型可以选择调用它。

python
javascript
from openai import OpenAI
import os

client = OpenAI(
    base_url="https://router.huggingface.co/v1",
    api_key=os.getenv("HF_TOKEN"),
)

tools = [
    {
        "type": "function",
        "name": "get_current_weather",
        "description": "Get the current weather in a given location",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "The city and state, e.g. San Francisco, CA",
                },
                "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
            },
            "required": ["location", "unit"],
        },
    }
]

response = client.responses.create(
    model="openai/gpt-oss-120b:fireworks-ai", 
    tools=tools,
    input="What is the weather like in Boston today?",
    tool_choice="auto",
)

print(response)

远程 MCP 调用

API 最先进的功能是远程 MCP 调用,它允许模型将任务委托给外部服务。使用响应 API 调用远程 MCP 服务器非常简单。例如,您可以这样使用 DeepWiki MCP 服务器来询问几乎任何公共 GitHub 存储库的问题。

python
javascript
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://router.huggingface.co/v1",
    api_key=os.getenv("HF_TOKEN"),
)

response = client.responses.create(
    model="openai/gpt-oss-120b:fireworks-ai",
    input="What transport protocols are supported in the 2025-03-26 version of the MCP spec?",
    tools=[
        {
            "type": "mcp",
            "server_label": "deepwiki",
            "server_url": "https://mcp.deepwiki.com/mcp",
            "require_approval": "never",
        },
    ],
)

print(response)

推理工作量

您还可以使用 `reasoning` 参数控制模型的“思考”时间。以下示例提示模型对答案投入中等程度的精力。

python
javascript
from openai import OpenAI
import os

client = OpenAI(
    base_url="https://router.huggingface.co/v1",
    api_key=os.getenv("HF_TOKEN"),
)

response = client.responses.create(
    model="openai/gpt-oss-120b:fireworks-ai",
    instructions="You are a helpful assistant.",
    input="Say hello to the world.",
    reasoning={
        "effort": "low",
    },
)

for index, item in enumerate(response.output):
    print(f"Output #{index}: {item.type}", item.content)

就这样!通过推理提供商的响应 API,您可以对 GPT OSS 等强大的开放权重模型进行精细控制,包括流式传输、工具调用和远程 MCP,使其成为构建可靠、代理驱动型应用程序的理想选择。

< > 在 GitHub 上更新