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')
相关推荐
DeepLink9 分钟前
Python小练习系列:学生信息排序(sorted + key函数)
python·求职
项目申报小狂人13 分钟前
CUDA详细安装及环境配置——环境配置指南 – CUDA+cuDNN+PyTorch 安装
人工智能·pytorch·python
学c真好玩23 分钟前
4.1-python操作wrod/pdf 文件
开发语言·python·pdf
东方佑24 分钟前
使用Python解析PPT文件并生成JSON结构详解
python·json·powerpoint
Auroral15626 分钟前
一文搞懂python实现邮件发送的全流程
python
大霸王龙28 分钟前
LLM(语言学习模型)行为控制技术
python·深度学习·学习
我不是大佬zvj30 分钟前
PyGame开发贪吃蛇小游戏
python·pygame
这里有鱼汤40 分钟前
Python 图像处理必备的 15 个基本技能 🎨
前端·后端·python
这里有鱼汤41 分钟前
想学会Python自动化办公?这20个Excel表格操作脚本一定要掌握!
前端·后端·python
ALe要立志成为web糕手44 分钟前
用Python实现TCP代理
网络·python·网络协议·tcp/ip·安全·web安全