JSON 模式允许你设置模型响应格式以返回有效的 JSON 对象作为聊天补全的一部分。 虽然以前可以生成有效的 JSON,但响应一致性可能存在问题,从而导致生成无效的 JSON 对象。
注意
尽管仍支持 JSON 模式,但建议尽可能使用结构化输出。 与 JSON 模式一样,结构化输出会生成有效的 JSON,但有一项附加优势,即你可以约束模型使用特定的 JSON 架构。
JSON 模式支持
目前仅支持以下模型的 JSON 模式:
支持的模型
gpt-35-turbo
(1106)
gpt-35-turbo
(0125)
gpt-4
(1106-Preview)
gpt-4
(0125-Preview)
gpt-4o
gpt-4o-mini
API 支持
对 JSON 模式的支持最初在 API 版本 2023-12-01-preview
中添加
示例
import os
from openai import AzureOpenAI
client = AzureOpenAI(
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
api_version="2025-03-01-preview"
)
response = client.chat.completions.create(
model="YOUR-MODEL_DEPLOYMENT_NAME", # Model = should match the deployment name you chose for your model deployment
response_format={ "type": "json_object" },
messages=[
{"role": "system", "content": "You are a helpful assistant designed to output JSON."},
{"role": "user", "content": "Who won the world series in 2020?"}
]
)
print(response.choices[0].message.content)
输出
{
"winner": "Los Angeles Dodgers",
"event": "World Series",
"year": 2020
}
在此示例中,用户请求特定 JSON 模式中的历史信息,因为用户计划使用输出进行进一步的脚本编写。
$openai = @{
api_key = $Env:AZURE_OPENAI_API_KEY
api_base = $Env:AZURE_OPENAI_ENDPOINT # like the following https://YOUR_RESOURCE_NAME.openai.azure.com/
api_version = '2024-03-01-preview' # may change in the future
name = 'YOUR-DEPLOYMENT-NAME-HERE' # name you chose for your deployment
}
$headers = @{
'api-key' = $openai.api_key
}
$messages = @()
$messages += @{
role = 'system'
content = 'You are a helpful assistant designed to output JSON.'
}
$messages += @{
role = 'user'
content = 'Who threw the final pitch during the world series each year from 1979 to 1989?'
}
$messages += @{
role = 'user'
content = 'Respond using schema. response:{year, team, player, player_height}.'
}
$body = @{
response_format = @{type = 'json_object'}
messages = $messages
} | ConvertTo-Json
$url = "$($openai.api_base)/openai/deployments/$($openai.name)/chat/completions?api-version=$($openai.api_version)"
$response = Invoke-RestMethod -Uri $url -Headers $headers -Body $body -Method Post -ContentType 'application/json'
$response.choices[0].message.content
输出
JSON 输出功能使 PowerShell 可以轻松地将响应转换为 .NET 对象。
通过 |
管道传递数据以运行更多脚本步骤,例如排序。
if ($response.choices[0].finish_reason -eq 'stop') {
$response.choices[0].message.content | ConvertFrom-Json | ForEach-Object response | Sort player_height -Descending
} else { write-warning 'the JSON response was incomplete'}
year team player player_height
---- ---- ------ -------------
1979 Pittsburgh Pirates Kent Tekulve 6' 4"
1984 Detroit Tigers Willie Hernandez 6' 3"
1988 Los Angeles Dodgers Orel Hershiser 6' 3"
1982 St. Louis Cardinals Bruce Sutter 6' 2"
1985 Kansas City Royals Dan Quisenberry 6' 2"
1986 New York Mets Jesse Orosco 6' 2"
1989 Oakland Athletics Dennis Eckersley 6' 2"
1981 Los Angeles Dodgers Steve Howe 6' 1"
1980 Philadelphia Phillies Tug McGraw 6' 0"
1987 Minnesota Twins Jeff Reardon 6' 0"
1983 Baltimore Orioles Tippy Martinez 5' 10"
若要成功使用 JSON 模式,需要满足两个关键因素:
response_format={ "type": "json_object" }
- 我们已经告诉模型输出 JSON 作为系统消息的一部分。
需要包括以下模型指导:模型应生成 JSON 作为消息对话的一部分。 建议将指令添加为系统消息的一部分。 根据 OpenAI 的说法,如果添加此指令失败,可能会导致模型“生成无休止的空白流,而请求可能会持续运行,直到达到令牌限制为止。”
如果未能在消息中包含“JSON”,则会返回以下内容:
输出
BadRequestError: Error code: 400 - {'error': {'message': "'messages' must contain the word 'json' in some form, to use 'response_format' of type 'json_object'.", 'type': 'invalid_request_error', 'param': 'messages', 'code': None}}
其他注意事项
在分析响应之前,应检查 finish_reason
中是否存在值 length
。 模型可能会生成部分 JSON。 这意味着模型的输出大于已作为请求的一部分设置的可用 max_tokens,或者对话本身超出了令牌限制。
JSON 模式会生成有效的 JSON,并且分析时不会出现错误。 但是,即使在提示中提出请求,也不能保证输出与特定架构匹配。