gpt4 book ai didi

python - 我如何使用 python 与 chatgpt 聊天

转载 作者:行者123 更新时间:2023-12-02 05:47:01 25 4
gpt4 key购买 nike

我请 ChatGPT 向我展示如何使用 OpenAi 的 API 在我的终端窗口中与其交互,它生成的代码我稍作修改以执行我想要的操作。

这是python代码:

import requests

with open('../api-key.txt','r') as key:
data = key.read().strip()

api_key = data
model="text-danvinci-003"

def chat_with_chatgpt(prompt):
res = requests.post(f"https://api.openai.com/v1/engines/{model}/jobs", headers = {
"Content-Type":"application/json",
"Authorization":f"Bearer {api_key}"
},
json={
"prompt":prompt,
"max_tokens":100
}).json()
print(res)
return res.choices[0].text

while True:
prompt = input('Me: ')
response = chat_with_chatgpt(prompt)
print(f'ChatGPT: {response}')

但是当我运行这段代码时,我收到了一些消息:

Me: hello
{'error': {'message': 'That model does not exist', 'type': 'invalid_request_error', 'param': None, 'code': None}}
Traceback (most recent call last):
File "/data/data/com.termux/files/home/python/main.py", line 23, in <module>
response = chat_with_chatgpt(prompt) ^^^^^^^^^^^^^^^^^^^^^^^^^
File "/data/data/com.termux/files/home/python/main.py", line 19, in chat_with_chatgpt
return res.choices[0].text
^^^^^^^^^^^ AttributeError: 'dict' object has no attribute 'choices'

我得到的响应是错误指令。

由于某些原因,我无法在我的系统上通过 pip install openai 安装 OpenAi,所以这是我唯一的选择。

最佳答案

我认为引擎 API 端点已被弃用,取而代之的是模型。欲了解更多信息,请阅读此处:https://help.openai.com/en/articles/6283125-what-happened-to-engines

您需要查看完成端点而不是 https://platform.openai.com/docs/api-reference/completions

这是使用 cURL 所需的 URL 结构和 header 的示例。

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

代码的一般结构应该没问题,您只需要换出正在使用的端点。

def chat_with_chatgpt(prompt):
res = requests.post(f"https://api.openai.com/v1/completions",
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
},
json={
"model": model
"prompt": prompt,
"max_tokens": 100
}).json()
return res.choices[0].text

关于python - 我如何使用 python 与 chatgpt 聊天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75351597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com