【问题标题】:How can i chat with chatgpt using python我如何使用 python 与 chatgpt 聊天
【发布时间】:2023-02-05 19:09:08
【问题描述】:

我要求 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,所以这是我唯一的选择。

【问题讨论】:

    标签: python python-requests openai


    【解决方案1】:

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

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

    下面是使用 cURL 的 URL 结构和所需标头的示例。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-05
      • 1970-01-01
      • 2023-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多