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')
相关推荐
小糖学代码4 小时前
LLM系列:1.python入门:3.布尔型对象
linux·开发语言·python
Data_agent4 小时前
1688获得1688店铺详情API,python请求示例
开发语言·爬虫·python
CoderJia程序员甲5 小时前
GitHub 热榜项目 - 日榜(2025-12-3)
ai·开源·llm·github·ai教程
周杰伦fans5 小时前
pycharm之gitignore设置
开发语言·python·pycharm
蜜獾云6 小时前
Stable Diffusion aki v4下载
ai·ai作画·aigc
weixin_462446236 小时前
【原创实践】python 获取节假日列表 并保存为excel
数据库·python·excel
计算机毕设匠心工作室6 小时前
【python大数据毕设实战】全球大学排名数据可视化分析系统、Hadoop、计算机毕业设计、包括数据爬取、数据分析、数据可视化、机器学习、实战教学
后端·python·mysql
别叫我->学废了->lol在线等6 小时前
演示 hasattr 和 ** 解包操作符
开发语言·前端·python
胡玉洋6 小时前
跨时空便民服务站
ai·ai作画·llm·aigc·ai编程·ai写作
free-elcmacom7 小时前
机器学习入门<6>BP神经网络揭秘:从自行车摔跤到吃一堑长一智的AI智慧
人工智能·python·深度学习·神经网络·机器学习