当前位置: 首页 > news >正文

Call OpenAI API with Python requests is missing a model parameter

题意:使用 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 包,因为它更灵活。下面是我的调用代码。

>>> 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:

>>> 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 端点无效。

>>> 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 的:

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:

>>> 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 请求等细节。

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • Stable Diffusion 使用详解(11)--- 场景ICON制作
  • (十六)、把镜像推送到私有化 Docker 仓库
  • 2024华为杯研赛E题保姆级教程思路分析
  • 打造民国风格炫酷个人网页:用HTML和CSS3传递民国风韵
  • 如何在Windows上安装Docker
  • 业务资源管理模式语言17
  • 如何通过蜂巢(容器安全)管理内部部署数据安全产品与云数据安全产品?
  • 浅谈计算机视觉新手的学习路径
  • AIoT智能工控板
  • Linux常用指令
  • [SDX35]SDX35硬件使用512MB内存,实际只初始化256MB问题分析及解决方案
  • 【STM32】esp8266连接wifi
  • 进阶SpringBoot之异步任务、邮件任务和定时执行任务
  • 高级I/O知识分享【5种IO模型 || select || poll】
  • 7000长文:一文读懂Agent,大模型的下一站
  • php的引用
  • [译]CSS 居中(Center)方法大合集
  • 【399天】跃迁之路——程序员高效学习方法论探索系列(实验阶段156-2018.03.11)...
  • 【mysql】环境安装、服务启动、密码设置
  • 【Redis学习笔记】2018-06-28 redis命令源码学习1
  • Create React App 使用
  • CSS 专业技巧
  • go append函数以及写入
  • IIS 10 PHP CGI 设置 PHP_INI_SCAN_DIR
  • iOS高仿微信项目、阴影圆角渐变色效果、卡片动画、波浪动画、路由框架等源码...
  • JAVA 学习IO流
  • weex踩坑之旅第一弹 ~ 搭建具有入口文件的weex脚手架
  • 百度地图API标注+时间轴组件
  • 对话:中国为什么有前途/ 写给中国的经济学
  • 回顾2016
  • 聚簇索引和非聚簇索引
  • 使用 5W1H 写出高可读的 Git Commit Message
  • 学习笔记DL002:AI、机器学习、表示学习、深度学习,第一次大衰退
  • 仓管云——企业云erp功能有哪些?
  • ​软考-高级-系统架构设计师教程(清华第2版)【第1章-绪论-思维导图】​
  • (70min)字节暑假实习二面(已挂)
  • (M)unity2D敌人的创建、人物属性设置,遇敌掉血
  • (阿里云在线播放)基于SpringBoot+Vue前后端分离的在线教育平台项目
  • (二十九)STL map容器(映射)与STL pair容器(值对)
  • (附源码)springboot课程在线考试系统 毕业设计 655127
  • (论文阅读30/100)Convolutional Pose Machines
  • (排序详解之 堆排序)
  • (三)Hyperledger Fabric 1.1安装部署-chaincode测试
  • (实测可用)(3)Git的使用——RT Thread Stdio添加的软件包,github与gitee冲突造成无法上传文件到gitee
  • (译)2019年前端性能优化清单 — 下篇
  • (原創) 物件導向與老子思想 (OO)
  • (转)EOS中账户、钱包和密钥的关系
  • (转)拼包函数及网络封包的异常处理(含代码)
  • (转)重识new
  • .360、.halo勒索病毒的最新威胁:如何恢复您的数据?
  • .aanva
  • .Mobi域名介绍
  • .net core docker部署教程和细节问题
  • .net 获取某一天 在当月是 第几周 函数
  • .Net环境下的缓存技术介绍