Share via


瞭解如何使用 JSON 模式

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

JSON 模式支援

JSON 模式目前僅支援下列模型:

支援的模型

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

API 支援

API 版本首次新增 JSON 模式的支援 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_reasonlength 。 模型可能會產生部分 JSON。 這表示模型的輸出大於設定為要求一部分的可用max_tokens,或交談本身超過令牌限制。

JSON 模式會產生有效且剖析且沒有錯誤的 JSON。 不過,即使在提示中要求,輸出仍無法比對特定架構。