几个月前我创建了一个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)