UniterRouter
API 参考OpenAI 兼容

结构化输出

OpenAI JSON Mode API - GPT-4、GPT-4o 生成经过验证的 JSON。基于 Schema 的结构化输出,可靠数据提取和类型安全的 AI 响应。

结构化输出

使用 response_format 生成可靠的 JSON 输出,支持 schema 验证。

支持的模型: GPT-4o, GPT-4 Turbo, GPT-3.5 Turbo, Claude 3.5, Gemini 2.0/1.5 等现代 LLM。

JSON 模式

强制模型输出有效的 JSON:

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "列出 3 种颜色,以 JSON 格式"}],
    response_format={"type": "json_object"}
)

重要: 使用 JSON 模式时,请在提示中提及 "JSON"。

JSON Schema 模式

强制执行特定的 schema(GPT-4o 及兼容模型):

from openai import OpenAI

client = OpenAI(
    base_url="https://api.uniterouter.ai/v1",
    api_key="your_api_key",
)

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "提取产品信息"},
        {"role": "user", "content": "iPhone 15 Pro 售价 $999"}
    ],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "product",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "price": {"type": "number"},
                    "currency": {"type": "string"}
                },
                "required": ["name", "price", "currency"],
                "additionalProperties": False
            }
        }
    }
)

输出:

{"name": "iPhone 15 Pro", "price": 999, "currency": "USD"}

示例请求

from openai import OpenAI
import json

client = OpenAI(
    base_url="https://api.uniterouter.ai/v1",
    api_key="your_api_key",
)

# 简单 JSON 模式
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "只输出 JSON"},
        {"role": "user", "content": "提取:小明今年 30 岁"}
    ],
    response_format={"type": "json_object"}
)

data = json.loads(response.choices[0].message.content)
print(data)  # {"name": "小明", "age": 30}
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.uniterouter.ai/v1",
  apiKey: process.env.UNITEROUTER_API_KEY,
});

const response = await client.chat.completions.create({
  model: "gpt-4o",
  messages: [
    { role: "system", content: "只输出 JSON" },
    { role: "user", content: "提取:小明今年 30 岁" },
  ],
  response_format: { type: "json_object" },
});

const data = JSON.parse(response.choices[0].message.content!);
console.log(data); // { name: "小明", age: 30 }
curl https://api.uniterouter.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $UNITEROUTER_API_KEY" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {"role": "system", "content": "只输出 JSON"},
      {"role": "user", "content": "提取:小明今年 30 岁"}
    ],
    "response_format": {"type": "json_object"}
  }'

Pydantic 集成

使用 Pydantic 进行类型安全的解析:

from pydantic import BaseModel
from openai import OpenAI

class Person(BaseModel):
    name: str
    age: int
    email: str | None = None

client = OpenAI(
    base_url="https://api.uniterouter.ai/v1",
    api_key="your_api_key",
)

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": f"提取人员信息为 JSON: {Person.model_json_schema()}"},
        {"role": "user", "content": "张三,30岁,[email protected]"}
    ],
    response_format={"type": "json_object"}
)

person = Person.model_validate_json(response.choices[0].message.content)
print(person.name)  # 张三

响应格式选项

类型描述使用场景
text纯文本(默认)通用响应
json_object有效的 JSON结构化数据
json_schemaSchema 验证的 JSON严格类型

Schema 最佳实践

{
  "type": "json_schema",
  "json_schema": {
    "name": "response_schema",
    "strict": true,
    "schema": {
      "type": "object",
      "properties": {
        "status": {
          "type": "string",
          "enum": ["success", "error"]
        },
        "data": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "id": {"type": "integer"},
              "name": {"type": "string"}
            },
            "required": ["id", "name"]
          }
        }
      },
      "required": ["status", "data"],
      "additionalProperties": false
    }
  }
}

使用场景

场景示例
数据提取从文本中提取实体
API 响应生成结构化 API 响应
表单解析将表单数据解析为对象
分类使用结构化标签分类
翻译输出带元数据的翻译

限制

  • json_schema 配合 strict: true 需要 GPT-4o 或兼容模型
  • 部分模型仅支持 json_object(基本 JSON 模式)
  • 复杂的嵌套 schema 可能需要提示工程

相关文档

How is this guide?