共用方式為


學習如何使用 JSON 模式

JSON 模式可讓您設定模型回應格式,在聊天完成時傳回有效的 JSON 物件。 雖然先前可產生有效的 JSON,但回應一致性可能有問題,導致產生的 JSON 對象無效。

JSON 模式支援

JSON 模式目前只獲得下列模型支援:

支援的模型

  • gpt-35-turbo (1106)
  • gpt-35-turbo (0125)
  • gpt-4 (1106-預覽)
  • gpt-4 (0125-預覽)

API 支援

API 版本 2023-12-01-preview 首次新增對 JSON 模式的支援

範例

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。 不過,即使在提示中要求,仍無法保證輸出與特定結構描述相符。