You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复OpenAI ChatCompletion API的AttributeError并实现多关键词响应

问题:循环调用OpenAI API生成股票相关响应时触发AttributeError错误

错误信息

运行代码后触发以下错误:

PS C:\Users\...\Documents\Article-gen> & C:/Users/.../AppData/Local/Microsoft/WindowsApps/python3.11.exe c:/Users/.../Documents/Article-gen/createArticle.py
ChatGPT API replies for Amazon (AMZN) stock:

Traceback (most recent call last):
  File "C:\Users\...\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\openai\openai_object.py", line 59, in __getattr__
    return self[k]
           ~~~~^^^
KeyError: 'text'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\Users\...\Documents\Article-gen\createArticle.py", line 29, in <module>
    outputText = choice.text.strip()
                 ^^^^^^^^^^^
  File "C:\Users\...\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\openai\openai_object.py", line 61, in __getattr__
    raise AttributeError(*err.args)
AttributeError: text

用户原始代码

import openai
import os

# Set OpenAI API key
openai.api_key = ""

# Then, you can call the "gpt-3.5-turbo" model
modelEngine = "gpt-3.5-turbo"

# set your input text
inputText = "Write a 1,500 word that is highly speculative bullish article IN YOUR OWN WORDS on {} stock and why it went up, you must include how it could affect the stock price and future outcome of the business. Include subheadings in your own words and act like you know it all and be an authoritative expert on the topic. Now write."

# Array of keywords to generate article on
keywords = ["Nio (NIO)", "Apple (AAPL)", "Microsoft (MSFT)", "Tesla (TSLA)", "Meta (META)", "Amazon (AMZN)"]

# Switches and injects keywords into API request
for keyword in keywords:
    # set input text with the current keyword
    inputSent = inputText.format(keyword)

# Send an API request and get a response, note that the interface and parameters have changed compared to the old model
response = openai.ChatCompletion.create(
   model=modelEngine,
   messages=[{"role": "user", "content": inputSent }],
   n = 1
)
print("ChatGPT API replies for", keyword, "stock:\n")
for choice in response.choices:
        outputText = choice.text.strip()
        print(outputText)
        print("------")
print("\n")

修复方案及原因

1. 响应结构错误

使用gpt-3.5-turbo模型调用ChatCompletion.create()时,返回的响应结构和旧版Completion接口不同:旧接口用choice.text获取内容,但ChatCompletion的每个choice里是message.content字段,直接访问choice.text会触发AttributeError。

2. 循环逻辑错误

原始代码的for循环仅遍历关键词给inputSent赋值,但API请求和打印逻辑都在循环外,导致只会处理最后一个关键词(Amazon),没有实现每个关键词生成响应的需求。

修复后的完整代码

import openai

# 设置OpenAI API密钥
openai.api_key = "你的API密钥"

# 使用gpt-3.5-turbo模型
modelEngine = "gpt-3.5-turbo"

# 提示词模板
inputText = "Write a 1,500 word that is highly speculative bullish article IN YOUR OWN WORDS on {} stock and why it went up, you must include how it could affect the stock price and future outcome of the business. Include subheadings in your own words and act like you know it all and be an authoritative expert on the topic. Now write."

# 要生成文章的股票关键词列表
keywords = ["Nio (NIO)", "Apple (AAPL)", "Microsoft (MSFT)", "Tesla (TSLA)", "Meta (META)", "Amazon (AMZN)"]

# 遍历每个关键词生成响应
for keyword in keywords:
    # 填充模板生成当前关键词的提示词
    inputSent = inputText.format(keyword)
    
    # 发送API请求
    response = openai.ChatCompletion.create(
        model=modelEngine,
        messages=[{"role": "user", "content": inputSent}],
        n=1
    )
    
    # 打印结果
    print(f"ChatGPT API replies for {keyword} stock:\n")
    for choice in response.choices:
        # 正确获取响应内容
        outputText = choice.message.content.strip()
        print(outputText)
        print("------")
    print("\n")

内容的提问来源于stack exchange,提问作者overdeveloping

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 08:42:35