Structured Outputs
Structured Outputs 把已完成、非拒绝的模型输出约束到你提供的 JSON Schema。
定义 · 一图看懂 · 工作原理
定义
Structured Outputs 将已完成、非拒绝的模型输出约束到你提供的 JSON Schema。Structured Outputs 是 JSON mode 的演进。文档把遵循 schema 列为好处之一:必填字段和枚举值遵循你提供的受支持 JSON Schema。
文档还把明确的拒绝列为好处:基于安全的模型拒绝现在可以通过程序检测到。Structured Outputs 支持 JSON Schema 语言的一个子集。Structured Outputs 可用于最新的大语言模型,从 GPT-4o 开始。
一图看懂
JSON mode 和 Structured Outputs 都能确保生成有效的 JSON,但 JSON mode 有一些边缘情况需要你检测并妥善处理,而且只有 Structured Outputs 能确保遵循 schema。
- Structured Outputs:已完成、非拒绝的模型输出被约束到所提供的 JSON Schema。
- JSON mode:输出被确保为有效 JSON,但有些边缘情况需要你检测并妥善处理;它不保证输出匹配任何特定 schema,只保证有效且能无错解析。
- 拒绝:拒绝不一定遵循你在
response_format中提供的 schema,因此 API 响应会包含名为refusal的新字段,表明模型拒绝了请求。 - 不完整的响应:模型可能无法生成与所提供 JSON schema 匹配的有效响应,例如达到 max tokens 上限且响应不完整时。
原文没有明确这些要点的先后顺序,因此按要点列出,不画先后箭头。
工作原理
Structured Outputs 在 OpenAI API 中有两种形式。当你构建的应用需要连接模型与应用自身的功能时,函数调用很有用。相比之下,通过 response_format 使用 Structured Outputs 更适合在模型回复用户时指定结构化 schema,而不是模型调用工具时。
由于 Structured Outputs 只支持生成指定的键和值,开发者必须将 additionalProperties 设为 false,才能选用 Structured Outputs。尽管所有字段都必须是必填的,且模型会为每个参数返回值,仍可以通过与 null 的联合类型来模拟可选参数。如果通过提供 strict 为 true 来开启 Structured Outputs,并用不受支持的 JSON Schema 调用 API,你会收到错误。
schema 的根级对象必须是对象,并且不能使用 anyOf。一个 schema 最多可有 5000 个对象属性,嵌套层级最多 10 层。在受支持的 GPT-6 及更新模型的标准单智能体模式下,可以在响应之间切换 schema:在下一条用户消息之前向 input 追加一个 configuration_update 项。
每个请求都保留原始的顶层 text.format,这样较早的提示前缀才仍有资格使用提示缓存。文档设想上一轮用纯文本描述了一批货物,有 17 个红色箱子和 26 个蓝色箱子。预期的答案是 total_crates 为 43。
响应对象的 text.format 仍然报告原始的请求级格式。在检查拒绝和不完整响应之后,用最新格式更新中的 schema 解析答案。每次格式更新都会替换整个格式。
例子
文档给出的一个用法是让模型以结构化、分步骤的方式输出答案,引导用户完成解答。除了 REST API 对 JSON Schema 的支持,OpenAI 的 Python 和 JavaScript 库还允许分别用 pydantic.BaseModel 和 z.object 定义对象 schema。第一步是定义一个对象或数据结构,用来表示模型应被约束遵循的 JSON Schema。
可以用 parse 方法把 JSON 响应自动解析为你定义的对象。在底层,SDK 负责提供与你的数据结构对应的 JSON schema,再把响应解析为对象。有时模型可能无法生成与所提供 JSON schema 匹配的有效响应。
这可能发生在拒绝的情形,即模型出于安全原因拒绝回答,或例如达到 max tokens 上限而响应不完整时。当 refusal 属性出现在输出对象中时,你可以在界面中展示这次拒绝,或在处理响应的代码中加入条件逻辑来处理被拒绝的请求。应用仍然需要处理拒绝、不完整的响应和 API 错误,并校验 schema 未表达的业务规则。
from pydantic import BaseModel
from openai import OpenAI
client = OpenAI()
class Step(BaseModel):
explanation: str
output: str
class MathReasoning(BaseModel):
steps: list[Step]
final_answer: str
completion = client.chat.completions.parse(
model="gpt-6.2-astra",
messages=[
{
"role": "system",
"content": "You are a helpful math tutor. Guide the user through the solution step by step.",
},
{"role": "user", "content": "how can I solve 8x + 7 = -23"},
],
response_format=MathReasoning,
)
math_reasoning = completion.choices[0].message.parsed{
"steps": [
{
"explanation": "Start with the equation 8x + 7 = -23.",
"output": "8x + 7 = -23"
},
{
"explanation": "Subtract 7 from both sides to isolate the term with the variable.",
"output": "8x = -23 - 7"
},
{
"explanation": "Simplify the right side of the equation.",
"output": "8x = -30"
},
{
"explanation": "Divide both sides by 8 to solve for x.",
"output": "x = -30 / 8"
},
{
"explanation": "Simplify the fraction.",
"output": "x = -15 / 4"
}
],
"final_answer": "x = -15 / 4"
}try:
response = client.chat.completions.create(
model="gpt-6.2-astra",
messages=[
{
"role": "system",
"content": "You are a helpful math tutor. Guide the user through the solution step by step.",
},
{"role": "user", "content": "how can I solve 8x + 7 = -23"},
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "math_response",
"strict": True,
"schema": {
"type": "object",
"properties": {
"steps": {
"type": "array",
"items": {
"type": "object",
"properties": {
"explanation": {"type": "string"},
"output": {"type": "string"},
},
"required": ["explanation", "output"],
"additionalProperties": False,
},
},
"final_answer": {"type": "string"},
},
"required": ["steps", "final_answer"],
"additionalProperties": False,
},
},
},
max_completion_tokens=1024,
)
if response.choices[0].finish_reason == "length":
raise Exception("Incomplete response")
math_response = response.choices[0].message
if math_response.refusal:
print(math_response.refusal)
elif math_response.content:
print(math_response.content)
else:
raise Exception("No response content")
except Exception as e:
# handle errors like finish_reason, refusal, content_filter, etc.
print(e)来源
本页内容整理自以下官方来源,点击可核对原文。
核验日期 ·
本页由 AI 依据上述官方来源整理,并经自动核对,未经本站实测。 发现错误?告诉我们。