我试图从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"
标头包含API令牌。没错,我试过了。我还试图传递与json相同的字典,数据,但作为json字符串。总是相同的错误消息。知道怎么打电话吗?
更新:
>>> 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
这些都返回相同的错误。我也尝试将'Content-Type': 'application/json'
添加到标头中。
update2:它适用于使用POST
的完成端点,但不适用于编辑端点。
>>> 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)'
发布于 2022-11-25 22:32:59
API需要一个JSON请求体,而不是表单编码的请求。而且,您需要使用requests.post()
方法来发送正确的HTTP方法。
使用json
参数,而不是data
参数,并使用正确的方法:
requests.post(url, headers=headers, json=data)
请参阅 section文档的OpenAI文档,其中curl
源代码示例发布了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
}'
以及文档的 section:
通常需要发送一些表单编码的数据--非常类似于HTML 。要做到这一点,只需将一个字典传递给
data
参数。当提出请求时,您的数据字典将自动进行表单编码。
..。
有时,您可能希望发送非表单编码的数据。
……
如果您需要application/json
头集,并且不希望自己对dict
进行编码,那么也可以使用参数(添加在2.4.2版中)直接传递它,并且它将被自动编码。
(粗体强调我的,稍作编辑以澄清)。
演示:
>>> 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}}
openai
Python library使用引擎盖下的请求库,但负责处理细节,比如如何正确地为您发送HTTP请求。
https://stackoverflow.com/questions/74578315
复制相似问题