推理提供商文档
使用推理提供商的结构化输出
并获得增强的文档体验
开始使用
使用推理提供商的结构化输出
在本指南中,我们将向您展示如何使用推理提供商生成符合特定 JSON 模式的结构化输出。这对于构建需要可预测、可解析响应的可靠 AI 应用程序非常有用。
结构化输出保证模型每次都返回与您的精确模式匹配的响应。这消除了对复杂解析逻辑的需求,并使您的应用程序更加健壮。
本指南假定您拥有 Hugging Face 帐户。如果您没有,可以免费在 huggingface.co 创建一个。
什么是结构化输出?
结构化输出确保模型响应始终遵循特定结构,通常是 JSON 模式。这意味着您将获得可预测的、类型安全的数据,可以轻松与您的系统集成。模型遵循严格的模板,因此您始终会以预期的格式获取数据。
传统上,从 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 模式,这是模型将接收的响应格式指令。这是模型将用于生成响应的模式。
{
"type": "object",
"properties": {
"title": {"type": "string"},
"abstract_summary": {"type": "string"}
},
"required": ["title", "abstract_summary"]
}
这个简单的模式确保我们始终能获取论文标题及其摘要的简洁摘要。请注意我们如何将这两个字段标记为必填项 - 这保证它们始终存在于响应中,从而使我们的应用程序更可靠。
步骤 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()
下一步
现在您已经了解了结构化输出,您可能想构建一个使用它们的应用程序。以下是一些您可以尝试的有趣想法:
- 不同模型:尝试不同的模型。最大的模型不总是最适合结构化输出!
- 多轮对话:在对话回合中保持结构化格式。
- 复杂模式:为您的用例构建特定领域的模式。
- 性能优化:为您的结构化输出需求选择合适的提供商。