Aqdas commited on
Commit
56ddbfa
·
1 Parent(s): 7c185a8

Create assistant_api.py

Browse files
Files changed (1) hide show
  1. assistant_api.py +45 -0
assistant_api.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class MathTutor:
2
+ def __init__(self):
3
+ from openai import OpenAI
4
+ self.client = OpenAI(api_key='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')
5
+
6
+ self.my_assistant = self.client.beta.assistants.create(
7
+ instructions="You are a personal math tutor. When asked a question, write and run Python code to answer the question.",
8
+ name="Math Tutor",
9
+ tools=[{"type": "code_interpreter"}],
10
+ model="gpt-4-1106-preview",
11
+ )
12
+
13
+ def ask_user(self, query):
14
+
15
+ self.thread = self.client.beta.threads.create()
16
+ message = self.client.beta.threads.messages.create(
17
+ thread_id=self.thread.id,
18
+ role="user",
19
+ content =query
20
+ )
21
+ self.run = self.client.beta.threads.runs.create(
22
+ thread_id=self.thread.id,
23
+ assistant_id=self.my_assistant.id,
24
+ instructions="Please address the user as Aqdas. The user has a premium account."
25
+ )
26
+
27
+ import time
28
+ while True:
29
+ run = self.client.beta.threads.runs.retrieve(thread_id=self.thread.id, run_id=self.run.id)
30
+ if run.completed_at:
31
+ elapsed = run.completed_at - run.created_at
32
+ elapsed = time.strftime('%H:%M:%S', time.gmtime(elapsed))
33
+ print(f'Run completed in {elapsed}')
34
+ break
35
+ # print('wait 1 sec')
36
+ time.sleep(1)
37
+
38
+ messages = self.client.beta.threads.messages.list(thread_id=self.thread.id)
39
+ last_message = messages.data
40
+ my_text = []
41
+ for i in range(len(last_message)):
42
+ last_message = messages.data[i]
43
+ text = last_message.content[0].text.value
44
+ my_text.append(text)
45
+ return my_text