OpenAI Assistants API tutorial
Import relevant libraries
!pip install --upgrade openai
import os
from openai import OpenAI
Environment configuration
OPENAI_API_KEY="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"
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
client = OpenAI()
File Upload
def upload_file(file_path):
# Upload a file with an "assistants" purpose
file_to_upload = client.files.create(
file=open(file_path, "rb"),
purpose='assistants'
)
return file_to_upload
# Path to the file to upload:
transformer_paper_path = "./data/transformer_paper.pdf"
uploaded_file = upload_file(transformer_paper_path)
The above instruction automatically uploads the transformer_paper.pdf to your OpenAI account, in the "files" section.
uploaded_file
Assistant Creation
def create_assistant(assistant_name,
my_instruction,
uploaded_file,
model="gpt-4-1106-preview"):
my_assistant = client.beta.assistants.create(
name = assistant_name,
instructions = my_instruction,
model="gpt-4-1106-preview",
tools=[{"type": "retrieval"}],
file_ids=[uploaded_file.id]
)
return my_assistant
# Create the assistant
inst="You are a polite and expert knowledge retrieval assistant. Use the documents provided as a knowledge base to answer questions"
assistant_name="Scientific Paper Assistant"
my_assistant = create_assistant(assistant_name, inst, uploaded_file)