Tonic commited on
Commit
7a67fb8
1 Parent(s): 890f2c9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -25
app.py CHANGED
@@ -10,31 +10,46 @@ assistant_id=os.getenv('ASSISTANT_ID')
10
  client = openai.OpenAI(api_key=openai.api_key)
11
 
12
  def ask_openai(question):
13
- thread = client.beta.threads.create()
14
- client.beta.threads.messages.create(
15
- thread_id=thread.id,
16
- role="user",
17
- content=question,
18
- )
19
-
20
- run = client.beta.threads.runs.create(
21
- thread_id=thread.id,
22
- assistant_id=assistant_id
23
- )
24
-
25
- run = client.beta.threads.runs.retrieve(
26
- thread_id=thread.id,
27
- run_id=run.id,
28
- )
29
-
30
- messages = client.beta.threads.messages.list(
31
- thread_id=thread.id,
32
- )
33
- for msg in messages:
34
- if msg.role == 'assistant':
35
- return msg.content[0]['text']['value']
36
-
37
- return "No response."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
  examples = [
40
  ["My Eucalyptus tree is struggling outside in the cold weather in europe"],
 
10
  client = openai.OpenAI(api_key=openai.api_key)
11
 
12
  def ask_openai(question):
13
+ try:
14
+ thread = client.beta.threads.create()
15
+ client.beta.threads.messages.create(
16
+ thread_id=thread.id,
17
+ role="user",
18
+ content=question,
19
+ )
20
+
21
+ run = client.beta.threads.runs.create(
22
+ thread_id=thread.id,
23
+ assistant_id=assistant_id
24
+ )
25
+
26
+ response_received = False
27
+ timeout = 150
28
+ start_time = time.time()
29
+
30
+ while not response_received and time.time() - start_time < timeout:
31
+ run_status = client.beta.threads.runs.retrieve(
32
+ thread_id=thread.id,
33
+ run_id=run.id,
34
+ )
35
+ if run_status.status == 'completed':
36
+ response_received = True
37
+ else:
38
+ time.sleep(4)
39
+
40
+ if not response_received:
41
+ return "Response timed out."
42
+
43
+ messages = client.beta.threads.messages.list(
44
+ thread_id=thread.id,
45
+ )
46
+ for msg in messages:
47
+ if msg.role == 'assistant':
48
+ return msg.content[0]['text']['value']
49
+
50
+ return "No response."
51
+ except Exception as e:
52
+ return f"An error occurred: {str(e)}"
53
 
54
  examples = [
55
  ["My Eucalyptus tree is struggling outside in the cold weather in europe"],