Call OpenAI API with Python requests is missing a model parameter

news2024/9/20 19:20:25

题意:使用 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 请求等细节。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2149815.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

通义千问重磅开源Qwen2.5,性能超越Llama

Qwen2.5 新闻 9月19日云栖大会&#xff0c;阿里云CTO周靖人发布通义千问新一代开源模型Qwen2.5&#xff0c;旗舰模型Qwen2.5-72B性能超越Llama 405B&#xff0c;再登全球开源大模型王座。Qwen2.5全系列涵盖多个尺寸的大语言模型、多模态模型、数学模型和代码模型&#xff0c;每…

TransUNet: 通过Transformer的视角重新思考U-Net架构在医学图像分割中的设计|文献速递-Transformer架构在医学影像分析中的应用

Title 题目 TransUNet: Rethinking the U-Net architecture design for medical imagesegmentation through the lens of transformers TransUNet: 通过Transformer的视角重新思考U-Net架构在医学图像分割中的设计 01 文献速递介绍 卷积神经网络&#xff08;CNNs&#xff…

计算机毕业设计之:教学平台微信小程序(

博主介绍&#xff1a; ✌我是阿龙&#xff0c;一名专注于Java技术领域的程序员&#xff0c;全网拥有10W粉丝。作为CSDN特邀作者、博客专家、新星计划导师&#xff0c;我在计算机毕业设计开发方面积累了丰富的经验。同时&#xff0c;我也是掘金、华为云、阿里云、InfoQ等平台…

生信初学者教程(四):软件

文章目录 RRstudioLinux系统其他软件本书是使用R语言编写的教程,用户需要下载R和RStudio软件用于进行分析。 版权归生信学习者所有,禁止商业和盗版使用,侵权必究 R R语言是一种免费的统计计算和图形化编程语言,是一种用于数据分析和统计建模的强大工具。它具有丰富的统计…

CSP-CCF★201912-2回收站选址★

一、问题描述 二、解答 代码&#xff1a; #include<iostream> #include<map> using namespace std; struct rubbish{int x;int y; }rub[1000]; int n; void input(){cin>>n;for(int i0;i<n;i){cin>>rub[i].x>>rub[i].y;} } bool has(int p,…

【machine learning-八-可视化loss funciton】

可视化lossfunction loss funciton可视化损失函数等高图 loss funciton 上一节讲过损失函数&#xff0c;也就是代价函数&#xff0c;它是衡量模型训练好坏的指标&#xff0c;对于线性回归来说&#xff0c;模型、参数、损失函数以及目标如下&#xff1a;、 损失函数的目标当然…

什么品牌超声波清洗机质量好?四大绝佳超声波清洗机品牌推荐!

在快节奏的现代生活中&#xff0c;个人物品的清洁卫生显得至关重要。眼镜、珠宝饰品、手表乃至日常餐厨用具&#xff0c;这些频繁接触的物品极易累积污渍与细菌。拿眼镜为例&#xff0c;缺乏定期清洁会让油渍与尘埃积累&#xff0c;进而成为细菌的温床&#xff0c;靠近眼睛使用…

SCDN是服务器吗?SCDN防御服务器有什么特点?

SCDN确实具有一定的防DDoS攻击能力&#xff0c;SCDN防御服务器有什么特点&#xff1f;高防SCDN通过结合内容分发网络&#xff08;CDN&#xff09;和分布式拒绝服务&#xff08;DDoS&#xff09;防护技术&#xff0c;提供了更全面的网络保护措施。在充满网络攻击的互联网时代&am…

dev c++输出中文乱码解决 printf乱码解决

把编码换成utf8就行 打开eiditor options

左手研发,右手销量,比亚迪舍弃了什么?

早买早享受&#xff0c;晚买享折扣&#xff0c;是近一年来汽车消费市场的真实写照。 A级家轿价格下探至6、7万元&#xff1b;曾经20万起步的主流B级车&#xff0c;如今只要12万元就能入手&#xff1b;即使是BBA等豪华品牌&#xff0c;也开始降价促销换销量。买车更便宜了&…

乐观锁、悲观锁

一、悲观锁 悲观锁 (Pessimistic Locking)&#xff0c;具有强烈的独占和排他特性。它指的是对数据被外界修改持保守态度。因此&#xff0c;在整个执行过程中&#xff0c;将处于锁定状态。所以&#xff0c;悲观锁是一种悲观思想&#xff0c;它总认为最坏的情况可能会出现&#x…

【Elasticsearch系列十五】强大特性

&#x1f49d;&#x1f49d;&#x1f49d;欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:kwan 的首页,持续学…

没想到【C# ASP.NET + Vue】也能打造如此强大的健身房管理系统!告别传统管理,体验智能化的会员服务,课程安排竟然如此简单

&#x1f393; 作者&#xff1a;计算机毕设小月哥 | 软件开发专家 &#x1f5a5;️ 简介&#xff1a;8年计算机软件程序开发经验。精通Java、Python、微信小程序、安卓、大数据、PHP、.NET|C#、Golang等技术栈。 &#x1f6e0;️ 专业服务 &#x1f6e0;️ 需求定制化开发源码提…

多模态文档理解:一文读懂mPLUG-DocOwl系列模型

〔探索AI的无限可能&#xff0c;微信关注“AIGCmagic”公众号&#xff0c;让AIGC科技点亮生活〕 本文作者&#xff1a;AIGCmagic社区 刘一手 前言 随着人工智能技术的发展&#xff0c;多模态大型语言模型&#xff08;MLLMs&#xff09;在视觉-文本理解领域取得了显著进展。m…

yolov8多任务模型-目标检测+车道线检测+可行驶区域检测-yolo多检测头代码+教程

你只需看一次&#xff1a;实时且通用的多任务模型 A-YOLOM 插图 贡献 轻量化集成模型&#xff1a;我们开发了一种轻量级模型&#xff0c;能够将三个任务整合到一个统一的模型中。这对于需要实时处理的多任务场景尤其有利。自适应连接模块&#xff1a;特别为分割架构的颈部区域…

js中的 赋值 浅拷贝 和 深拷贝 详细解读

js数据类型主要分基本数据类型和引用数据类型。前者包括Number,String等&#xff0c;后者主要是Object,因此以下会针对不同的数据类型来分析,需要的朋友可以参考一下 基本数据类型&#xff08;Primary Data Types&#xff09;: String&#xff08;字符串&#xff09; Number&…

--芯片测试--

目录 芯片逻辑是什么 芯片如何选型&#xff1f; 测试策略有什么 Alpha测试和Beta测试的区别&#xff1f; 主要区别 TOPS是什么 如何计算TOPS MAC单元是什么 频率的单位是什么 如何解决跨时钟域问题&#xff1f; 解释一下对异步电路的理解&#xff0c;以及如何实现同步…

【北京迅为】《STM32MP157开发板使用手册》-第四十三章 软件定时器实验

iTOP-STM32MP157开发板采用ST推出的双核cortex-A7单核cortex-M4异构处理器&#xff0c;既可用Linux、又可以用于STM32单片机开发。开发板采用核心板底板结构&#xff0c;主频650M、1G内存、8G存储&#xff0c;核心板采用工业级板对板连接器&#xff0c;高可靠&#xff0c;牢固耐…

seL4 Capabilities(翻自官网)(一)

官网教程链接: Capability 初始化Capabilities tutorials // 先使用repo拉取一下tutorials&#xff0c;然后执行repo sync&#xff0c;所有的教程都在里面&#xff0c;学习某个的时候只需要改变的是 --tut 后面的参数 ./init --tut capabilities # building the tutorial exe…

电商商品详情API接口对电商跨境电商企业运营的好处

为了获取更大利益&#xff0c;电商商家经常需要使用价格&#xff0c;ERP接口系统。价格接口对电商商家有多方面的好处&#xff0c;主要体现在以下几个方面&#xff1a; 1、价格接口系统可以帮助品牌和商家实现更加科学和精准的定价策略。通过实时获取多个主流电商平台&#xf…