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 界面发送请求时都会出现这个错误:”

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 的响应都放在一个变量中,但没有任何变化。仍然出现相同的错误。响应看起来是这样的:”

{
  "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
  }
}

问题解决:

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]`。”

print(response['choices'][0]['message']['content'])

'HIIIIIII'

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

response.get('choices')[0].get('message').get('content')

  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

营赢盈英

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值