切换语言

结构化输出

强制模型输出符合 JSON Schema,便于可靠解析。

结构化输出确保模型生成结果符合你提供的 JSON Schema,适合需要程序化解析输出的应用。

两种方式

模式response_format.type说明
JSON Schema(推荐)json_schema严格按 schema 生成
JSON Object(旧版)json_object保证合法 JSON,但不校验结构

示例:抽取结构化数据

from openai import OpenAI
import json

client = OpenAI(
    base_url="https://api-inference.bitdeer.ai/v1",
    api_key="YOUR_API_KEY",
)

response = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V4-Pro",
    messages=[
        {
            "role": "system",
            "content": "You are a data extraction assistant. Extract expense information from the user's input.",
        },
        {
            "role": "user",
            "content": "I spent $120 on dinner last Friday and bought office supplies for $45 on Monday.",
        },
    ],
    max_tokens=1024,
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "expense_report",
            "schema": {
                "type": "object",
                "properties": {
                    "expenses": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "description": {"type": "string"},
                                "amount": {"type": "number"},
                                "date": {"type": "string"},
                                "category": {"type": "string"},
                            },
                            "required": ["description", "amount"],
                        },
                    },
                    "total": {"type": "number"},
                },
                "required": ["expenses", "total"],
            },
            "strict": True,
        },
    },
)

result = json.loads(response.choices[0].message.content)
print(json.dumps(result, indent=2))

预期输出

{
  "expenses": [
    {"description": "Dinner", "amount": 120, "date": "last Friday", "category": "Food"},
    {"description": "Office supplies", "amount": 45, "date": "Monday", "category": "Office"}
  ],
  "total": 165
}

Schema 要求

strict: true 时:

  • 支持的类型:stringnumberintegerbooleanarrayobjectenumanyOf
  • 对象的所有属性必须显式列出
  • 不支持的 schema 会返回错误

JSON Object 模式(更简单)

response = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V4-Pro",
    messages=[{"role": "user", "content": "List 3 colors as JSON."}],
    max_tokens=256,
    response_format={"type": "json_object"},
)

可保证输出为合法 JSON,但不强制具体结构。

最后更新于

本页目录

结构化输出 · Bitdeer AI