Structured Output

Structured Output 是让 LLM 按照预定义的 JSON Schema 输出结构化数据的机制。它比 Output Parser 更可靠,因为模型被约束为只输出合法的 JSON。

#type / concept #status / evergreen #tech / ai

[!info] related notes

Structured Output

一句话定义

Structured Output 是让 LLM 按照预定义的 JSON Schema 输出结构化数据的机制。模型被约束为只输出符合 Schema 的 JSON,不需要后处理解析。

它解决什么问题

传统方式:LLM 输出自由文本 → Output Parser 尝试提取 JSON → 可能失败

Structured Output:LLM 直接输出合法 JSON → 100% 可靠解析

核心原理

OpenAI Structured Output

from pydantic import BaseModel

class CalendarEvent(BaseModel):
    name: str
    date: str
    participants: list[str]

response = await client.chat.completions.create(
    model="gpt-4",
    messages=[{"role": "user", "content": "提取事件信息: 明天下午3点和张三开会"}],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "calendar_event",
            "schema": CalendarEvent.model_json_schema(),
        },
    },
)

event = CalendarEvent.model_validate_json(response.choices[0].message.content)

Anthropic Tool Use for Structured Output

# Anthropic 没有 response_format,但可以用 tool_use 强制结构化输出
response = await client.messages.create(
    model="claude-sonnet-4-20250514",
    messages=[...],
    tools=[{
        "name": "output_result",
        "description": "输出结构化结果",
        "input_schema": CalendarEvent.model_json_schema(),
    }],
    tool_choice={"type": "tool", "name": "output_result"},
)

result = CalendarEvent(**response.content[0].input)

与 Output Parser 的对比

Structured OutputOutput Parser
可靠性100%(模型约束)~95%(后处理)
支持模型GPT-4, Claude (via tool_use)所有模型
延迟略高(约束解码)
灵活性受 Schema 限制完全自由

常见坑

  1. Schema 太复杂: 嵌套太深导致模型输出质量下降
  2. 不支持所有模型: 需要降级到 Output Parser
  3. 不做 Schema 验证: 输出了 JSON 但字段缺失

参考资料

创建于 2026/6/30 更新于 2026/7/15