CORVO-AI commited on
Commit
43e5fec
·
verified ·
1 Parent(s): 0461c97

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -168
app.py CHANGED
@@ -9,9 +9,10 @@ app = Flask(__name__)
9
  GLOBAL_WORKSPACE_ID = None
10
  GLOBAL_BOT_ID = None
11
 
12
- # Cookie value used in requests (empty for now - should be updated with a valid cookie)
13
  AUTH_COOKIE = "pscd=try.botpress.com; _hjSessionUser_2931810=eyJpZCI6ImQ2MGMzYjhkLTlkMjQtNTA0OS1hMzlmLWEzNmI0NzA0NzUxNCIsImNyZWF0ZWQiOjE3MzU3MTg0MDcwNTAsImV4aXN0aW5nIjp0cnVlfQ==; hubspotutk=75739411a4d011b2164c4f3d944ecb94; intercom-device-id-bjzkw2xf=afd0a36b-b229-44e3-828e-60483c80c10c; _hjSessionUser_3339867=eyJpZCI6IjU4ODlmMTY4LWRkNGEtNTJhZS1hZTUzLWZlYWQwM2ZmMTVjNyIsImNyZWF0ZWQiOjE3MzU3MTg1ODM4MDgsImV4aXN0aW5nIjp0cnVlfQ==; __hstc=59821234.75739411a4d011b2164c4f3d944ecb94.1735718442141.1746194848836.1746538539919.88; mp_1195923e954ce61d822842b5832047cd_mixpanel=%7B%22distinct_id%22%3A%20%22d403ad7b-ea73-4d29-b977-5fd95afd585c%22%2C%22%24device_id%22%3A%20%22d403ad7b-ea73-4d29-b977-5fd95afd585c%22%2C%22%24initial_referrer%22%3A%20%22https%3A%2F%2Fapp.botpress.cloud%2F%22%2C%22%24initial_referring_domain%22%3A%20%22app.botpress.cloud%22%2C%22__mps%22%3A%20%7B%7D%2C%22__mpso%22%3A%20%7B%22%24initial_referrer%22%3A%20%22https%3A%2F%2Fapp.botpress.cloud%2F%22%2C%22%24initial_referring_domain%22%3A%20%22app.botpress.cloud%22%7D%2C%22__mpus%22%3A%20%7B%7D%2C%22__mpa%22%3A%20%7B%7D%2C%22__mpu%22%3A%20%7B%7D%2C%22__mpr%22%3A%20%5B%5D%2C%22__mpap%22%3A%20%5B%5D%2C%22%24user_id%22%3A%20%22d403ad7b-ea73-4d29-b977-5fd95afd585c%22%7D; intercom-session-bjzkw2xf=TTdnZGNWUC9xNXMreE80NXhRZFNZS0pyUEdsbkJRc2JMcXdGZmcveVRPYkxZTmVnVnhqMUhJTWlDcEpVcWljeDZVYVVSblN4YnV5S0xBdWxDd2swQjZiaUZTeWl5M1psRmtoUWJwUU9FSFE9LS1Bay9zNldJTmVhUFdwMFNReFRmcXB3PT0=--68abc5394d7aab99748f3e451637cab5d9152a4c; _ga=GA1.2.1726154447.1735718383; _gid=GA1.2.1619749406.1746821934; _gat_UA-226900660-1=1; _gat_UA-226900660-2=1; _ga_W6YT9YSNLH=GS2.2.s1746821948$o89$g0$t1746821948$j0$l0$h0; _ga_CYSS87Q508=GS2.2.s1746821949$o89$g0$t1746821949$j0$l0$h0; _hjSession_2931810=eyJpZCI6IjA1YTlkMzY3LWNiZWEtNGQ3OC04YzNiLTEzNTFjNjkxYzViZSIsImMiOjE3NDY4MjE5NTU2NjYsInMiOjAsInIiOjAsInNiIjowLCJzciI6MCwic2UiOjAsImZzIjowLCJzcCI6MH0=; _ga_PCC6TBWJY6=GS2.1.s1746821926$o120$g1$t1746821960$j0$l0$h0; _ga_HKHSWES9V9=GS2.1.s1746821929$o120$g1$t1746821960$j29$l0$h193244206; csrf_token_bd9ac21c34b9f0915e733c3e5305d737d0722c1168be7376b889426b5ec2a298=pIDxu4npODUGEpo7JHVQrKZ4GFaa3U+3BpgxaV5hcVw=; ory_kratos_session=MTc0NjgyMjAyOHxfUmdMaVlTQXVfSmxlT1lJSGpyU2FhbjVUTHg0R0ZsQWgtVm00M3pHcXZwVG9yNW1qRDJheUFGaFZvNmFEUVdBOThQR014RjJJbmhUMmhIV1I1ME5UVHZkTDNpMUMtQlRjZ1ZTbE55M19Pb2dHTF9vQlJoSGlBQnRRWUp0M1ZUdnVvcENLeVhOTllWNk1zMk11bFVPOWFrTzJMTTdxMmVteUozVVRDMWE5TVIxbDgzU3dUY2VQaDBRWDN4bDJUVm8yUkZQa19sb09GbzlFZHF2MDFQcVR6bVVWVVpDLXVoQ1lXMEh2LV9Sd2VNZXM1cjM4TGZPVTJqdW5xNTBETTBDYkppU0xNU2xicUk3Z2EyMnFkVmdyQT09fEYiv7pXcfXVnpIFi4JLGgDObQAchyJCoAwGDSkFkoX7; ajs_user_id=d403ad7b-ea73-4d29-b977-5fd95afd585c; ajs_anonymous_id=cda6139d-cb82-4906-bfac-adaea115b097"
14
 
 
15
  # -------------------------------------------------------------------
16
  # Helper functions for random bot/workspace names
17
  # -------------------------------------------------------------------
@@ -176,57 +177,61 @@ def delete_workspace(workspace_id):
176
 
177
 
178
  # -------------------------------------------------------------------
179
- # Main function that calls the Botpress API endpoint
180
  # -------------------------------------------------------------------
181
- def chat_with_assistant(user_input, chat_history, bot_id, workspace_id):
 
182
  """
183
- Sends the user input and chat history to the Botpress API endpoint,
184
- returns the assistant's response and (possibly updated) bot/workspace IDs.
 
 
 
 
 
 
185
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  # Prepare the headers
187
  headers = {
188
  "User-Agent": "Mozilla/5.0",
189
- "x-bot-id": bot_id,
190
  "Content-Type": "application/json",
191
  "Cookie": AUTH_COOKIE
192
  }
193
 
194
- # Process chat history into the format expected by the API
195
- messages = []
196
- system_prompt = ""
197
- for msg in chat_history:
198
- if msg["role"] == "system":
199
- system_prompt = msg["content"]
200
- else:
201
- messages.append({
202
- "role": msg["role"],
203
- "content": msg["content"],
204
- "type": "text"
205
- })
206
-
207
- # Add the latest user input if not already in chat history
208
- if user_input and (not messages or messages[-1]["role"] != "user" or messages[-1]["content"] != user_input):
209
- messages.append({
210
- "role": "user",
211
- "content": user_input,
212
- "type": "text"
213
- })
214
-
215
- # Prepare the payload for the API
216
  payload = {
217
- "type": "openai:generateContent",
218
  "input": {
219
- "model": {
220
- "id": "gpt-4.1-2025-04-14"
221
- },
222
- "systemPrompt": system_prompt,
223
- "messages": messages,
224
- "temperature": 0.9,
225
- "topP": 0.95,
226
- "debug": False,
227
  }
228
  }
229
 
 
 
230
  botpress_url = "https://api.botpress.cloud/v1/chat/actions"
231
  max_retries = 3
232
  timeout = 120 # Increased timeout for long messages
@@ -237,24 +242,22 @@ def chat_with_assistant(user_input, chat_history, bot_id, workspace_id):
237
  # Attempt to send the request
238
  for attempt in range(max_retries):
239
  try:
240
- print(f"Attempt {attempt+1}: Sending request to Botpress API with bot_id={bot_id}, workspace_id={workspace_id}")
241
  response = requests.post(botpress_url, json=payload, headers=headers, timeout=timeout)
242
 
243
  # If successful (200)
244
  if response.status_code == 200:
245
  data = response.json()
246
- assistant_content = data.get('output', {}).get('choices', [{}])[0].get('content', '')
247
- print(f"Successfully received response from Botpress API")
248
- return assistant_content, bot_id, workspace_id
249
 
250
- # Handle 403 error (authentication/authorization issue)
251
- elif response.status_code == 403:
252
- print(f"Received 403 error. Need to create new IDs.")
253
- need_new_ids = True
254
- break
255
 
256
- elif response.status_code == 404:
257
- print(f"Received 404 error. Need to create new IDs.")
 
258
  need_new_ids = True
259
  break
260
 
@@ -271,7 +274,7 @@ def chat_with_assistant(user_input, chat_history, bot_id, workspace_id):
271
  time.sleep(2)
272
  continue
273
  else:
274
- return f"Unable to get a response from the assistant (Error {response.status_code}).", bot_id, workspace_id
275
 
276
  except requests.exceptions.Timeout:
277
  print(f"Request timed out. Retrying...")
@@ -279,7 +282,7 @@ def chat_with_assistant(user_input, chat_history, bot_id, workspace_id):
279
  time.sleep(2)
280
  continue
281
  else:
282
- return "The assistant is taking too long to respond. Please try again with a shorter message.", bot_id, workspace_id
283
 
284
  except Exception as e:
285
  print(f"Error during request: {str(e)}")
@@ -287,25 +290,29 @@ def chat_with_assistant(user_input, chat_history, bot_id, workspace_id):
287
  time.sleep(2)
288
  continue
289
  else:
290
- return f"Unable to get a response from the assistant: {str(e)}", bot_id, workspace_id
291
 
292
  # If we need new IDs, create them and try again
293
  if need_new_ids:
294
  print("Creating new workspace and bot IDs...")
295
 
296
  # First, try to clean up old resources
297
- if bot_id and workspace_id:
298
- delete_bot(bot_id, workspace_id)
299
- delete_workspace(workspace_id)
300
 
301
  # Create new resources
302
  new_workspace_id = create_workspace()
303
  if not new_workspace_id:
304
- return "Failed to create a new workspace. Please try again later.", bot_id, workspace_id
305
 
306
  new_bot_id = create_bot(new_workspace_id)
307
  if not new_bot_id:
308
- return "Failed to create a new bot. Please try again later.", new_workspace_id, workspace_id
 
 
 
 
309
 
310
  # Update headers with new bot ID
311
  headers["x-bot-id"] = new_bot_id
@@ -317,125 +324,22 @@ def chat_with_assistant(user_input, chat_history, bot_id, workspace_id):
317
 
318
  if retry_response.status_code == 200:
319
  data = retry_response.json()
320
- assistant_content = data.get('output', {}).get('choices', [{}])[0].get('content', '')
321
- print(f"Successfully received response with new IDs")
322
- return assistant_content, new_bot_id, new_workspace_id
 
 
 
323
  else:
324
  print(f"Failed with new IDs: {retry_response.status_code}, {retry_response.text}")
325
- return f"Unable to get a response from the assistant with new credentials.", new_bot_id, new_workspace_id
326
 
327
  except Exception as e:
328
  print(f"Error with new IDs: {str(e)}")
329
- return f"Unable to get a response from the assistant with new credentials: {str(e)}", new_bot_id, new_workspace_id
330
 
331
  # Should not reach here due to the handling in the loop
332
- return "Unable to get a response from the assistant.", bot_id, workspace_id
333
-
334
-
335
- def transcribe_audio(audio_url, bot_id):
336
- """Transcribe audio from URL using Botpress API"""
337
- botpress_url = "https://api.botpress.cloud/v1/chat/actions"
338
- headers = {
339
- "User-Agent": "Mozilla/5.0",
340
- "x-bot-id": bot_id,
341
- "Content-Type": "application/json",
342
- "Cookie": AUTH_COOKIE
343
- }
344
-
345
- payload = {
346
- "type": "openai:transcribeAudio",
347
- "input": {
348
- "fileUrl": audio_url,
349
- "language": "",
350
- "prompt": "get all text from this Audio",
351
- "temperature": 0
352
- }
353
- }
354
-
355
- try:
356
- response = requests.post(botpress_url, json=payload, headers=headers, timeout=120)
357
- if response.status_code == 200:
358
- data = response.json()
359
- # Extract text from all segments and join them
360
- segments = data.get('output', {}).get('segments', [])
361
- transcription = " ".join([segment.get('text', '').strip() for segment in segments])
362
- return transcription
363
- else:
364
- print(f"Audio transcription failed: {response.status_code}, {response.text}")
365
- return None
366
- except Exception as e:
367
- print(f"Error during audio transcription: {str(e)}")
368
- return None
369
-
370
-
371
- # -------------------------------------------------------------------
372
- # Flask Endpoint
373
- # -------------------------------------------------------------------
374
- @app.route("/chat", methods=["POST"])
375
- def chat_endpoint():
376
- """
377
- Expects JSON with:
378
- {
379
- "user_input": "string",
380
- "chat_history": [
381
- {"role": "system", "content": "..."},
382
- {"role": "user", "content": "..."},
383
- ...
384
- ],
385
- "audio_url": "string" (optional)
386
- }
387
- Returns JSON with:
388
- {
389
- "assistant_response": "string"
390
- }
391
- """
392
- global GLOBAL_WORKSPACE_ID, GLOBAL_BOT_ID
393
-
394
- # Parse JSON from request
395
- data = request.get_json(force=True)
396
- user_input = data.get("user_input", "")
397
- chat_history = data.get("chat_history", [])
398
- audio_url = data.get("audio_url", "")
399
-
400
- # If we don't yet have a workspace or bot, create them
401
- if not GLOBAL_WORKSPACE_ID or not GLOBAL_BOT_ID:
402
- print("No existing IDs found. Creating new workspace and bot...")
403
- GLOBAL_WORKSPACE_ID = create_workspace()
404
- if GLOBAL_WORKSPACE_ID:
405
- GLOBAL_BOT_ID = create_bot(GLOBAL_WORKSPACE_ID)
406
-
407
- # If creation failed
408
- if not GLOBAL_WORKSPACE_ID or not GLOBAL_BOT_ID:
409
- return jsonify({"assistant_response": "I'm currently unavailable. Please try again later."}), 500
410
-
411
- # If audio URL is provided, transcribe it first
412
- if audio_url:
413
- print(f"Transcribing audio from URL: {audio_url}")
414
- transcription = transcribe_audio(audio_url, GLOBAL_BOT_ID)
415
- if transcription:
416
- # Add transcription to user input
417
- if user_input:
418
- user_input = f"{user_input}\n\nTranscribed audio: {transcription}"
419
- else:
420
- user_input = transcription
421
- print(f"Audio transcription: {transcription}")
422
-
423
- # Call our function that interacts with Botpress API
424
- print(f"Sending chat request with existing bot_id={GLOBAL_BOT_ID}, workspace_id={GLOBAL_WORKSPACE_ID}")
425
- assistant_response, updated_bot_id, updated_workspace_id = chat_with_assistant(
426
- user_input,
427
- chat_history,
428
- GLOBAL_BOT_ID,
429
- GLOBAL_WORKSPACE_ID
430
- )
431
-
432
- # Update global IDs if they changed
433
- if updated_bot_id != GLOBAL_BOT_ID or updated_workspace_id != GLOBAL_WORKSPACE_ID:
434
- print(f"Updating global IDs: bot_id={updated_bot_id}, workspace_id={updated_workspace_id}")
435
- GLOBAL_BOT_ID = updated_bot_id
436
- GLOBAL_WORKSPACE_ID = updated_workspace_id
437
-
438
- return jsonify({"assistant_response": assistant_response})
439
 
440
 
441
  # -------------------------------------------------------------------
 
9
  GLOBAL_WORKSPACE_ID = None
10
  GLOBAL_BOT_ID = None
11
 
12
+ # Empty cookie value (to be filled by the user)
13
  AUTH_COOKIE = "pscd=try.botpress.com; _hjSessionUser_2931810=eyJpZCI6ImQ2MGMzYjhkLTlkMjQtNTA0OS1hMzlmLWEzNmI0NzA0NzUxNCIsImNyZWF0ZWQiOjE3MzU3MTg0MDcwNTAsImV4aXN0aW5nIjp0cnVlfQ==; hubspotutk=75739411a4d011b2164c4f3d944ecb94; intercom-device-id-bjzkw2xf=afd0a36b-b229-44e3-828e-60483c80c10c; _hjSessionUser_3339867=eyJpZCI6IjU4ODlmMTY4LWRkNGEtNTJhZS1hZTUzLWZlYWQwM2ZmMTVjNyIsImNyZWF0ZWQiOjE3MzU3MTg1ODM4MDgsImV4aXN0aW5nIjp0cnVlfQ==; __hstc=59821234.75739411a4d011b2164c4f3d944ecb94.1735718442141.1746194848836.1746538539919.88; mp_1195923e954ce61d822842b5832047cd_mixpanel=%7B%22distinct_id%22%3A%20%22d403ad7b-ea73-4d29-b977-5fd95afd585c%22%2C%22%24device_id%22%3A%20%22d403ad7b-ea73-4d29-b977-5fd95afd585c%22%2C%22%24initial_referrer%22%3A%20%22https%3A%2F%2Fapp.botpress.cloud%2F%22%2C%22%24initial_referring_domain%22%3A%20%22app.botpress.cloud%22%2C%22__mps%22%3A%20%7B%7D%2C%22__mpso%22%3A%20%7B%22%24initial_referrer%22%3A%20%22https%3A%2F%2Fapp.botpress.cloud%2F%22%2C%22%24initial_referring_domain%22%3A%20%22app.botpress.cloud%22%7D%2C%22__mpus%22%3A%20%7B%7D%2C%22__mpa%22%3A%20%7B%7D%2C%22__mpu%22%3A%20%7B%7D%2C%22__mpr%22%3A%20%5B%5D%2C%22__mpap%22%3A%20%5B%5D%2C%22%24user_id%22%3A%20%22d403ad7b-ea73-4d29-b977-5fd95afd585c%22%7D; intercom-session-bjzkw2xf=TTdnZGNWUC9xNXMreE80NXhRZFNZS0pyUEdsbkJRc2JMcXdGZmcveVRPYkxZTmVnVnhqMUhJTWlDcEpVcWljeDZVYVVSblN4YnV5S0xBdWxDd2swQjZiaUZTeWl5M1psRmtoUWJwUU9FSFE9LS1Bay9zNldJTmVhUFdwMFNReFRmcXB3PT0=--68abc5394d7aab99748f3e451637cab5d9152a4c; _ga=GA1.2.1726154447.1735718383; _gid=GA1.2.1619749406.1746821934; _gat_UA-226900660-1=1; _gat_UA-226900660-2=1; _ga_W6YT9YSNLH=GS2.2.s1746821948$o89$g0$t1746821948$j0$l0$h0; _ga_CYSS87Q508=GS2.2.s1746821949$o89$g0$t1746821949$j0$l0$h0; _hjSession_2931810=eyJpZCI6IjA1YTlkMzY3LWNiZWEtNGQ3OC04YzNiLTEzNTFjNjkxYzViZSIsImMiOjE3NDY4MjE5NTU2NjYsInMiOjAsInIiOjAsInNiIjowLCJzciI6MCwic2UiOjAsImZzIjowLCJzcCI6MH0=; _ga_PCC6TBWJY6=GS2.1.s1746821926$o120$g1$t1746821960$j0$l0$h0; _ga_HKHSWES9V9=GS2.1.s1746821929$o120$g1$t1746821960$j29$l0$h193244206; csrf_token_bd9ac21c34b9f0915e733c3e5305d737d0722c1168be7376b889426b5ec2a298=pIDxu4npODUGEpo7JHVQrKZ4GFaa3U+3BpgxaV5hcVw=; ory_kratos_session=MTc0NjgyMjAyOHxfUmdMaVlTQXVfSmxlT1lJSGpyU2FhbjVUTHg0R0ZsQWgtVm00M3pHcXZwVG9yNW1qRDJheUFGaFZvNmFEUVdBOThQR014RjJJbmhUMmhIV1I1ME5UVHZkTDNpMUMtQlRjZ1ZTbE55M19Pb2dHTF9vQlJoSGlBQnRRWUp0M1ZUdnVvcENLeVhOTllWNk1zMk11bFVPOWFrTzJMTTdxMmVteUozVVRDMWE5TVIxbDgzU3dUY2VQaDBRWDN4bDJUVm8yUkZQa19sb09GbzlFZHF2MDFQcVR6bVVWVVpDLXVoQ1lXMEh2LV9Sd2VNZXM1cjM4TGZPVTJqdW5xNTBETTBDYkppU0xNU2xicUk3Z2EyMnFkVmdyQT09fEYiv7pXcfXVnpIFi4JLGgDObQAchyJCoAwGDSkFkoX7; ajs_user_id=d403ad7b-ea73-4d29-b977-5fd95afd585c; ajs_anonymous_id=cda6139d-cb82-4906-bfac-adaea115b097"
14
 
15
+
16
  # -------------------------------------------------------------------
17
  # Helper functions for random bot/workspace names
18
  # -------------------------------------------------------------------
 
177
 
178
 
179
  # -------------------------------------------------------------------
180
+ # Flask Endpoint
181
  # -------------------------------------------------------------------
182
+ @app.route("/chat", methods=["POST"])
183
+ def chat_endpoint():
184
  """
185
+ Expects JSON with:
186
+ {
187
+ "audio_url": "string" (required)
188
+ }
189
+ Returns JSON with:
190
+ {
191
+ "assistant_response": "string" (transcription result)
192
+ }
193
  """
194
+ global GLOBAL_WORKSPACE_ID, GLOBAL_BOT_ID
195
+
196
+ # Parse JSON from request
197
+ data = request.get_json(force=True)
198
+ audio_url = data.get("audio_url", "")
199
+
200
+ if not audio_url:
201
+ return jsonify({"assistant_response": "Error: audio_url is required"}), 400
202
+
203
+ # If we don't yet have a workspace or bot, create them
204
+ if not GLOBAL_WORKSPACE_ID or not GLOBAL_BOT_ID:
205
+ print("No existing IDs found. Creating new workspace and bot...")
206
+ GLOBAL_WORKSPACE_ID = create_workspace()
207
+ if GLOBAL_WORKSPACE_ID:
208
+ GLOBAL_BOT_ID = create_bot(GLOBAL_WORKSPACE_ID)
209
+
210
+ # If creation failed
211
+ if not GLOBAL_WORKSPACE_ID or not GLOBAL_BOT_ID:
212
+ return jsonify({"assistant_response": "I'm currently unavailable. Please try again later."}), 500
213
+
214
  # Prepare the headers
215
  headers = {
216
  "User-Agent": "Mozilla/5.0",
217
+ "x-bot-id": GLOBAL_BOT_ID,
218
  "Content-Type": "application/json",
219
  "Cookie": AUTH_COOKIE
220
  }
221
 
222
+ # Use the transcription payload
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  payload = {
224
+ "type": "openai:transcribeAudio",
225
  "input": {
226
+ "fileUrl": audio_url,
227
+ "language": "",
228
+ "prompt": "get all text from this Audio",
229
+ "temperature": 0
 
 
 
 
230
  }
231
  }
232
 
233
+ print(f"Processing audio transcription request with URL: {audio_url}")
234
+
235
  botpress_url = "https://api.botpress.cloud/v1/chat/actions"
236
  max_retries = 3
237
  timeout = 120 # Increased timeout for long messages
 
242
  # Attempt to send the request
243
  for attempt in range(max_retries):
244
  try:
245
+ print(f"Attempt {attempt+1}: Sending request to Botpress API with bot_id={GLOBAL_BOT_ID}, workspace_id={GLOBAL_WORKSPACE_ID}")
246
  response = requests.post(botpress_url, json=payload, headers=headers, timeout=timeout)
247
 
248
  # If successful (200)
249
  if response.status_code == 200:
250
  data = response.json()
 
 
 
251
 
252
+ # For audio transcription, extract the full text from all segments
253
+ segments = data.get('output', {}).get('segments', [])
254
+ full_transcript = " ".join([segment.get('text', '').strip() for segment in segments])
255
+ print(f"Successfully received transcription from Botpress API")
256
+ return jsonify({"assistant_response": full_transcript})
257
 
258
+ # Handle 403 error (authentication/authorization issue)
259
+ elif response.status_code in [403, 404]:
260
+ print(f"Received {response.status_code} error. Need to create new IDs.")
261
  need_new_ids = True
262
  break
263
 
 
274
  time.sleep(2)
275
  continue
276
  else:
277
+ return jsonify({"assistant_response": f"Unable to get a response (Error {response.status_code})."})
278
 
279
  except requests.exceptions.Timeout:
280
  print(f"Request timed out. Retrying...")
 
282
  time.sleep(2)
283
  continue
284
  else:
285
+ return jsonify({"assistant_response": "The request is taking too long to process. Please try again."})
286
 
287
  except Exception as e:
288
  print(f"Error during request: {str(e)}")
 
290
  time.sleep(2)
291
  continue
292
  else:
293
+ return jsonify({"assistant_response": f"Unable to process the request: {str(e)}"})
294
 
295
  # If we need new IDs, create them and try again
296
  if need_new_ids:
297
  print("Creating new workspace and bot IDs...")
298
 
299
  # First, try to clean up old resources
300
+ if GLOBAL_BOT_ID and GLOBAL_WORKSPACE_ID:
301
+ delete_bot(GLOBAL_BOT_ID, GLOBAL_WORKSPACE_ID)
302
+ delete_workspace(GLOBAL_WORKSPACE_ID)
303
 
304
  # Create new resources
305
  new_workspace_id = create_workspace()
306
  if not new_workspace_id:
307
+ return jsonify({"assistant_response": "Failed to create a new workspace. Please try again later."})
308
 
309
  new_bot_id = create_bot(new_workspace_id)
310
  if not new_bot_id:
311
+ return jsonify({"assistant_response": "Failed to create a new bot. Please try again later."})
312
+
313
+ # Update global IDs
314
+ GLOBAL_BOT_ID = new_bot_id
315
+ GLOBAL_WORKSPACE_ID = new_workspace_id
316
 
317
  # Update headers with new bot ID
318
  headers["x-bot-id"] = new_bot_id
 
324
 
325
  if retry_response.status_code == 200:
326
  data = retry_response.json()
327
+
328
+ # For audio transcription, extract the full text from all segments
329
+ segments = data.get('output', {}).get('segments', [])
330
+ full_transcript = " ".join([segment.get('text', '').strip() for segment in segments])
331
+ print(f"Successfully received transcription with new IDs")
332
+ return jsonify({"assistant_response": full_transcript})
333
  else:
334
  print(f"Failed with new IDs: {retry_response.status_code}, {retry_response.text}")
335
+ return jsonify({"assistant_response": "Unable to get a response with new credentials."})
336
 
337
  except Exception as e:
338
  print(f"Error with new IDs: {str(e)}")
339
+ return jsonify({"assistant_response": f"Unable to get a response with new credentials: {str(e)}"})
340
 
341
  # Should not reach here due to the handling in the loop
342
+ return jsonify({"assistant_response": "Unable to process the request."})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
343
 
344
 
345
  # -------------------------------------------------------------------