Tonic commited on
Commit
d62df08
Β·
1 Parent(s): 48c7413

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -9
app.py CHANGED
@@ -12,19 +12,20 @@ client = openai.OpenAI(api_key=openai.api_key)
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:
@@ -35,22 +36,30 @@ def ask_openai(question):
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"],
56
  ["My callatea house plant is yellowing."],
 
12
  def ask_openai(question):
13
  try:
14
  thread = client.beta.threads.create()
15
+
16
  client.beta.threads.messages.create(
17
  thread_id=thread.id,
18
  role="user",
19
  content=question,
20
  )
21
+
22
  run = client.beta.threads.runs.create(
23
  thread_id=thread.id,
24
  assistant_id=assistant_id
25
  )
26
 
27
  response_received = False
28
+ timeout = 30 # seconds
29
  start_time = time.time()
30
 
31
  while not response_received and time.time() - start_time < timeout:
 
36
  if run_status.status == 'completed':
37
  response_received = True
38
  else:
39
+ time.sleep(4)
40
 
41
  if not response_received:
42
  return "Response timed out."
43
 
44
+ steps = client.beta.threads.runs.steps.list(
45
  thread_id=thread.id,
46
+ run_id=run.id
47
  )
48
+
49
+ if steps.data:
50
+ last_step = steps.data[-1]
51
+ if last_step.type == 'message_creation':
52
+ message_id = last_step.step_details.message_creation.message_id
53
+ message = client.beta.threads.messages.retrieve(
54
+ thread_id=thread.id,
55
+ message_id=message_id
56
+ )
57
+ return message.content[0]['text']['value']
58
 
59
  return "No response."
60
  except Exception as e:
61
+ return f"An error occurred: {str(e)}"
62
+
63
  examples = [
64
  ["My Eucalyptus tree is struggling outside in the cold weather in europe"],
65
  ["My callatea house plant is yellowing."],