Assistant_API_Math_Tutor / assistant_api.py
Aqdas's picture
Update assistant_api.py
2ad794a
class MathTutor:
def __init__(self):
from openai import OpenAI
import os
self.client = OpenAI(api_key=os.environ['openai_api_key'])
self.my_assistant = self.client.beta.assistants.create(
instructions="You are a personal math tutor. When asked a question, write and run Python code to answer the question.",
name="Math Tutor",
tools=[{"type": "code_interpreter"}],
model="gpt-4-1106-preview",
)
def ask_user(self, query):
self.thread = self.client.beta.threads.create()
message = self.client.beta.threads.messages.create(
thread_id=self.thread.id,
role="user",
content =query
)
self.run = self.client.beta.threads.runs.create(
thread_id=self.thread.id,
assistant_id=self.my_assistant.id,
instructions="Please address the user as Aqdas. The user has a premium account."
)
import time
while True:
run = self.client.beta.threads.runs.retrieve(thread_id=self.thread.id, run_id=self.run.id)
if run.completed_at:
elapsed = run.completed_at - run.created_at
elapsed = time.strftime('%H:%M:%S', time.gmtime(elapsed))
print(f'Run completed in {elapsed}')
break
# print('wait 1 sec')
time.sleep(1)
messages = self.client.beta.threads.messages.list(thread_id=self.thread.id)
last_message = messages.data
my_text = []
for i in range(0,len(last_message)-1):
last_message = messages.data[i]
text = last_message.content[0].text.value
my_text.append(text)
return my_text