Search code examples
pythonopenai-apichatgpt-api

OpenAI API error: "'Choice' object has no attribute 'text'"


I created a Python bot a few months ago, and it worked perfectly, but now, after the OpenAI SDK update, I have some problems with it. As I don't know Python very well, I need your help.

This is the code:

from openai import OpenAI
import time
import os
import csv
import logging

# Your OpenAI API key
api_key = "MY-API-KEY"

client = OpenAI(api_key=api_key)

# Path to the CSV file containing city names
csv_file = "city.csv"

# Directory where generated content files will be saved
output_directory = "output/"

# Initialize the OpenAI API client

# Configure logging to save error messages
logging.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 file
def 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 file
def 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 function
def 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()

Currently, I'm getting this error: 'Choice' object has no attribute 'text' and couldn't fix it at all. Would you please tell me how I can fix this? Also, if there is any other problem with the code, please guide me on how to fix it. Thanks.

I tried many things using Bard and ChatGPT, but none of them helped.


Solution

  • You're trying to extract the response incorrectly.

    Change this...

    choices = response.choices
    chat_completion = choices[0]
    content = chat_completion.text # Wrong (this works with the Completions API)
    

    ...to this.

    choices = response.choices
    chat_completion = choices[0]
    content = chat_completion.message.content # Correct (this works with the Chat Completions API)
    

    Or, if you want to have everything in one line, change this...

    content = response.choices[0].text # Wrong (this works with the Completions API)
    

    ...to this.

    content = response.choices[0].message.content # Correct (this works with the Chat Completions API)