Getting AttributeError when using openAI python library

题意:"使用 OpenAI Python 库时出现 AttributeError"

问题背景:

I'm building a new AI chatbot utilizing the openai library and I have a gradio UI set up in one file (app.py) and a predict() function in another (trainedBot.py) Every time I send a request through the gradio UI I get this error:

"我正在使用 OpenAI 库构建一个新的 AI 聊天机器人,并在一个文件 (app.py) 中设置了 Gradio 界面,在另一个文件 (trainedBot.py) 中编写了 predict() 函数。每次我通过 Gradio 界面发送请求时都会出现这个错误:"

python 复制代码
File "/home/user/app/trainedBot.py", line 48, in predict
    return response.choices.message.content
AttributeError: 'list' object has no attribute 'message'

I tried putting both the message and the openAI response in a variable and nothing happened. Still got the same error. The response looked like this:

"我尝试将消息和 OpenAI 的响应都放在一个变量中,但没有任何变化。仍然出现相同的错误。响应看起来是这样的:"

python 复制代码
{
  "id": "chatcmpl-8CHKgpOewruWDC2Et1R6ZFtdPmSQR",
  "object": "chat.completion",
  "created": 1697937254,
  "model": "gpt-4-0613",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "HIIIIIII"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 308,
    "completion_tokens": 4,
    "total_tokens": 312
  }
}

问题解决:

python 复制代码
response = {
  "id": "chatcmpl-8CHKgpOewruWDC2Et1R6ZFtdPmSQR",
  "object": "chat.completion",
  "created": 1697937254,
  "model": "gpt-4-0613",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "HIIIIIII"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 308,
    "completion_tokens": 4,
    "total_tokens": 312
  }
}

Your choices is a list so access it you need to put [0]

"你的 `choices` 是一个列表,所以要访问它,你需要使用 `[0]`。"

python 复制代码
print(response['choices'][0]['message']['content'])

'HIIIIIII'

Or could be: 或者也可以用以下的方式

python 复制代码
response.get('choices')[0].get('message').get('content')
相关推荐
亿牛云爬虫专家5 分钟前
优化数据的抓取规则:减少无效请求
python·数据采集·多线程·爬虫代理·数据抓取·代理ip·房价
程序媛堆堆7 分钟前
解决NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+问题
python
DreamByte10 分钟前
Python Tkinter小程序
开发语言·python·小程序
Python极客之家11 分钟前
基于深度学习的眼部疾病检测识别系统
人工智能·python·深度学习·毕业设计·卷积神经网络
Bigcrab__17 分钟前
Python3网络爬虫开发实战(15)Scrapy 框架的使用(第一版)
爬虫·python·scrapy
千寻简1 小时前
Cursor免费 GPT-4 IDE 工具的保姆级使用教程
java·运维·ide·ai
易辰君1 小时前
Python编程 - 协程
开发语言·python
宇宙第一小趴菜1 小时前
探索网络世界:TCP/IP协议、Python Socket编程及日常生活比喻
网络·python·tcp/ip
小黑031 小时前
Phoenix使用
开发语言·python
南斯拉夫的铁托1 小时前
(PySpark)RDD实验实战——求商品销量排行
python·spark·pyspark