推理提供商文档
使用推理提供商实现结构化输出
并获得增强的文档体验
开始使用
使用推理提供商实现结构化输出
在本指南中,我们将向您展示如何使用推理提供商(Inference Providers)来生成遵循特定 JSON 模式(Schema)的结构化输出。这对于构建需要可预测、可解析响应的可靠 AI 应用程序非常有用。
结构化输出保证模型每次返回的响应都与您的精确模式相匹配。这消除了对复杂解析逻辑的需求,并使您的应用程序更加健壮。
本指南假定您拥有 Hugging Face 帐户。如果您没有,可以免费在 huggingface.co 上创建。
什么是结构化输出?
结构化输出确保模型响应始终遵循特定的结构,通常是 JSON Schema。这意味着您可以获得可预测、类型安全的数据,能够轻松地与您的系统集成。模型遵循严格的模板,因此您始终能以预期的格式获取数据。
传统上,从大语言模型(LLM)获取结构化数据需要提示词工程(要求模型“以 JSON 格式响应”)、对响应进行后处理和解析,有时在解析失败时还需要重试。这种方法不可靠,会导致应用程序变得脆弱。
通过结构化输出,您可以获得:
- 保证符合您定义的模式
- 减少由格式错误或无法解析的 JSON 导致的错误
- 更轻松地与下游系统集成
- 无需重试逻辑或复杂的错误处理
- 更高效地利用 Token(减少冗长的指令)
简而言之,结构化输出通过确保每个响应都匹配您的模式,并提供内置的验证和类型安全,使您的应用程序更加健壮和可靠。
步骤 1:定义您的模式
在进行任何 API 调用之前,您需要定义所需的结构。让我们构建一个实际的例子:从研究论文中提取结构化信息。这是一个常见的真实用例,您需要解析学术论文并提取标题、作者、贡献和方法论等关键细节。
我们将创建一个简单的模式来捕捉最核心的元素:论文标题及其摘要的总结。最简单的方法是使用 Pydantic,这是一个允许您定义代表 JSON 模式(以及其他内容)的 Python 类的库。
from pydantic import BaseModel
class PaperAnalysis(BaseModel):
title: str
abstract_summary: str使用 model_json_schema,我们可以将 Pydantic 模型转换为 JSON Schema,这正是模型将接收到的响应格式指令。模型将使用此模式来生成响应。
{
"type": "object",
"properties": {
"title": {"type": "string"},
"abstract_summary": {"type": "string"}
},
"required": ["title", "abstract_summary"]
}这个简单的模式确保我们始终能获得论文标题和简洁的摘要总结。请注意,我们将两个字段都标记为必填(required)——这保证了它们在响应中始终存在,从而提高应用程序的可靠性。
步骤 2:设置您的推理客户端
现在我们已经定义好了模式,让我们设置用于与推理提供商通信的客户端。我们将向您展示两种方法:Hugging Face Hub 客户端(可直接访问所有推理提供商)和 OpenAI 客户端(通过兼容 OpenAI 的端点工作)。
安装 Hugging Face Hub Python 包
pip install huggingface_hub
使用推理提供商(请查看此列表以获取所有可用提供商)和您的 Hugging Face Token 来初始化 InferenceClient。
import os
from huggingface_hub import InferenceClient
# Initialize the client
client = InferenceClient(
provider="cerebras", # or use "auto" for automatic selection
api_key=os.environ["HF_TOKEN"],
)
结构化输出是选择特定提供商和模型的理想用例,因为您希望避免模型、提供商和模式之间出现不兼容的问题。
步骤 3:生成结构化输出
现在让我们从研究论文中提取结构化信息。我们将把论文内容以及我们的模式发送给模型,并获得结构完美的数据。
在这个例子中,我们将分析一篇著名的 AI 研究论文。模型将阅读论文并根据我们预定义的模式提取关键信息。
以下是如何使用 Hugging Face Hub 客户端生成结构化输出的方法
from pydantic import BaseModel
# Example paper text (truncated for brevity)
paper_text = """
Title: Attention Is All You Need
Abstract: The dominant sequence transduction models are based on complex recurrent
or convolutional neural networks that include an encoder and a decoder. The best
performing models also connect the encoder and decoder through an attention mechanism.
We propose a new simple network architecture, the Transformer, based solely on
attention mechanisms, dispensing with recurrence and convolutions entirely...
"""
# Define the response format
class PaperAnalysis(BaseModel):
title: str
abstract_summary: str
# Convert the Pydantic model to a JSON Schema and wrap it in a dictionary
response_format = {
"type": "json_schema",
"json_schema": {
"name": "PaperAnalysis",
"schema": PaperAnalysis.model_json_schema(),
"strict": True,
},
}
# Define your messages with a system prompt and a user prompt
# The system prompt is a description of the task you want the model to perform
# The user prompt is the input data you want to process
messages = [
{
"role": "system",
"content": "Extract paper title and abstract summary."
},
{
"role": "user",
"content": paper_text
}
]
# Generate structured output using Qwen/Qwen3-32B model
response = client.chat_completion(
messages=messages,
response_format=response_format,
model="Qwen/Qwen3-32B",
)
# The response is guaranteed to match your schema
structured_data = response.choices[0].message.content
print(structured_data)步骤 4:处理响应
两种方法都保证您的响应将与指定的模式相匹配。以下是如何访问和使用这些结构化数据的方法
Hugging Face Hub 客户端返回一个 ChatCompletion 对象,其中包含模型返回的字符串响应。使用 json.loads 函数解析响应以获取结构化数据。
# The response is guaranteed to match your schema
structured_data = response.choices[0].message.content
print("Paper Analysis Results:")
print(structured_data)
# Parse the JSON to work with individual fields
import json
analysis = json.loads(structured_data)
print(f"Title: {analysis['title']}")
print(f"Abstract Summary: {analysis['abstract_summary']}")结构化输出可能如下所示
{
"title": "Attention Is All You Need",
"abstract_summary": "Introduces the Transformer architecture based solely on attention mechanisms, eliminating recurrence and convolutions for sequence transduction tasks. Shows superior quality in machine translation while being more parallelizable and requiring less training time."
}您现在可以自信地处理这些数据,而无需担心解析错误或字段缺失。模式验证确保了必填字段始终存在且数据类型正确。
完整可运行示例
这是一个完整的脚本,您可以立即运行它来查看结构化输出的实际效果
点击展开完整脚本
import os
import json
from huggingface_hub import InferenceClient
from pydantic import BaseModel
from typing import List
# Set your Hugging Face token
# export HF_TOKEN="your_token_here"
def analyze_paper_structured():
"""Complete example of structured output for research paper analysis."""
# Initialize the client
client = InferenceClient(
provider="cerebras", # or use "auto" for automatic selection
api_key=os.environ["HF_TOKEN"],
)
# Example paper text (you can replace this with any research paper)
paper_text = """
Title: Attention Is All You Need
Abstract: The dominant sequence transduction models are based on complex recurrent
or convolutional neural networks that include an encoder and a decoder. The best
performing models also connect the encoder and decoder through an attention mechanism.
We propose a new simple network architecture, the Transformer, based solely on
attention mechanisms, dispensing with recurrence and convolutions entirely.
Experiments on two machine translation tasks show these models to be superior
in quality while being more parallelizable and requiring significantly less time to train.
Introduction: Recurrent neural networks, long short-term memory and gated recurrent
neural networks in particular, have been firmly established as state of the art approaches
in sequence modeling and transduction problems such as language modeling and machine translation.
"""
# Define the response format (JSON Schema)
class PaperAnalysis(BaseModel):
title: str
abstract_summary: str
response_format = {
"type": "json_schema",
"json_schema": {
"name": "PaperAnalysis",
"schema": PaperAnalysis.model_json_schema(),
"strict": True,
},
}
# Define your messages
messages = [
{
"role": "system",
"content": "Extract paper title and abstract summary."
},
{
"role": "user",
"content": paper_text
}
]
# Generate structured output
response = client.chat_completion(
messages=messages,
response_format=response_format,
model="Qwen/Qwen3-32B",
)
# The response is guaranteed to match your schema
structured_data = response.choices[0].message.content
# Parse and display results
analysis = json.loads(structured_data)
print(f"Title: {analysis['title']}")
print(f"Abstract Summary: {analysis['abstract_summary']}")
if __name__ == "__main__":
# Make sure you have set your HF_TOKEN environment variable
analyze_paper_structured()后续步骤
既然您已经了解了结构化输出,您可能想构建一个使用它们的应用程序。这里有一些您可以尝试的有趣想法
- 尝试不同模型:实验不同的模型。最大的模型并不总是最适合结构化输出的!
- 多轮对话:在对话轮次之间维持结构化格式。
- 复杂 Schema:为您具体的使用场景构建领域特定的 Schema。
- 性能优化:为您的结构化输出需求选择合适的供应商。