OpenAI API:如何使用 gpt-4-vision-preview 模型启用 JSON 模式?

chi*_*bop 5 python openai-api gpt-4

更新:他们似乎在 API 文档中犯了一个错误,现在已修复。

早些时候,它说“当调用gpt-4-vision-preview或 时gpt-3.5-turbo”,但现在改为“当调用gpt-4-1106-preview或 时gpt-3.5-turbo-1106”。


根据Text Generation - OpenAI API,“当调用gpt-4-vision-preview或时gpt-3.5-turbo,您可以将 response_format 设置{ type: "json_object" }为启用 JSON 模式。”

但是,以下代码会引发错误:

 {'error': {'message': '1 validation error for Request\nbody -> response_format\n  extra fields not permitted (type=value_error.extra)', 'type': 'invalid_request_error', 'param': None, 'code': None}}
Run Code Online (Sandbox Code Playgroud)

如果我发表评论"response_format": {"type": "json_object"},效果很好。

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }
    
    payload = {
        "model": "gpt-4-vision-preview",
        "response_format": {"type": "json_object"},
        "messages": [
          {
            "role": "system",
            "content": "You are a helpful assistant. Your response should be in JSON format."
          },
          {
            "role": "user",
            "content": [
              {
                "type": "text",
                "text": prompt
              },
              {
                "type": "image_url",
                "image_url": {
                  "url": f"data:image/jpeg;base64,{base64_image}"
                }
              }
            ]
          }
        ],
        "max_tokens": 1000,
    }
    
    response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
    print(response.json())
Run Code Online (Sandbox Code Playgroud)

Rok*_*nko 7

gpt-4-1106-preview只有使用or才能返回 JSON 响应,如gpt-3.5-turbo-1106OpenAI官方文档中所述:

使用聊天完成的常见方法是通过提供系统消息来指示模型始终以对您的用例有意义的某种格式返回 JSON。这效果很好,但有时模型可能会生成无法解析为有效 JSON 的输出。

为了防止这些错误并提高模型性能,在调用 gpt-4-1106-preview或时gpt-3.5-turbo-1106,可以设置response_format{ type: "json_object" }启用 JSON 模式。启用 JSON 模式时,模型仅限于生成解析为有效 JSON 的字符串。

另外,我还制作了一个有关如何获取 JSON 格式的响应的YouTube 教程,并将代码发布到我的 GitHub 个人资料上。


Python 中的工作示例

如果运行test.py,您将得到以下响应:

{ "response": "您好!今天需要什么帮助吗?" }

测试.py

import os
from openai import OpenAI
client = OpenAI()
OpenAI.api_key = os.getenv('OPENAI_API_KEY')

completion = client.chat.completions.create(
  model="gpt-4-1106-preview",
  messages=[
    {"role": "system", "content": "You are a helpful assistant. Your response should be in JSON format."},
    {"role": "user", "content": "Hello!"}
  ],
  response_format={"type": "json_object"}
)

print(completion.choices[0].message.content)
Run Code Online (Sandbox Code Playgroud)

Node.js 中的工作示例

如果运行test.js,您将得到以下响应:

{ "response": "您好!今天需要什么帮助吗?" }

测试.js

const OpenAI = require("openai");
const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

async function main() {
  const completion = await openai.chat.completions.create({
    model: "gpt-4-1106-preview",
    messages: [
      {
        role: "system",
        content:
          "You are a helpful assistant. Your response should be in JSON format.",
      },
      { role: "user", content: "Hello!" },
    ],
    response_format: { type: "json_object" },
  });

  console.log(completion.choices[0].message.content);
}

main();
Run Code Online (Sandbox Code Playgroud)


小智 1

根据发行说明,这些 GPT 模式不支持新的 JSON 输出格式选项。尝试 gpt-3.5-turbo-1106 或 gpt-4-1106-preview 而不是 gpt-3.5-turbo。

https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo