结构化输出
结构化输出(Structured Output)让模型按照你指定的 JSON Schema 格式返回数据,确保输出结果可被程序直接解析,无需手动提取或正则匹配。
适用场景
- 从非结构化文本中提取结构化信息(如从文章中提取人名、日期、地点)
- 让模型返回固定格式的数据供后端系统消费
- 构建需要可靠 JSON 输出的工作流和 Agent
两种模式
JSON Mode
设置 response_format: { type: "json_object" },模型会返回合法的 JSON,但不保证符合特定 Schema。你需要在提示词中描述期望的 JSON 结构。
JSON Schema Mode
设置 response_format: { type: "json_schema", json_schema: {...} },模型会严格按照你提供的 JSON Schema 返回数据。这是更推荐的方式。
JSON Mode 示例
Python
from openai import OpenAI
client = OpenAI(
api_key="<ACCELE_AI_API_KEY>",
base_url="https://api.acceleai.cn/v1"
)
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个信息提取助手,请以 JSON 格式返回结果。"},
{"role": "user", "content": "北京时间2026年4月3日,张三在上海签署了一份价值500万的合同。"}
],
response_format={"type": "json_object"}
)
print(response.choices[0].message.content)
# {"person": "张三", "location": "上海", "date": "2026-04-03", "amount": 5000000, "event": "签署合同"}cURL
curl https://api.acceleai.cn/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <ACCELE_AI_API_KEY>" \
-d '{
"model": "gpt-4o",
"messages": [
{"role": "system", "content": "你是一个信息提取助手,请以 JSON 格式返回结果。"},
{"role": "user", "content": "北京时间2026年4月3日,张三在上海签署了一份价值500万的合同。"}
],
"response_format": {"type": "json_object"}
}'JSON Schema Mode 示例
通过提供完整的 JSON Schema,模型会严格遵循你定义的字段名、类型和结构。
Python
from openai import OpenAI
client = OpenAI(
api_key="<ACCELE_AI_API_KEY>",
base_url="https://api.acceleai.cn/v1"
)
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "user", "content": "给我推荐3本关于人工智能的书籍。"}
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "book_recommendations",
"strict": True,
"schema": {
"type": "object",
"properties": {
"books": {
"type": "array",
"items": {
"type": "object",
"properties": {
"title": {"type": "string"},
"author": {"type": "string"},
"year": {"type": "integer"},
"reason": {"type": "string"}
},
"required": ["title", "author", "year", "reason"],
"additionalProperties": False
}
}
},
"required": ["books"],
"additionalProperties": False
}
}
}
)
print(response.choices[0].message.content)使用 Pydantic(推荐)
OpenAI Python SDK 支持直接传入 Pydantic 模型,自动生成 JSON Schema:
from openai import OpenAI
from pydantic import BaseModel
client = OpenAI(
api_key="<ACCELE_AI_API_KEY>",
base_url="https://api.acceleai.cn/v1"
)
class Book(BaseModel):
title: str
author: str
year: int
reason: str
class BookList(BaseModel):
books: list[Book]
response = client.beta.chat.completions.parse(
model="gpt-4o",
messages=[
{"role": "user", "content": "给我推荐3本关于人工智能的书籍。"}
],
response_format=BookList
)
books = response.choices[0].message.parsed
for book in books.books:
print(f"《{book.title}》- {book.author} ({book.year})")
print(f" 推荐理由:{book.reason}")JavaScript 示例
import OpenAI from "openai";
import { z } from "zod";
import { zodResponseFormat } from "openai/helpers/zod";
const client = new OpenAI({
apiKey: "<ACCELE_AI_API_KEY>",
baseURL: "https://api.acceleai.cn/v1"
});
const BookSchema = z.object({
books: z.array(z.object({
title: z.string(),
author: z.string(),
year: z.number(),
reason: z.string()
}))
});
const response = await client.beta.chat.completions.parse({
model: "gpt-4o",
messages: [
{ role: "user", content: "给我推荐3本关于人工智能的书籍。" }
],
response_format: zodResponseFormat(BookSchema, "book_recommendations")
});
console.log(response.choices[0].message.parsed);支持的模型
结构化输出功能的支持程度因模型而异:
| 模型 | JSON Mode | JSON Schema Mode |
|---|---|---|
| GPT-4o / GPT-4o-mini | ✅ | ✅ |
| GPT-5 | ✅ | ✅ |
| Claude Sonnet 4 / Opus 4 | ✅ | ✅ |
| Gemini 2.5 Pro / Flash | ✅ | ✅ |
| DeepSeek V3 | ✅ | ✅ |
[!TIP] 如果模型不支持 JSON Schema Mode,可以退回使用 JSON Mode,并在系统提示词中明确描述期望的 JSON 结构。
注意事项
strict: true时,Schema 中的所有字段都必须设置required,且需要additionalProperties: false- 结构化输出可能会略微增加输出 Token 消耗(模型需要严格遵循格式)
- 流式输出同样支持结构化输出,SDK 会在流结束后自动拼装并解析完整 JSON