Call OpenAI API with Python requests is missing a model parameter

server/2024/9/25 0:50:04/
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/server/121579.html

相关文章

VmWare安装虚拟机教程(centos7)

VMWare下载&#xff1a; 下载 VMware Workstation Pro - VMware Customer Connect 安装包&#xff1a;&#xff08;16的版本&#xff09;免费&#xff01;&#xff08;一个赞就行&#xff09; 一直点下一步即可&#xff0c;注意修改一下安装位置就好 二、安装虚拟机 安装虚…

kismet和war driving具体准备(仅供无线安全学习)

war driving准备 一台笔记本 一个最好是双频的网卡&#xff0c;单频搜集信号少 我自己买的是http://e.tb.cn/h.grI4EmkDLOqQXHG?tkKZ5g3RVeH6f 如果经济条件允许可以去买大功率天线&#xff08;我买的车载的 大概40db这样子 范围广&#xff09; http://e.tb.cn/h.grCM0CQ6L…

【PostgreSQL教程】PostgreSQL 特别篇之 常用函数

博主介绍:✌全网粉丝20W+,CSDN博客专家、Java领域优质创作者,掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域✌ 技术范围:SpringBoot、SpringCloud、Vue、SSM、HTML、Nodejs、Python、MySQL、PostgreSQL、大数据、物联网、机器学习等设计与开发。 感兴趣的可…

day-59 两数相除

思路 首先判断商的正负&#xff0c;然后便可将两个数都转换为整数&#xff0c;方便商的计算&#xff0c;商的计算用被除数不断减去除数即可 解题过程 注意&#xff1a;整型的负值比正值多一个数&#xff0c;这种特殊情况需要需要单独讨论&#xff0c;同时当除数为1时&#xff…

python基础题练习

1.可否定义一个sum函数呢&#xff1f;返回指定区间的值的和&#xff1f;例如&#xff0c;区间[1,4]的和为123410返回指定区间值的平方的和呢&#xff1f;立方呢&#xff1f; 代码&#xff1a; # 计算从start到end&#xff08;包括end&#xff09;的所有整数的和。 def sum_ra…

宿舍管理系统的设计与实现 (含源码+sql+视频导入教程)

&#x1f449;文末查看项目功能视频演示获取源码sql脚本视频导入教程视频 1 、功能描述 宿舍管理系统拥有三个角色&#xff0c;分别为系统管理员、宿舍管理员以及学生。其功能如下&#xff1a; 管理员&#xff1a;宿舍管理员管理、学生管理、宿舍楼管理、缺勤记录管理、个人密…

【C++】内存管理

目录 C/C内存分布C语言中动态内存管理方式C内存管理方式new/delete操作内置类型new/delete操作自定义类型 operator new与operator delete函数【⭐】透过源码分析两个全局函数 new和delete的实现原理内置类型自定义类型 定位new表达式池化技术原理分析【高并发内存池雏形】 C/C…

Scikit-learn 识别手写数字

Scikit-learn 识别手写数字的完整教程&#xff08;包含各模型预测结果和准确率&#xff09; 本教程将使用 Scikit-learn 提供的手写数字数据集&#xff0c;分别使用支持向量机 (SVM)、随机森林和逻辑回归三种模型进行训练&#xff0c;并展示它们的预测结果和准确率。 1. Scik…