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')
相关推荐
浅浅28010 分钟前
numpy、pandas内存优化操作整理
数据结构·经验分享·python·学习·性能优化·numpy·pandas
MCP星球15 分钟前
我们离Agent终极形态又近了一步:全球首个支持谷歌A2A(Agent-to-Agent)协议的智能体注册网站上线Product Hunt,未来智能体协作网络
ai·agent·智能体·智能体协作·a2a·a2a协议·agent network·智能体网络·谷歌a2a·agent2agent
拓端研究室TRL27 分钟前
Python+AI提示词比特币数据预测:Logistic逻辑回归、SVC及XGB特征工程优化实践
开发语言·人工智能·python·算法·逻辑回归
就叫飞六吧27 分钟前
Python自动化selenium-一直卡着不打开浏览器怎么办?
python·selenium·自动化
亚林瓜子33 分钟前
AWS Elastic Beanstalk的部署Python Flask后端服务(Hello,World)
python·flask·aws·eb
weixin_3077791339 分钟前
实现AWS Step Function安全地请求企业内部API返回数据
开发语言·python·云计算·aws
小研学术1 小时前
如何用AI辅助数据分析及工具推荐
论文阅读·人工智能·ai·数据挖掘·数据分析·deepseek
zhangjipinggom1 小时前
怎么安装python3.5-以及怎么在这个环境下安装包
开发语言·python
格子先生Lab1 小时前
Java反射机制深度解析与应用案例
java·开发语言·python·反射
Samuel-Gyx2 小时前
2025第十六届蓝桥杯python B组满分题解(详细)
python·职场和发展·蓝桥杯