CORVO-AI commited on
Commit
1f75665
·
verified ·
1 Parent(s): 3e4bb78

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +139 -42
app.py CHANGED
@@ -6,10 +6,9 @@ import time
6
 
7
  app = Flask(__name__)
8
 
9
-
10
-
11
- GLOBAL_WORKSPACE_ID = "wkspace_01JSP2RQYHY6SFQ95PS0X1RM7C"
12
- GLOBAL_BOT_ID = "e7d787aa-fbc0-40b3-ac7f-e283aae81932"
13
 
14
  # Cookie value used in requests (should be updated with a valid cookie)
15
  AUTH_COOKIE = "pscd=try.botpress.com; _hjSessionUser_2931810=eyJpZCI6ImQ2MGMzYjhkLTlkMjQtNTA0OS1hMzlmLWEzNmI0NzA0NzUxNCIsImNyZWF0ZWQiOjE3MzU3MTg0MDcwNTAsImV4aXN0aW5nIjp0cnVlfQ==; hubspotutk=75739411a4d011b2164c4f3d944ecb94; intercom-device-id-bjzkw2xf=afd0a36b-b229-44e3-828e-60483c80c10c; _hjSessionUser_3339867=eyJpZCI6IjU4ODlmMTY4LWRkNGEtNTJhZS1hZTUzLWZlYWQwM2ZmMTVjNyIsImNyZWF0ZWQiOjE3MzU3MTg1ODM4MDgsImV4aXN0aW5nIjp0cnVlfQ==; 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; _gid=GA1.2.1287628494.1744029890; _hjSession_2931810=eyJpZCI6IjYxMzliNWFhLTZkZDMtNDQxNy1hODliLTJkMjI3ZjhjMmZkZCIsImMiOjE3NDQwMjk4OTk5NzksInMiOjAsInIiOjAsInNiIjowLCJzciI6MCwic2UiOjAsImZzIjowLCJzcCI6MX0=; __hstc=59821234.75739411a4d011b2164c4f3d944ecb94.1735718442141.1743857941488.1744029903713.64; __hssrc=1; csrf_token_bd9ac21c34b9f0915e733c3e5305d737d0722c1168be7376b889426b5ec2a298=bh2jkV1V4U780wKDgoj+CN2zFBwUjPdw4PdorGkX/jA=; ory_kratos_session=MTc0NDAyOTk1OHwxWng4S0ZiNVVLblNRWldzUU9WWVVTRlVwU053aFBTOGZOa3ZBenJBQzdRejIydkc0YTJXZFVsVllvU1diNk9lQlQ1NTJtT2dJbWhDeWRDeU5TVmViNjhNclBPRDBZeFdrY3k3emh5dmlscE8wNmFLcENLLWhhbGJvblMwbUNPaUF3Y29mQ0ZKQld0ajkxeVA3YzhNWDJfaFhwRnp2LUF4VGVxSV92Yk5zTHBQT2x3X2hPZGpPUlpDOHBMTWQyeGRqeUJVTjhPRldTS09XeVA0UUswSDFyRWZLOUNFTkZwdllMT2NMUkN1dlRHcVcxUU9nbEFMaV96RU1Ea1pVbWc5SjAzdU82RGpSMk1LdHY0VlYxZHE0UT09fI-_ev3SlBoRdguqdHUF842Ku0_AZ9rX7GxVN7rV9NHs; ajs_user_id=d403ad7b-ea73-4d29-b977-5fd95afd585c; ajs_anonymous_id=cda6139d-cb82-4906-bfac-adaea115b097; _ga=GA1.1.1726154447.1735718383; _ga_W6YT9YSNLH=GS1.2.1744029893.64.1.1744030016.0.0.0; _ga_CYSS87Q508=GS1.2.1744029892.64.1.1744030016.0.0.0; __hssc=59821234.3.1744029903713; intercom-session-bjzkw2xf=RDY2ZU9VdlNaTHFvNFlwdnNmdXU1azdvVllUREF1UmZtdTNzMlVCZVFUYVpBTVFNSzFyclkwME9ySnZOd21pYTNDbE1DSVk3dk9QVVJrTzJYTHdVMEVMTXhaOTRWZ3AxSVZuYktVTnpYUFE9LS1nczlsRzhzNHdiZ2FmT3B2ZWdQNjVnPT0=--676bd54698c0b37278daa9c30607c884dedaf325; _ga_PCC6TBWJY6=GS1.1.1744029889.84.1.1744030023.0.0.0; _ga_HKHSWES9V9=GS1.1.1744029889.84.1.1744030023.57.0.2075971943"
@@ -18,23 +17,28 @@ AUTH_COOKIE = "pscd=try.botpress.com; _hjSessionUser_2931810=eyJpZCI6ImQ2MGMzYjh
18
  # Helper functions for random bot/workspace names
19
  # -------------------------------------------------------------------
20
  def generate_random_name(length=5):
 
21
  return ''.join(random.choices(string.ascii_letters, k=length))
22
 
23
  # -------------------------------------------------------------------
24
  # Functions to create/delete workspaces and bots
25
  # -------------------------------------------------------------------
26
  def create_workspace():
 
27
  ws_url = "https://api.botpress.cloud/v1/admin/workspaces"
28
  headers = {
29
  "User-Agent": "Mozilla/5.0",
30
  "Cookie": AUTH_COOKIE
31
  }
32
  payload = {"name": generate_random_name()}
 
33
  try:
34
  response = requests.post(ws_url, headers=headers, json=payload)
35
  if response.status_code == 200:
36
  response_json = response.json()
37
- return response_json.get('id')
 
 
38
  else:
39
  print(f"Workspace creation failed with: {response.status_code}, {response.text}")
40
  return None
@@ -44,6 +48,11 @@ def create_workspace():
44
 
45
 
46
  def create_bot(workspace_id):
 
 
 
 
 
47
  bot_url = "https://api.botpress.cloud/v1/admin/bots"
48
  headers = {
49
  "User-Agent": "Mozilla/5.0",
@@ -52,6 +61,7 @@ def create_bot(workspace_id):
52
  "Content-Type": "application/json"
53
  }
54
  payload = {"name": generate_random_name()}
 
55
  try:
56
  response = requests.post(bot_url, headers=headers, json=payload)
57
  if response.status_code == 200:
@@ -59,10 +69,18 @@ def create_bot(workspace_id):
59
  bot_id = response_json.get("bot", {}).get("id")
60
  if not bot_id:
61
  print("Bot ID not found in the response.")
 
 
 
 
62
  # Install integration for the new bot
63
- if bot_id:
64
- install_bot_integration(bot_id, workspace_id)
65
- return bot_id
 
 
 
 
66
  else:
67
  print(f"Bot creation failed with: {response.status_code}, {response.text}")
68
  return None
@@ -73,6 +91,10 @@ def create_bot(workspace_id):
73
 
74
  def install_bot_integration(bot_id, workspace_id):
75
  """Install required integration for the bot to function properly"""
 
 
 
 
76
  url = f"https://api.botpress.cloud/v1/admin/bots/{bot_id}"
77
  headers = {
78
  "User-Agent": "Mozilla/5.0",
@@ -89,6 +111,7 @@ def install_bot_integration(bot_id, workspace_id):
89
  }
90
  }
91
  }
 
92
  try:
93
  response = requests.put(url, headers=headers, json=payload)
94
  if response.status_code == 200:
@@ -103,30 +126,54 @@ def install_bot_integration(bot_id, workspace_id):
103
 
104
 
105
  def delete_bot(bot_id, workspace_id):
 
 
 
 
 
106
  url = f"https://api.botpress.cloud/v1/admin/bots/{bot_id}"
107
  headers = {
108
  "User-Agent": "Mozilla/5.0",
109
  "x-workspace-id": workspace_id,
110
  "Cookie": AUTH_COOKIE
111
  }
 
112
  try:
113
- return requests.delete(url, headers=headers)
 
 
 
 
 
 
114
  except Exception as e:
115
  print(f"Error deleting bot: {str(e)}")
116
- return None
117
 
118
 
119
  def delete_workspace(workspace_id):
 
 
 
 
 
120
  url = f"https://api.botpress.cloud/v1/admin/workspaces/{workspace_id}"
121
  headers = {
122
  "User-Agent": "Mozilla/5.0",
123
  "Cookie": AUTH_COOKIE
124
  }
 
125
  try:
126
- return requests.delete(url, headers=headers)
 
 
 
 
 
 
127
  except Exception as e:
128
  print(f"Error deleting workspace: {str(e)}")
129
- return None
130
 
131
 
132
  # -------------------------------------------------------------------
@@ -145,7 +192,7 @@ def chat_with_assistant(user_input, chat_history, bot_id, workspace_id):
145
  "Cookie": AUTH_COOKIE
146
  }
147
 
148
- # Process chat history into the format expected by the new API
149
  messages = []
150
  system_prompt = ""
151
  for msg in chat_history:
@@ -166,7 +213,7 @@ def chat_with_assistant(user_input, chat_history, bot_id, workspace_id):
166
  "type": "text"
167
  })
168
 
169
- # Prepare the payload for the new API
170
  payload = {
171
  "type": "openai:generateContent",
172
  "input": {
@@ -182,54 +229,100 @@ def chat_with_assistant(user_input, chat_history, bot_id, workspace_id):
182
  }
183
 
184
  botpress_url = "https://api.botpress.cloud/v1/chat/actions"
185
- max_retries = 5
186
- timeout = 60 # seconds
 
 
 
187
 
188
  # Attempt to send the request
189
  for attempt in range(max_retries):
190
  try:
 
191
  response = requests.post(botpress_url, json=payload, headers=headers, timeout=timeout)
192
 
193
  # If successful (200)
194
  if response.status_code == 200:
195
  data = response.json()
196
  assistant_content = data.get('output', {}).get('choices', [{}])[0].get('content', '')
 
197
  return assistant_content, bot_id, workspace_id
198
 
199
- # Handle 403 error specifically
200
  elif response.status_code == 403:
201
- # Step 1: Delete the current bot and workspace
202
- if bot_id and workspace_id:
203
- delete_bot(bot_id, workspace_id)
204
- delete_workspace(workspace_id)
205
-
206
- # Step 2: Create a new workspace and bot
207
- new_workspace_id = create_workspace()
208
- if new_workspace_id:
209
- new_bot_id = create_bot(new_workspace_id)
210
-
211
- # Step 3: Retry with the new IDs
212
- headers["x-bot-id"] = new_bot_id
213
- retry_response = requests.post(botpress_url, json=payload, headers=headers, timeout=timeout)
214
- if retry_response.status_code == 200:
215
- data = retry_response.json()
216
- assistant_content = data.get('output', {}).get('choices', [{}])[0].get('content', '')
217
- return assistant_content, new_bot_id, new_workspace_id
218
- else:
219
- return f"Unable to get a response from the assistant.", new_bot_id, new_workspace_id
220
 
221
  # Any other error status code
222
  else:
223
- raise Exception("Unexpected error occurred.")
 
 
 
 
 
 
 
 
 
 
 
 
 
224
 
225
  except Exception as e:
226
- # If this is not the last attempt, retry the same request
227
  if attempt < max_retries - 1:
228
- time.sleep(2) # Wait before retrying
229
  continue
 
 
 
 
 
 
230
 
231
- # If this is the last attempt, handle it gracefully
232
- return f"Unable to get a response from the assistant after multiple attempts.", bot_id, workspace_id
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
 
234
  # Should not reach here due to the handling in the loop
235
  return "Unable to get a response from the assistant.", bot_id, workspace_id
@@ -264,14 +357,17 @@ def chat_endpoint():
264
 
265
  # If we don't yet have a workspace or bot, create them
266
  if not GLOBAL_WORKSPACE_ID or not GLOBAL_BOT_ID:
 
267
  GLOBAL_WORKSPACE_ID = create_workspace()
268
  if GLOBAL_WORKSPACE_ID:
269
  GLOBAL_BOT_ID = create_bot(GLOBAL_WORKSPACE_ID)
 
270
  # If creation failed
271
  if not GLOBAL_WORKSPACE_ID or not GLOBAL_BOT_ID:
272
  return jsonify({"assistant_response": "I'm currently unavailable. Please try again later."}), 500
273
 
274
  # Call our function that interacts with Botpress API
 
275
  assistant_response, updated_bot_id, updated_workspace_id = chat_with_assistant(
276
  user_input,
277
  chat_history,
@@ -280,7 +376,8 @@ def chat_endpoint():
280
  )
281
 
282
  # Update global IDs if they changed
283
- if updated_bot_id and updated_workspace_id:
 
284
  GLOBAL_BOT_ID = updated_bot_id
285
  GLOBAL_WORKSPACE_ID = updated_workspace_id
286
 
 
6
 
7
  app = Flask(__name__)
8
 
9
+ # Global variables to store workspace and bot IDs
10
+ GLOBAL_WORKSPACE_ID = None
11
+ GLOBAL_BOT_ID = None
 
12
 
13
  # Cookie value used in requests (should be updated with a valid cookie)
14
  AUTH_COOKIE = "pscd=try.botpress.com; _hjSessionUser_2931810=eyJpZCI6ImQ2MGMzYjhkLTlkMjQtNTA0OS1hMzlmLWEzNmI0NzA0NzUxNCIsImNyZWF0ZWQiOjE3MzU3MTg0MDcwNTAsImV4aXN0aW5nIjp0cnVlfQ==; hubspotutk=75739411a4d011b2164c4f3d944ecb94; intercom-device-id-bjzkw2xf=afd0a36b-b229-44e3-828e-60483c80c10c; _hjSessionUser_3339867=eyJpZCI6IjU4ODlmMTY4LWRkNGEtNTJhZS1hZTUzLWZlYWQwM2ZmMTVjNyIsImNyZWF0ZWQiOjE3MzU3MTg1ODM4MDgsImV4aXN0aW5nIjp0cnVlfQ==; 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; _gid=GA1.2.1287628494.1744029890; _hjSession_2931810=eyJpZCI6IjYxMzliNWFhLTZkZDMtNDQxNy1hODliLTJkMjI3ZjhjMmZkZCIsImMiOjE3NDQwMjk4OTk5NzksInMiOjAsInIiOjAsInNiIjowLCJzciI6MCwic2UiOjAsImZzIjowLCJzcCI6MX0=; __hstc=59821234.75739411a4d011b2164c4f3d944ecb94.1735718442141.1743857941488.1744029903713.64; __hssrc=1; csrf_token_bd9ac21c34b9f0915e733c3e5305d737d0722c1168be7376b889426b5ec2a298=bh2jkV1V4U780wKDgoj+CN2zFBwUjPdw4PdorGkX/jA=; ory_kratos_session=MTc0NDAyOTk1OHwxWng4S0ZiNVVLblNRWldzUU9WWVVTRlVwU053aFBTOGZOa3ZBenJBQzdRejIydkc0YTJXZFVsVllvU1diNk9lQlQ1NTJtT2dJbWhDeWRDeU5TVmViNjhNclBPRDBZeFdrY3k3emh5dmlscE8wNmFLcENLLWhhbGJvblMwbUNPaUF3Y29mQ0ZKQld0ajkxeVA3YzhNWDJfaFhwRnp2LUF4VGVxSV92Yk5zTHBQT2x3X2hPZGpPUlpDOHBMTWQyeGRqeUJVTjhPRldTS09XeVA0UUswSDFyRWZLOUNFTkZwdllMT2NMUkN1dlRHcVcxUU9nbEFMaV96RU1Ea1pVbWc5SjAzdU82RGpSMk1LdHY0VlYxZHE0UT09fI-_ev3SlBoRdguqdHUF842Ku0_AZ9rX7GxVN7rV9NHs; ajs_user_id=d403ad7b-ea73-4d29-b977-5fd95afd585c; ajs_anonymous_id=cda6139d-cb82-4906-bfac-adaea115b097; _ga=GA1.1.1726154447.1735718383; _ga_W6YT9YSNLH=GS1.2.1744029893.64.1.1744030016.0.0.0; _ga_CYSS87Q508=GS1.2.1744029892.64.1.1744030016.0.0.0; __hssc=59821234.3.1744029903713; intercom-session-bjzkw2xf=RDY2ZU9VdlNaTHFvNFlwdnNmdXU1azdvVllUREF1UmZtdTNzMlVCZVFUYVpBTVFNSzFyclkwME9ySnZOd21pYTNDbE1DSVk3dk9QVVJrTzJYTHdVMEVMTXhaOTRWZ3AxSVZuYktVTnpYUFE9LS1nczlsRzhzNHdiZ2FmT3B2ZWdQNjVnPT0=--676bd54698c0b37278daa9c30607c884dedaf325; _ga_PCC6TBWJY6=GS1.1.1744029889.84.1.1744030023.0.0.0; _ga_HKHSWES9V9=GS1.1.1744029889.84.1.1744030023.57.0.2075971943"
 
17
  # Helper functions for random bot/workspace names
18
  # -------------------------------------------------------------------
19
  def generate_random_name(length=5):
20
+ """Generate a random name for workspace or bot"""
21
  return ''.join(random.choices(string.ascii_letters, k=length))
22
 
23
  # -------------------------------------------------------------------
24
  # Functions to create/delete workspaces and bots
25
  # -------------------------------------------------------------------
26
  def create_workspace():
27
+ """Create a new workspace and return its ID"""
28
  ws_url = "https://api.botpress.cloud/v1/admin/workspaces"
29
  headers = {
30
  "User-Agent": "Mozilla/5.0",
31
  "Cookie": AUTH_COOKIE
32
  }
33
  payload = {"name": generate_random_name()}
34
+
35
  try:
36
  response = requests.post(ws_url, headers=headers, json=payload)
37
  if response.status_code == 200:
38
  response_json = response.json()
39
+ workspace_id = response_json.get('id')
40
+ print(f"Successfully created workspace: {workspace_id}")
41
+ return workspace_id
42
  else:
43
  print(f"Workspace creation failed with: {response.status_code}, {response.text}")
44
  return None
 
48
 
49
 
50
  def create_bot(workspace_id):
51
+ """Create a new bot in the specified workspace and return its ID"""
52
+ if not workspace_id:
53
+ print("Cannot create bot: No workspace ID provided")
54
+ return None
55
+
56
  bot_url = "https://api.botpress.cloud/v1/admin/bots"
57
  headers = {
58
  "User-Agent": "Mozilla/5.0",
 
61
  "Content-Type": "application/json"
62
  }
63
  payload = {"name": generate_random_name()}
64
+
65
  try:
66
  response = requests.post(bot_url, headers=headers, json=payload)
67
  if response.status_code == 200:
 
69
  bot_id = response_json.get("bot", {}).get("id")
70
  if not bot_id:
71
  print("Bot ID not found in the response.")
72
+ return None
73
+
74
+ print(f"Successfully created bot: {bot_id} in workspace: {workspace_id}")
75
+
76
  # Install integration for the new bot
77
+ integration_success = install_bot_integration(bot_id, workspace_id)
78
+ if integration_success:
79
+ print(f"Successfully installed integration for bot {bot_id}")
80
+ return bot_id
81
+ else:
82
+ print(f"Failed to install integration for bot {bot_id}")
83
+ return bot_id # Still return the bot ID even if integration fails
84
  else:
85
  print(f"Bot creation failed with: {response.status_code}, {response.text}")
86
  return None
 
91
 
92
  def install_bot_integration(bot_id, workspace_id):
93
  """Install required integration for the bot to function properly"""
94
+ if not bot_id or not workspace_id:
95
+ print("Cannot install integration: Missing bot ID or workspace ID")
96
+ return False
97
+
98
  url = f"https://api.botpress.cloud/v1/admin/bots/{bot_id}"
99
  headers = {
100
  "User-Agent": "Mozilla/5.0",
 
111
  }
112
  }
113
  }
114
+
115
  try:
116
  response = requests.put(url, headers=headers, json=payload)
117
  if response.status_code == 200:
 
126
 
127
 
128
  def delete_bot(bot_id, workspace_id):
129
+ """Delete a bot from the specified workspace"""
130
+ if not bot_id or not workspace_id:
131
+ print("Cannot delete bot: Missing bot ID or workspace ID")
132
+ return False
133
+
134
  url = f"https://api.botpress.cloud/v1/admin/bots/{bot_id}"
135
  headers = {
136
  "User-Agent": "Mozilla/5.0",
137
  "x-workspace-id": workspace_id,
138
  "Cookie": AUTH_COOKIE
139
  }
140
+
141
  try:
142
+ response = requests.delete(url, headers=headers)
143
+ if response.status_code in [200, 204]:
144
+ print(f"Successfully deleted bot: {bot_id}")
145
+ return True
146
+ else:
147
+ print(f"Failed to delete bot: {response.status_code}, {response.text}")
148
+ return False
149
  except Exception as e:
150
  print(f"Error deleting bot: {str(e)}")
151
+ return False
152
 
153
 
154
  def delete_workspace(workspace_id):
155
+ """Delete a workspace"""
156
+ if not workspace_id:
157
+ print("Cannot delete workspace: No workspace ID provided")
158
+ return False
159
+
160
  url = f"https://api.botpress.cloud/v1/admin/workspaces/{workspace_id}"
161
  headers = {
162
  "User-Agent": "Mozilla/5.0",
163
  "Cookie": AUTH_COOKIE
164
  }
165
+
166
  try:
167
+ response = requests.delete(url, headers=headers)
168
+ if response.status_code in [200, 204]:
169
+ print(f"Successfully deleted workspace: {workspace_id}")
170
+ return True
171
+ else:
172
+ print(f"Failed to delete workspace: {response.status_code}, {response.text}")
173
+ return False
174
  except Exception as e:
175
  print(f"Error deleting workspace: {str(e)}")
176
+ return False
177
 
178
 
179
  # -------------------------------------------------------------------
 
192
  "Cookie": AUTH_COOKIE
193
  }
194
 
195
+ # Process chat history into the format expected by the API
196
  messages = []
197
  system_prompt = ""
198
  for msg in chat_history:
 
213
  "type": "text"
214
  })
215
 
216
+ # Prepare the payload for the API
217
  payload = {
218
  "type": "openai:generateContent",
219
  "input": {
 
229
  }
230
 
231
  botpress_url = "https://api.botpress.cloud/v1/chat/actions"
232
+ max_retries = 3
233
+ timeout = 120 # Increased timeout for long messages
234
+
235
+ # Flag to track if we need to create new IDs
236
+ need_new_ids = False
237
 
238
  # Attempt to send the request
239
  for attempt in range(max_retries):
240
  try:
241
+ print(f"Attempt {attempt+1}: Sending request to Botpress API with bot_id={bot_id}, workspace_id={workspace_id}")
242
  response = requests.post(botpress_url, json=payload, headers=headers, timeout=timeout)
243
 
244
  # If successful (200)
245
  if response.status_code == 200:
246
  data = response.json()
247
  assistant_content = data.get('output', {}).get('choices', [{}])[0].get('content', '')
248
+ print(f"Successfully received response from Botpress API")
249
  return assistant_content, bot_id, workspace_id
250
 
251
+ # Handle 403 error (authentication/authorization issue)
252
  elif response.status_code == 403:
253
+ print(f"Received 403 error. Need to create new IDs.")
254
+ need_new_ids = True
255
+ break
256
+
257
+ # Handle network errors or timeouts (just retry)
258
+ elif response.status_code in [443, 408, 502, 503, 504]:
259
+ print(f"Received error {response.status_code}. Retrying...")
260
+ time.sleep(3) # Wait before retrying
261
+ continue
 
 
 
 
 
 
 
 
 
 
262
 
263
  # Any other error status code
264
  else:
265
+ print(f"Received unexpected error: {response.status_code}, {response.text}")
266
+ if attempt < max_retries - 1:
267
+ time.sleep(2)
268
+ continue
269
+ else:
270
+ return f"Unable to get a response from the assistant (Error {response.status_code}).", bot_id, workspace_id
271
+
272
+ except requests.exceptions.Timeout:
273
+ print(f"Request timed out. Retrying...")
274
+ if attempt < max_retries - 1:
275
+ time.sleep(2)
276
+ continue
277
+ else:
278
+ return "The assistant is taking too long to respond. Please try again with a shorter message.", bot_id, workspace_id
279
 
280
  except Exception as e:
281
+ print(f"Error during request: {str(e)}")
282
  if attempt < max_retries - 1:
283
+ time.sleep(2)
284
  continue
285
+ else:
286
+ return f"Unable to get a response from the assistant: {str(e)}", bot_id, workspace_id
287
+
288
+ # If we need new IDs, create them and try again
289
+ if need_new_ids:
290
+ print("Creating new workspace and bot IDs...")
291
 
292
+ # First, try to clean up old resources
293
+ if bot_id and workspace_id:
294
+ delete_bot(bot_id, workspace_id)
295
+ delete_workspace(workspace_id)
296
+
297
+ # Create new resources
298
+ new_workspace_id = create_workspace()
299
+ if not new_workspace_id:
300
+ return "Failed to create a new workspace. Please try again later.", bot_id, workspace_id
301
+
302
+ new_bot_id = create_bot(new_workspace_id)
303
+ if not new_bot_id:
304
+ return "Failed to create a new bot. Please try again later.", new_workspace_id, workspace_id
305
+
306
+ # Update headers with new bot ID
307
+ headers["x-bot-id"] = new_bot_id
308
+
309
+ # Try one more time with the new IDs
310
+ try:
311
+ print(f"Retrying with new bot_id={new_bot_id}, workspace_id={new_workspace_id}")
312
+ retry_response = requests.post(botpress_url, json=payload, headers=headers, timeout=timeout)
313
+
314
+ if retry_response.status_code == 200:
315
+ data = retry_response.json()
316
+ assistant_content = data.get('output', {}).get('choices', [{}])[0].get('content', '')
317
+ print(f"Successfully received response with new IDs")
318
+ return assistant_content, new_bot_id, new_workspace_id
319
+ else:
320
+ print(f"Failed with new IDs: {retry_response.status_code}, {retry_response.text}")
321
+ return f"Unable to get a response from the assistant with new credentials.", new_bot_id, new_workspace_id
322
+
323
+ except Exception as e:
324
+ print(f"Error with new IDs: {str(e)}")
325
+ return f"Unable to get a response from the assistant with new credentials: {str(e)}", new_bot_id, new_workspace_id
326
 
327
  # Should not reach here due to the handling in the loop
328
  return "Unable to get a response from the assistant.", bot_id, workspace_id
 
357
 
358
  # If we don't yet have a workspace or bot, create them
359
  if not GLOBAL_WORKSPACE_ID or not GLOBAL_BOT_ID:
360
+ print("No existing IDs found. Creating new workspace and bot...")
361
  GLOBAL_WORKSPACE_ID = create_workspace()
362
  if GLOBAL_WORKSPACE_ID:
363
  GLOBAL_BOT_ID = create_bot(GLOBAL_WORKSPACE_ID)
364
+
365
  # If creation failed
366
  if not GLOBAL_WORKSPACE_ID or not GLOBAL_BOT_ID:
367
  return jsonify({"assistant_response": "I'm currently unavailable. Please try again later."}), 500
368
 
369
  # Call our function that interacts with Botpress API
370
+ print(f"Sending chat request with existing bot_id={GLOBAL_BOT_ID}, workspace_id={GLOBAL_WORKSPACE_ID}")
371
  assistant_response, updated_bot_id, updated_workspace_id = chat_with_assistant(
372
  user_input,
373
  chat_history,
 
376
  )
377
 
378
  # Update global IDs if they changed
379
+ if updated_bot_id != GLOBAL_BOT_ID or updated_workspace_id != GLOBAL_WORKSPACE_ID:
380
+ print(f"Updating global IDs: bot_id={updated_bot_id}, workspace_id={updated_workspace_id}")
381
  GLOBAL_BOT_ID = updated_bot_id
382
  GLOBAL_WORKSPACE_ID = updated_workspace_id
383