結構化輸出
結構化輸出讓模型按照你指定的 JSON 格式回傳資料,適用於資料提取、分類標註、表單填充等場景。
JSON Mode
最簡單的結構化輸出方式,強制模型回傳合法 JSON:
Python
json_mode.py
from openai import OpenAI
client = OpenAI(
base_url="https://api.ofox.ai/v1",
api_key="<你的 OFOXAI_API_KEY>"
)
response = client.chat.completions.create(
model="openai/gpt-4o",
messages=[
{"role": "system", "content": "你是一個資料提取助手。請以 JSON 格式回傳結果。"},
{"role": "user", "content": "提取以下文本中的人名、公司和職位:張三是阿里巴巴的高級工程師"}
],
response_format={"type": "json_object"}
)
import json
result = json.loads(response.choices[0].message.content)
print(result)
# {"name": "張三", "company": "阿里巴巴", "title": "高級工程師"}使用 JSON Mode 時,system prompt 中必須包含 “JSON” 關鍵詞,否則部分模型可能忽略格式要求。
JSON Schema 約束
更精確地控制輸出結構,確保欄位名稱和類型符合預期:
json_schema.py
response = client.chat.completions.create(
model="openai/gpt-4o",
messages=[
{"role": "user", "content": "分析這段使用者評論的情感:這個產品太棒了,非常好用!"}
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "sentiment_analysis",
"schema": {
"type": "object",
"properties": {
"sentiment": {
"type": "string",
"enum": ["positive", "negative", "neutral"],
"description": "情感傾向"
},
"confidence": {
"type": "number",
"description": "置信度 0-1"
},
"keywords": {
"type": "array",
"items": {"type": "string"},
"description": "關鍵情感詞"
}
},
"required": ["sentiment", "confidence", "keywords"],
"additionalProperties": False
}
}
}
)輸出:
{
"sentiment": "positive",
"confidence": 0.95,
"keywords": ["太棒了", "非常好用"]
}實際應用場景
資料提取
# 從非結構化文本提取結構化資料
response = client.chat.completions.create(
model="openai/gpt-4o",
messages=[{
"role": "user",
"content": """提取以下訂單資訊:
客戶李四於2025年1月15日下單購買了3台MacBook Pro,
單價18999元,收貨位址是北京市朝陽區xxx路123號"""
}],
response_format={
"type": "json_schema",
"json_schema": {
"name": "order_info",
"schema": {
"type": "object",
"properties": {
"customer": {"type": "string"},
"date": {"type": "string"},
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {"type": "string"},
"quantity": {"type": "integer"},
"unit_price": {"type": "number"}
}
}
},
"address": {"type": "string"}
},
"required": ["customer", "date", "items", "address"]
}
}
}
)分類標註
# 多標籤分類
response = client.chat.completions.create(
model="openai/gpt-4o",
messages=[{
"role": "user",
"content": "分類這篇文章的主題:AI 技術在醫療領域的應用越來越廣泛..."
}],
response_format={
"type": "json_schema",
"json_schema": {
"name": "classification",
"schema": {
"type": "object",
"properties": {
"primary_category": {"type": "string"},
"secondary_categories": {
"type": "array",
"items": {"type": "string"}
},
"tags": {
"type": "array",
"items": {"type": "string"}
}
},
"required": ["primary_category"]
}
}
}
)支援的模型
| 模型 | JSON Mode | JSON Schema |
|---|---|---|
openai/gpt-4o | ✅ | ✅ |
openai/gpt-4o-mini | ✅ | ✅ |
anthropic/claude-sonnet-4.5 | ✅ | — |
google/gemini-3-flash-preview | ✅ | ✅ |
不支援 JSON Schema 的模型可以透過在 system prompt 中詳細描述期望的 JSON 格式來實作類似效果。
Last updated on