推理提供商文件

使用推理提供商的結構化輸出

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

使用推理提供商的結構化輸出

在本指南中,我們將向您展示如何使用推理提供商生成符合特定 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 相容的端點工作)。

huggingface_hub
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 研究論文。模型將閱讀論文並根據我們預定義的模式提取關鍵資訊。

huggingface_hub
openai

以下是使用 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:處理響應

這兩種方法都保證您的響應將與指定的模式匹配。以下是訪問和使用結構化資料的方法:

huggingface_hub
openai

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."
}

現在您可以自信地處理這些資料,而無需擔心解析錯誤或欄位缺失。模式驗證可確保必需欄位始終存在且資料型別正確。

完整工作示例

這是一個完整的指令碼,您可以立即執行它來檢視結構化輸出的實際效果:

點選展開完整指令碼
huggingface_hub
openai
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()

下一步

現在您已經瞭解了結構化輸出,您可能想構建一個使用它們的應用程式。以下是一些您可以嘗試的有趣想法:

  • 不同模型:嘗試不同的模型。最大的模型不總是最適合結構化輸出!
  • 多輪對話:在對話回合中保持結構化格式。
  • 複雜模式:為您的用例構建特定領域的模式。
  • 效能最佳化:為您的結構化輸出需求選擇合適的提供商。
< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.