Java 后端面试题库 / 全部题解免费阅读理解原理,有条理地回答

怎样用 response_format 得到 JSON 或符合 Schema 的输出?

查看完整题解

参考回答

直接回答

Chat 中支持的模型可用 response_format={"type":"json_object"} 请求 JSON 模式,并在指令中明确要求 JSON。要指定字段和类型,优先使用支持 Structured Outputs 的 json_schema。Responses 的对应入口是 text.format。

讲清原理

JSON 模式强调可解析 JSON,不确保每个字段满足业务规则。严格 Schema 也有支持范围,响应还可能被拒绝或因预算中断。因此客户端仍要先检查结果状态,再解析并校验数据。

例子与易错点

例如抽取工单级别时,要求一个包含 priority 的对象,并限制它为固定枚举。示例使用模拟响应核对 Chat 的实际 Schema 包装与本地结果解析。

import json
import httpx
from openai import OpenAI

model = "gpt-6.2-astra"
response_format = {
    "type": "json_schema",
    "json_schema": {"name": "ticket_priority", "strict": True, "schema": {
        "type": "object",
        "properties": {"priority": {"type": "string", "enum": ["high", "normal"]}},
        "required": ["priority"],
        "additionalProperties": False,
    }},
}

def classify(request):
    assert json.loads(request.content)["response_format"] == response_format
    return httpx.Response(200, json={
        "id": "chat-fixture", "object": "chat.completion", "created": 0,
        "model": model, "choices": [{"index": 0, "finish_reason": "stop",
            "message": {"role": "assistant", "content": '{"priority":"high"}'}}],
    })

with OpenAI(api_key="fixture", base_url="https://fixture.invalid/v1",
            http_client=httpx.Client(transport=httpx.MockTransport(classify))) as client:
    choice = client.chat.completions.create(
        model=model, response_format=response_format,
        messages=[{"role": "user", "content": "Classify this ticket: checkout is down"}],
    ).choices[0]
    assert choice.finish_reason == "stop" and not choice.message.refusal
    ticket = json.loads(choice.message.content)
    assert set(ticket) == {"priority"} and ticket["priority"] in {"high", "normal"}
    print(ticket["priority"])

相关题:第 7 题、第 11 题、第 13 题、第 24 题。

这道题,你掌握得怎么样?

掌握程度由你主动标记,阅读和收藏不会自动改变状态。