结构化输出

使用 JSON Schema 约束 AI 模型输出格式

概述

结构化输出功能允许您定义 JSON Schema,并通过 response_format 约束模型输出格式。但该能力只对后台已开启 supports_structured_output=1 的模型生效。

⚠️ 当前状态

根据当前数据库,active 模型中开启结构化输出能力的数量为 0。如果您现在直接传入 response_format,通常会收到 structured_output_not_supported 错误。

请求示例

Python
from openai import OpenAI
from pydantic import BaseModel, Field

client = OpenAI(
    base_url="https://api.lingyuncx.com/v1",
    api_key="sk-xxxxxxxx"
)

# 定义输出结构
class UserInfo(BaseModel):
    name: str = Field(description="用户姓名")
    age: int = Field(description="用户年龄")
    email: str = Field(description="用户邮箱")
    interests: list[str] = Field(description="兴趣爱好列表")

response = client.chat.completions.create(
    model="<请替换为后台已开启 structured output 的模型 ID>",
    messages=[
        {"role": "system", "content": "请从对话中提取用户信息。"},
        {"role": "user", "content": "你好,我叫张三,今年 28 岁,邮箱是 zhangsan@example.com,喜欢读书和旅游。"}
    ],
    response_format={"type": "json_schema", "json_schema": UserInfo.model_json_schema()}
)

print(response.choices[0].message.content)

返回示例

JSON
{
  "name": "张三",
  "age": 28,
  "email": "zhangsan@example.com",
  "interests": ["读书", "旅游"]
}

应用场景

  • 信息提取:从文本中提取结构化字段
  • 数据格式化:将非结构化内容转成标准 JSON
  • 接口编排:为下游系统生成稳定字段
  • 规则校验:在模型侧提前约束输出范围

💡 提示

使用前请先在后台确认目标模型已开启结构化输出能力;如果还未开启,可先按普通 JSON 文本输出处理。