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')
相关推荐
ComPDFKit1 分钟前
OpenClaw安全风险与规避方法 — 安全“养虾”全套办法
安全·ai
Flittly2 分钟前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(10)Team Protocols (团队协议)
笔记·python·ai·ai编程
阿_旭2 分钟前
基于YOLO26深度学习的蓝莓成熟度检测与分割系统【python源码+Pyqt5界面+数据集+训练代码】图像分割、人工智能
人工智能·python·深度学习·毕业设计·蓝莓成熟度检测
lxmyzzs5 分钟前
使用Python分析COCO数据集标注信息:一个简单脚本实现统计与可视化
python·深度学习·目标检测·计算机视觉
wertyuytrewm5 分钟前
自动化与脚本
jvm·数据库·python
智算菩萨9 分钟前
【How Far Are We From AGI】4 AGI的“生理系统“——从算法架构到算力基座的工程革命
论文阅读·人工智能·深度学习·算法·ai·架构·agi
qq_4176950511 分钟前
Python深度学习入门:TensorFlow 2.0/Keras实战
jvm·数据库·python
problc12 分钟前
在 OpenClaw 里一句话记账:消费说出来,账单自动进乖猫记账 App
开发语言·python
紫丁香13 分钟前
Dify源码深度剖析3
后端·python·ai·flask·fastapi
@Ma13 分钟前
企业微信智能机器人 Python 插件获取回调和发送消息支持文字图片语音视频
python·机器人·企业微信