OpenAI API错误:”‘Choice’对象没有属性’text'”

几个月前我创建了一个Python机器人,它运行得很完美,但现在,在OpenAI SDK更新后,我遇到了一些问题。由于我不太熟悉Python,我需要你的帮助。

这是代码:

from openai import OpenAIimport timeimport osimport csvimport logging# Your OpenAI API keyapi_key = "MY-API-KEY"client = OpenAI(api_key=api_key)# Path to the CSV file containing city namescsv_file = "city.csv"# Directory where generated content files will be savedoutput_directory = "output/"# Initialize the OpenAI API client# Configure logging to save error messageslogging.basicConfig(    filename="error_log.txt",    level=logging.ERROR,    format="%(asctime)s [%(levelname)s]: %(message)s",    datefmt="%Y-%m-%d %H:%M:%S",)# Read city names from the CSV filedef read_city_names_from_csv(file_path):    city_names = []    with open(file_path, "r") as csv_file:        csv_reader = csv.reader(csv_file)        for row in csv_reader:            if row:                city_names.append(row[0])    return city_names# Generate content for a given city name and save it to a filedef generate_and_save_content(city_name):    prompt_template = (        ".... Now Write An Article On This Topic {city_name}"     )    messages = [        {"role": "system", "content": "You are a helpful assistant."},        {"role": "user", "content": prompt_template.format(city_name=city_name)},    ]    try:         response = client.chat.completions.create(model="gpt-3.5-turbo",        messages=messages,        max_tokens=1000)        choices = response.choices        chat_completion = choices[0]        content = chat_completion.text        output_file = os.path.join(output_directory, city_name + ".txt")        with open(output_file, "w", encoding="utf-8") as file:            file.write(content)        return True    except Exception as e:        error_message = f"Error generating content for {city_name}: {str(e)}"        print(error_message)        logging.error(error_message)        return False# Main functiondef main():    # Create the output directory if it doesn't exist    if not os.path.exists(output_directory):        os.makedirs(output_directory)    city_names = read_city_names_from_csv(csv_file)    successful_chats = 0    unsuccessful_chats = 0    for city_name in city_names:        print(f"Generating content for {city_name}...")        success = generate_and_save_content(city_name)        if success:            successful_chats += 1        else:            unsuccessful_chats += 1        # Add a delay to avoid API rate limits        time.sleep(2)    print("Content generation completed.")    print(f"Successful chats: {successful_chats}")    print(f"Unsuccessful chats: {unsuccessful_chats}")if __name__ == "__main__":    main()

目前,我遇到了这个错误:'Choice'对象没有属性'text',我完全无法解决它。你能告诉我如何修复这个问题吗?另外,如果代码中还有其他问题,请指导我如何修复。谢谢。

我尝试了很多方法,使用了Bard和ChatGPT,但都没有帮助。


回答:

你尝试提取响应的方式不正确。

将这段代码…

choices = response.choiceschat_completion = choices[0]content = chat_completion.text # 错误(这适用于Completions API)

…改为这段代码。

choices = response.choiceschat_completion = choices[0]content = chat_completion.message.content # 正确(这适用于Chat Completions API)

或者,如果你想在一行内完成所有操作,将这段代码…

content = response.choices[0].text # 错误(这适用于Completions API)

…改为这段代码。

content = response.choices[0].message.content # 正确(这适用于Chat Completions API)

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注