跳轉到主要內容
兩條路徑:
  • response_format: {"type": "json_object"} —— 模型返回合法 JSON
  • response_format: {"type": "json_schema", "json_schema": {...}} —— 模型 輸出符合你的 schema

示例(json_schema,OpenAI)

resp = client.chat.completions.create(
    model="openai/gpt-4o-mini",
    messages=[{"role": "user", "content": "Extract name and age."}],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "person",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "age": {"type": "integer"},
                },
                "required": ["name", "age"],
            },
        },
    },
)

跨服務商支持

只要上游模型能夠處理 response_format,它就被支持。對于 Gemini, OrcaRouter 的翻譯層會把它映射為 responseMimeType + responseSchema。 對于 OpenAI / Grok / DeepSeek(這些都是 OpenAI 兼容上游),該字段以 原生形態抵達上游。Anthropic 沒有 response_format 的等價物, 所以在那邊需要 schema 約束輸出時請使用 Anthropic 的 tool_use 模式。
服務商json_objectjson_schema備注
OpenAI??OpenAI 原生字段形態
Grok(xAI)??xAI 是 OpenAI 兼容
DeepSeek???請核對 DeepSeek 各模型的支持情況
Gemini??翻譯為 responseMimeType + responseSchema
Anthropic??請改用 tool_use 模式

另見