Hi Leaders, can you please help me out?..I fear I am really frustrated
I keep on having the error " AttributeError: ‘OpenAI’ object has no attribute ‘file’ "
Given that, I am using VS code, my API is up to date, file path is correct, Python version = 3.10.10, OpenAI version =1.8.0
Below is my code:
import openai
from dotenv import load_dotenv
from openai import OpenAI
import os
import requests
import traceback
import time
Add this line to print the OpenAI library version
print(openai.version)
Load environment variables and set OpenAI API key
load_dotenv()
api_key = os.getenv(‘OPENAI_API_KEY’)
Ensure the API key is available
if not api_key:
raise ValueError(“The OPENAI_API_KEY must be set in the environment variables.”)
Initialize the OpenAI client with the API key
client = OpenAI(api_key=api_key)
def download_pdf(url, filename):
try:
response = requests.get(url)
response.raise_for_status()
with open(filename, “wb”) as file:
file.write(response.content)
return True
except Exception as e:
print(“Failed to download the PDF:”, e)
traceback.print_exc()
return False
def upload_file(client, file_path):
#def upload_file(file_path):
try:
with open(file_path, ‘rb’) as file:
file_response = client.file.create(file=file, purpose=‘answers’)#use clients file
return file_response.id
except Exception as e:
print(“Failed to upload file:”, e)
traceback.print_exc()
return None
#print(upload_file)
def upload_file(cleint,file_path):
try:
with open(file_path, ‘rb’) as file:
response = openai.File.create(file=file) # Use openai.File.create directly
return response.id
except Exception as e:
print(“Failed to upload file:”, e)
traceback.print_exc()
return None
def create_thread_and_message(client, assistant_id, prompt, file_id):
thread = client.thread.create()
thread_id = thread.id
message = client.message.create(thread_id=thread_id, role=“user”, content=prompt, file_id=file_id)
return thread_id, message.id
def create_run(client, assistant_id, thread_id):
run = client.run.create(assistant_id=assistant_id, thread_id=thread_id)
return run
def wait_on_run(client, run):
while run.status in [“queued”, “in_progress”]:
time.sleep(0.5)
run = client.run.retrieve(id=run.id)
return run
def get_run_messages(client, thread_id, last_message_id):
messages = client.message.list(thread_id=thread_id, order=“asc”, after=last_message_id)
return messages
Define the URL for the PDF and local directory to save the file
url = “https://etechyou.org/wp-content/uploads/2021/12/FURIOUS-ENTREPRENEURS-RULES-AND-REGULATIONS-Online-1.pdf”
local_directory = r"C:\Users\myname\OneDrive\Desktop\python steps" #“C:\Users\myname\OneDrive\Desktop\python steps\”
input_pdf = os.path.join(local_directory, “downloaded_pdf.pdf”)
Download the PDF
if not download_pdf(url, input_pdf):
raise Exception(“Failed to download PDF.”)
Upload the PDF to OpenAI and retrieve the file ID
file_id = upload_file(client,input_pdf)
if not file_id:
raise Exception(“Failed to upload PDF to OpenAI.”)
Create an Assistant
assistant = client.assistant.create(
name=“SummaryPandaV3”,
model=“gpt-4-1106-preview”,
tools=[{“type”: “retrieval”}]
)
Create a thread and a message asking to summarize the PDF
thread_id, message_id = create_thread_and_message(client, assistant.id, “Please summarize this document focusing on the most relevant points.”, file_id)
Create a run to process the thread
run = create_run(client, assistant.id, thread_id)
Wait for the run to complete
run = wait_on_run(client, run)
Retrieve the assistant’s messages after the user’s last message
messages = get_run_messages(client, thread_id, message_id)
Extract the response from the messages
summary = “”
for message in messages.data:
if message.role == “assistant”:
summary += message.content.text
Save the summary to a file
output_summary_path = os.path.join(local_directory, “summary.txt”)
with open(output_summary_path, “w”) as summary_file:
summary_file.write(summary)
print(f"Summary saved to {output_summary_path}")