你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

了解如何使用 JSON 模式

JSON 模式允许你设置模型响应格式以返回有效的 JSON 对象作为聊天补全的一部分。 虽然以前可以生成有效的 JSON,但响应一致性可能存在问题,从而导致生成无效的 JSON 对象。

JSON 模式支持

目前仅支持以下模型的 JSON 模式:

支持的模型

  • gpt-35-turbo (1106)
  • gpt-35-turbo (0125)
  • gpt-4 (1106-Preview)
  • gpt-4 (0125-Preview)

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="2024-03-01-preview"
)

response = client.chat.completions.create(
  model="gpt-4-0125-Preview", # Model = should match the deployment name you chose for your 0125-Preview 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 模式,需要满足两个关键因素:

  • 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,并且分析时不会出现错误。 但是,即使在提示中提出请求,也不能保证输出与特定架构匹配。