Call OpenAI API with Python requests is missing a model parameter

news/2024/9/25 0:15:23/
aidu_pl">

题意:使用 Python requests 调用 OpenAI API 时缺少 model 参数。

问题背景:

I'm trying to call OpenAI API from Python. I know they have their own openai package, but I want to use a generic solution. I chose the requests package for its flexibility. Here is my call

我正在尝试从 Python 调用 OpenAI API。我知道他们有自己的 openai 包,但我想使用一个通用的解决方案。我选择了 requests 包,因为它更灵活。下面是我的调用代码。

python">>>> headers = {"Authorization": "Bearer xxx"}
>>> url = 'https://api.openai.com/v1/completions'
>>> data = {'model': 'text-davinci-002', 'prompt': 'Once upon a time'}
>>> requests.get(url, headers=headers, data=data).content
...  "error": {\n        "message": "you must provide a model parameter"

The header contains the API token. It's correct, I tried it. I also tried to pass the same dictionary as json, as data but as a json string. Always the same error message. Any idea how to make the call?

请求头中包含了 API 令牌,是正确的,我已经测试过。我还尝试将相同的字典作为 JSON 或字符串传递,总是出现相同的错误信息。有什么办法可以让调用成功吗?

Update:

python">>>> requests.get(url, headers=headers, json=data).content
>>> requests.get(url, headers=headers, json=json.dumps(data)).content
>>> requests.get(url, headers=headers, data=json.dumps(data)).content
>>> requests.get(url, headers=headers, data=json.dumps(data).encode()).content

These all return the same error. I tried to add 'Content-Type': 'application/json' to the headers too.

这些方法都会返回相同的错误。我也尝试在请求头中添加 'Content-Type': 'application/json'

update2: It works for the completion endpoint with POST, but not for the edit endpoint.

更新2:对于 completion 端点使用 POST 方法是可行的,但对 edit 端点无效。

python">>>> completion_url =  "https://api.openai.com/v1/completions"
>>> completion_data = {'model': 'text-davinci-002', 'prompt': 'Once upon a time'}
>>> requests.post(completion_url, headers=headers, json=completion_data).json()
... # it works
>>> edit_url =  "https://api.openai.com/v1/edits"
>>> completion_data = {'model': 'text-davinci-002', 'input': 'Once upon a time', 'instruction': 'Continue'}
>>> requests.get(edit_url, headers=headers, json=edit_data).json()['error']['message']
'you must provide a model parameter'
>>> requests.post(edit_url, headers=headers, json=edit_data).json()['error']['message']
'Invalid URL (POST /v1/edits)'

问题解决:

The API expects a JSON request body,not a form-encoded request. And, you need to use the requests.post() method to send the right HTTP method.

翻译为:

“API 期望接收的是 JSON 格式的请求体,而不是表单编码的请求。另外,你需要使用 `requests.post()` 方法来发送正确的 HTTP 请求。”

Use the json argument, not the data argument, and the right method:

使用 json 参数,而不是 data 参数,并确保使用正确的方法:

requests.post(url, headers=headers, json=data)

See the Create completion section of the OpenAI documentation, where the curl source code sample posts JSON:

请参阅 OpenAI 文档的创建 completion 部分,其中的 curl 示例代码是通过 POST 方法发送 JSON 的:

python">curl https://api.openai.com/v1/completions \-H 'Content-Type: application/json' \-H 'Authorization: Bearer YOUR_API_KEY' \-d '{"model": "text-davinci-002","prompt": "Say this is a test","max_tokens": 6,"temperature": 0
}'

as well as the More complicated POST requests section of the documentation:

以及文档中的更复杂的 POST 请求部分:

Typically, you want to send some form-encoded data — much like an HTML form. To do this, simply pass a dictionary to the data argument. Your dictionary of data will automatically be form-encoded when the request is made[.]

[...]

There are times that you may want to send data that is not form-encoded.

[...].

If you need [the application/json header] set and you don’t want to encode the dict yourself, you can also pass it directly using the json parameter (added in version 2.4.2) and it will be encoded automatically[.]

(Bold emphasis mine, slightly edited for clarity).

Demo:

python">>>> import requests
>>> key = "<APIKEY>"
>>> headers = {"Authorization": f"Bearer {key}"}
>>> data = {'model': 'text-davinci-002', 'prompt': 'Once upon a time'}
>>> requests.post(url, headers=headers, json=data).json()
{'id': 'cmpl-6HIPWd1eDo6veh3FkTRsv9aJyezBv', 'object': 'text_completion', 'created': 1669580366, 'model': 'text-davinci-002', 'choices': [{'text': ' there was a castle up in space. In this castle there was a queen who', 'index': 0, 'logprobs': None, 'finish_reason': 'length'}], 'usage': {'prompt_tokens': 4, 'completion_tokens': 16, 'total_tokens': 20}}

The openai Python library uses the requests library under the hood but takes care of details like how to send HTTP requests correctly for you.

openai Python 库在底层使用了 requests 库,但它会为你处理如何正确发送 HTTP 请求等细节。


http://www.ppmy.cn/news/1530027.html

相关文章

SQL面试常见题目

SQL面试常见题目涉及多个方面&#xff0c;包括数据查询、数据操作、表的设计与优化等。以下列举一些经典的SQL面试题目&#xff0c;并附上解析答案&#xff1a; 1. 查询一张表中重复的数据 题目&#xff1a; 给定一个表 employees&#xff0c;包含 id, name, salary 列。如何…

使用Redis实现用户关注博客的推模式

目录 一、思路 二、实现代码&#xff1a; 一、思路 发布者&#xff1a; 这里采用redis的zset结构&#xff0c;将键设置为被推送用户id&#xff0c;值设置为博客id&#xff0c;score设置为时间戳 推送之前先查到当前发布博客用户的粉丝有哪些&#xff0c;然后去循环挨个推送…

RabbitMQ08_保证消息可靠性

保证消息可靠性 一、生产者可靠性1、生产者重连机制&#xff08;防止网络波动&#xff09;2、生产者确认机制Publisher Return 确认机制Publisher Confirm 确认机制 二、MQ 可靠性1、数据持久化交换机、队列持久化消息持久化 2、Lazy Queue 惰性队列 三、消费者可靠性1、消费者…

web学习——VUE

VUE&Element 今日目标&#xff1a; 能够使用VUE中常用指令和插值表达式能够使用VUE生命周期函数 mounted能够进行简单的 Element 页面修改能够完成查询所有功能能够完成添加功能 1&#xff0c;VUE 1.1 概述 接下来我们学习一款前端的框架&#xff0c;就是 VUE。 Vue 是…

网络:UDP协议

个人主页 &#xff1a; 个人主页 个人专栏 &#xff1a; 《数据结构》 《C语言》《C》《Linux》 文章目录 前言UDP协议报头和有效载荷分离的问题有效载荷向上交付的问题&#xff0c;也就是交给哪个进程&#xff1f;怎么确定把报文收全了&#xff1f;UDP报头是如何封装的呢&…

828华为云征文 | 华为云X实例的镜像管理详解

前言 随着云计算的不断普及&#xff0c;云服务器成为企业和开发者日常工作中的重要工具。为了提升工作效率和降低运维成本&#xff0c;云服务器镜像的管理尤为重要。镜像作为服务器或磁盘的模板&#xff0c;预装了操作系统、软件及配置&#xff0c;是快速部署和迁移业务的重要…

某建筑市场爬虫数据采集逆向分析

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言 目标网站 aHR0cHM6Ly9qenNjLm1vaHVyZC5nb3YuY24vZGF0YS9jb21wYW55P2NvbXBsZXhuYW1lPSVFNiVCMCVCNA 提示&#xff1a;以下是本篇文章正文内容&#xff0c;下面…

机器翻译与数据集_by《李沐:动手学深度学习v2》pytorch版

系列文章目录 文章目录 系列文章目录介绍机器翻译下载和预处理数据集词元化词表加载数据集训练模型对上述代码中出现的Vocab进行总体解释和逐行解释使用场景 小结练习答案1. num_examples 参数对词表大小的影响2. 对于没有单词边界的语言&#xff0c;单词级词元化的有效性 介绍…