结构化输出

结构化输出(Structured Outputs)让我们能够将模型的响应约束为特定格式——可以是有效的 JSON,也可以是我们的代码能够直接解析的严格 schema。

这消除了脆弱的字符串解析,使模型输出能够安全地用于数据管道、API 系统中。

有两种模式:

模式 它的作用
json_object 请求有效的 JSON——不强制执行 schema
json_schema 将输出约束为匹配我们的 schema 的有效 JSON

1. JSON 模式

传入 text={"format": {"type": "json_object"}},模型就会返回有效的 JSON。不需要 schema——当我们想要结构化输出但不需要严格的字段控制时很有用。

import os
from openai import OpenAI
from aws_bedrock_token_generator import provide_token
import json

region = "us-east-1"
os.environ["OPENAI_BASE_URL"] = f"https://bedrock-mantle.{region}.api.aws/openai/v1"
os.environ["OPENAI_API_KEY"] = provide_token(region=region)

client = OpenAI()

response = client.responses.create(
    model='openai.gpt-5.5',
    instructions="Always respond with valid JSON.",
    input="Give me the name, founded year, and headquarters of Amazon.",
    text={"format": {"type": "json_object"}}
)

data = json.loads(response.output_text)
print(json.dumps(data, indent=2))

现在执行该文件, 返回结果如下:

{
  "name": "Amazon",
  "founded_year": 1994,
  "headquarters": "Seattle, Washington, United States"
}

2. 使用 Pydantic 的结构化输出

Pydantic让LLM输出结构化数据而不是自由文本,并且自动帮你验证类型、解析成对象。是structured output/function calling的标准搭档。

更简洁的方法:将我们的 schema 定义为 Pydantic 模型并使用 responses.parse()。SDK 会验证响应并返回一个类型化的 Python 对象——无需 json.loads()

如果尚未安装 Pydantic,先安装它:

python3 -m pip install pydantic

将下面的代码复制到文件 structured_pydantic.py 中:

import os
from openai import OpenAI
from pydantic import BaseModel

client = OpenAI()

class SupportTicket(BaseModel):
    category: str
    severity: str
    summary: str

response = client.responses.parse(
    model=os.environ["MODEL_ID"]
    input="My EC2 instance is down and I can't SSH in."
    text_format=SupportTicket
)

ticket = response.output_parsed
print(f"Category: {ticket.category}")
print(f"Severity: {ticket.severity}")
print(f"Summary:  {ticket.summary}")

response.output_parsed 是一个 SupportTicket 实例——完全类型化,无需解析。输出如下:

Category: EC2 / Compute
Severity: High
Summary:  EC2 instance is down and the user is unable to connect via SSH.