CORVO-AI commited on
Commit
909eff0
·
verified ·
1 Parent(s): ea53014

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +214 -45
app.py CHANGED
@@ -1,57 +1,226 @@
1
  from flask import Flask, request, jsonify
2
  import requests
 
 
3
 
4
  app = Flask(__name__)
5
 
6
- # Define the URL and headers for the external API
7
- EXTERNAL_API_URL = "https://api.botpress.cloud/v1/cognitive/chat-gpt/query"
8
- HEADERS = {
9
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
10
- "x-bot-id": "fbe047bc-06fb-44c1-9672-342fe1a2e506",
11
- "Content-Type": "application/json",
12
- "Cookie": "pscd=try.botpress.com; _gid=GA1.2.615255121.1735718396; _gcl_au=1.1.2059955793.1735718381; csrf_token_bd9ac21c34b9f0915e733c3e5305d737d0722c1168be7376b889426b5ec2a298=jodj27LFWsi2+szyWXyyeB9kSLWs8KK+JXM6e0HYjk4=; ory_kratos_session=MTczNTY3NTI2MHx5WlZxQnRHZzgwTHlWYzdDemF6aWFuSk4tOXA2eThZS0FZXy1XSnZyZzBWX3EwRVRBUU1hM2E1Mi1RdG9Da0RhYXVWODctQUk0dUlIVFhaZkl1OUpYdmViOGc0RmVRcEtacFhNeG5HYW9kSDNnMlVsbFVQZjdnQmJrUjV2MzJmLWs2Vmh2YnZ4bGl5ZmhGcF9lVkNxSFBIOWN0dS1Pd3MwR2NidzdLOGpwQVZZS3kzRlF4cU1uOHVVSXNoVnhQaXRCRzlkMHlzaWJNRnlVWkp6MnNrMWwwSWtaZGxNc2JONlRMZ3RTaW5XbzI3X1VGb0daNFhVWC1FakR0aWhNTG5EZDc0cGlCc3NtMUVpdGJPZ2hCV3RIQT09fI4khQhSXNtG4vpJU2FiOKNw13-i91YryQW4fmXKuaRU; _hjSession_2931810=eyJpZCI6ImY1ZjMyOWNkLTYwOTEtNDQ0Yi1iZTYyLWQzZGYwZDQzNGE5OSIsImMiOjE3MzU3MTg0MDcwNTIsInMiOjAsInIiOjAsInNiIjowLCJzciI6MCwic2UiOjAsImZzIjoxLCJzcCI6MH0=; _hjSessionUser_2931810=eyJpZCI6ImQ2MGMzYjhkLTlkMjQtNTA0OS1hMzlmLWEzNmI0NzA0NzUxNCIsImNyZWF0ZWQiOjE3MzU3MTg0MDcwNTAsImV4aXN0aW5nIjp0cnVlfQ==; __hstc=59821234.75739411a4d011b2164c4f3d944ecb94.1735718442141.1735718442141.1735718442141.1; hubspotutk=75739411a4d011b2164c4f3d944ecb94; __hssrc=1; intercom-device-id-bjzkw2xf=afd0a36b-b229-44e3-828e-60483c80c10c; _hjSession_3339867=eyJpZCI6ImZlOTE3N2VjLTNjMGQtNGNmMC1iMDU1LTVjMzRjOGMyMzMxZCIsImMiOjE3MzU3MTg1ODM4MDksInMiOjAsInIiOjAsInNiIjowLCJzciI6MCwic2UiOjAsImZzIjoxLCJzcCI6MH0=; _hjSessionUser_3339867=eyJpZCI6IjU4ODlmMTY4LWRkNGEtNTJhZS1hZTUzLWZlYWQwM2ZmMTVjNyIsImNyZWF0ZWQiOjE3MzU3MTg1ODM4MDgsImV4aXN0aW5nIjp0cnVlfQ==; mp_1195923e954ce61d822842b5832047cd_mixpanel=%7B%22distinct_id%22%3A%20%22anonymous%22%2C%22%24device_id%22%3A%20%22anonymous%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%7D; _ga_PCC6TBWJY6=GS1.1.1735718393.1.1.1735719368.0.0.0; _ga=GA1.1.1726154447.1735718383; _ga_HKHSWES9V9=GS1.1.1735718383.1.1.1735719368.22.0.1129077405; _ga_W6YT9YSNLH=GS1.2.1735718403.1.1.1735719369.0.0.0; __hssc=59821234.2.1735718442141; _ga_CYSS87Q508=GS1.2.1735718405.1.1.1735719371.0.0.0; ajs_user_id=anonymous; ajs_anonymous_id=01be9348-6603-4da6-a529-dcdcca3d822d; intercom-session-bjzkw2xf=NGNPa3dQZDFJZW5sV2R6WGd1VnpyUUw0QlNqcHVBL05iOXRVZ04ydEZDTFFhekRqSU01VkFCMWFMclN6eVVUZS0tWkR0LzRwMkQ2MTdod21IcWROS1Rjdz09--dd9958b94533c254b9325ab04bb09ddb2669d9e6", # Replace with actual cookie value
13
- }
14
-
15
- @app.route('/chat', methods=['POST'])
16
- def query():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  try:
18
- # Get the JSON payload from the request
19
- data = request.get_json()
20
- question = data.get('question', '')
21
- history = data.get('history', [])
22
-
23
- # Construct the payload for the external API
24
- payload = {
25
- "prompt": {
26
- "messages": history + [
27
- {"role": "user", "content": question}
28
- ],
29
- "model": "gpt-4o",
30
- "temperature": 0.9,
31
- "signatureVersion": "Jan-2024",
32
- },
33
- "variables": {
34
- "TASK_INPUT": ""
35
- },
36
- "options": {
37
- "origin": "cards/ai-task",
38
- },
39
- "origin": "cards/ai-task",
40
- }
41
-
42
- # Send the POST request to the external API
43
- response = requests.post(EXTERNAL_API_URL, json=payload, headers=HEADERS)
44
-
45
- # Check the response status
46
  if response.status_code == 200:
47
- response_json = response.json()
48
- assistant_content = response_json.get('choices', [{}])[0].get('message', {}).get('content', '')
49
- return jsonify({"success": True, "response": assistant_content})
 
 
 
 
 
 
50
  else:
51
- return jsonify({"success": False, "error": response.text}), response.status_code
52
 
53
  except Exception as e:
54
- return jsonify({"success": False, "error": str(e)}), 500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
 
 
 
56
  if __name__ == "__main__":
57
- app.run(host="0.0.0.0", port=7860)
 
1
  from flask import Flask, request, jsonify
2
  import requests
3
+ import random
4
+ import string
5
 
6
  app = Flask(__name__)
7
 
8
+ # -------------------------------------------------------------------
9
+ # Global variables to hold workspace and bot IDs across requests
10
+ # -------------------------------------------------------------------
11
+ GLOBAL_WORKSPACE_ID = None
12
+ GLOBAL_BOT_ID = None
13
+
14
+
15
+ # -------------------------------------------------------------------
16
+ # Helper functions for random bot/workspace names
17
+ # -------------------------------------------------------------------
18
+ def generate_random_name(length=5):
19
+ return ''.join(random.choices(string.ascii_letters, k=length))
20
+
21
+
22
+ # -------------------------------------------------------------------
23
+ # Functions to create/delete workspaces and bots
24
+ # -------------------------------------------------------------------
25
+ def create_workspace():
26
+ ws_url = "https://api.botpress.cloud/v1/admin/workspaces"
27
+ headers = {
28
+ "User-Agent": "Mozilla/5.0",
29
+ # Replace with your valid cookie below
30
+ "cookie": "pscd=try.botpress.com; ..."
31
+ }
32
+ payload = {"name": generate_random_name()}
33
+ response = requests.post(ws_url, headers=headers, json=payload)
34
+
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
41
+
42
+
43
+ def create_bot(workspace_id):
44
+ bot_url = "https://api.botpress.cloud/v1/admin/bots"
45
+ headers = {
46
+ "User-Agent": "Mozilla/5.0",
47
+ "x-workspace-id": workspace_id,
48
+ # Replace with your valid cookie below
49
+ "cookie": "pscd=try.botpress.com; ..."
50
+ }
51
+ payload = {"name": generate_random_name()}
52
+ response = requests.post(bot_url, headers=headers, json=payload)
53
+
54
+ if response.status_code == 200:
55
+ response_json = response.json()
56
+ bot_id = response_json.get("bot", {}).get("id")
57
+ if not bot_id:
58
+ print("Bot ID not found in the response.")
59
+ return bot_id
60
+ else:
61
+ print(f"Bot creation failed with: {response.status_code}, {response.text}")
62
+ return None
63
+
64
+
65
+ def delete_bot(bot_id, workspace_id):
66
+ url = f"https://api.botpress.cloud/v1/admin/bots/{bot_id}"
67
+ headers = {
68
+ "User-Agent": "Mozilla/5.0",
69
+ "x-workspace-id": workspace_id,
70
+ # Replace with your valid cookie below
71
+ "cookie": "pscd=try.botpress.com; ..."
72
+ }
73
+ return requests.delete(url, headers=headers)
74
+
75
+
76
+ def delete_workspace(workspace_id):
77
+ url = f"https://api.botpress.cloud/v1/admin/workspaces/{workspace_id}"
78
+ headers = {
79
+ "User-Agent": "Mozilla/5.0",
80
+ # Replace with your valid cookie below
81
+ "cookie": "pscd=try.botpress.com; ..."
82
+ }
83
+ return requests.delete(url, headers=headers)
84
+
85
+
86
+ # -------------------------------------------------------------------
87
+ # Main function that calls the Botpress GPT-4 endpoint
88
+ # -------------------------------------------------------------------
89
+ def chat_with_assistant(user_input, chat_history, bot_id, workspace_id):
90
+ """
91
+ Sends the user input and chat history to the Botpress GPT-4 endpoint,
92
+ returns the assistant's response and (possibly updated) bot/workspace IDs.
93
+ """
94
+
95
+ # Prepare the headers
96
+ headers = {
97
+ "User-Agent": "Mozilla/5.0",
98
+ "x-bot-id": bot_id, # existing bot ID (could be None on first try)
99
+ "Content-Type": "application/json",
100
+ # Replace with your valid cookie below
101
+ "Cookie": "pscd=try.botpress.com; ..."
102
+ }
103
+
104
+ # Prepare the payload
105
+ payload = {
106
+ "prompt": {
107
+ "messages": chat_history, # from user request
108
+ "model": "gpt-4o",
109
+ "temperature": 0.9,
110
+ "signatureVersion": "Jan-2024"
111
+ },
112
+ "variables": {
113
+ "TASK_INPUT": ""
114
+ },
115
+ "options": {
116
+ "origin": "cards/ai-task"
117
+ },
118
+ "origin": "cards/ai-task"
119
+ }
120
+
121
+ botpress_url = "https://api.botpress.cloud/v1/cognitive/chat-gpt/query"
122
+
123
+ # Attempt to send the request
124
  try:
125
+ response = requests.post(botpress_url, json=payload, headers=headers)
126
+
127
+ # If successful (200)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  if response.status_code == 200:
129
+ data = response.json()
130
+ assistant_content = data.get('choices', [{}])[0].get('message', {}).get('content', '')
131
+ return assistant_content, bot_id, workspace_id
132
+
133
+ # If we get a 403, it could be because the bot/workspace IDs are invalid/expired
134
+ elif response.status_code == 403:
135
+ raise Exception("Invalid or expired bot ID.")
136
+
137
+ # Other errors
138
  else:
139
+ return f"Error {response.status_code}: {response.text}", bot_id, workspace_id
140
 
141
  except Exception as e:
142
+ # If invalid/expired bot, create new workspace/bot and retry
143
+ if "Invalid or expired bot ID" in str(e):
144
+ # Attempt to delete old IDs if they exist
145
+ if bot_id and workspace_id:
146
+ delete_bot(bot_id, workspace_id)
147
+ delete_workspace(workspace_id)
148
+
149
+ # Create fresh IDs
150
+ new_workspace = create_workspace()
151
+ new_bot = create_bot(new_workspace)
152
+ if not new_workspace or not new_bot:
153
+ return "Failed to regenerate workspace or bot IDs.", None, None
154
+
155
+ # Update headers with the new bot ID
156
+ headers["x-bot-id"] = new_bot
157
+
158
+ # Retry
159
+ retry_response = requests.post(botpress_url, json=payload, headers=headers)
160
+ if retry_response.status_code == 200:
161
+ data = retry_response.json()
162
+ assistant_content = data.get('choices', [{}])[0].get('message', {}).get('content', '')
163
+ return assistant_content, new_bot, new_workspace
164
+ else:
165
+ return f"Error {retry_response.status_code}: {retry_response.text}", new_bot, new_workspace
166
+ else:
167
+ # Other exceptions
168
+ return f"Unexpected error: {str(e)}", bot_id, workspace_id
169
+
170
+
171
+ # -------------------------------------------------------------------
172
+ # Flask Endpoint
173
+ # -------------------------------------------------------------------
174
+ @app.route("/chat", methods=["POST"])
175
+ def chat_endpoint():
176
+ """
177
+ Expects JSON with:
178
+ {
179
+ "user_input": "string",
180
+ "chat_history": [
181
+ {"role": "system", "content": "..."},
182
+ {"role": "user", "content": "..."},
183
+ ...
184
+ ]
185
+ }
186
+ Returns JSON with:
187
+ {
188
+ "assistant_response": "string"
189
+ }
190
+ """
191
+ global GLOBAL_WORKSPACE_ID, GLOBAL_BOT_ID
192
+
193
+ # Parse JSON from request
194
+ data = request.get_json(force=True)
195
+ user_input = data.get("user_input", "")
196
+ chat_history = data.get("chat_history", [])
197
+
198
+ # If we don't yet have a workspace or bot, create them
199
+ if not GLOBAL_WORKSPACE_ID or not GLOBAL_BOT_ID:
200
+ GLOBAL_WORKSPACE_ID = create_workspace()
201
+ GLOBAL_BOT_ID = create_bot(GLOBAL_WORKSPACE_ID)
202
+
203
+ # If creation failed
204
+ if not GLOBAL_WORKSPACE_ID or not GLOBAL_BOT_ID:
205
+ return jsonify({"assistant_response": "Could not create workspace or bot."}), 500
206
+
207
+ # Call our function that interacts with Botpress GPT-4
208
+ assistant_response, updated_bot_id, updated_workspace_id = chat_with_assistant(
209
+ user_input,
210
+ chat_history,
211
+ GLOBAL_BOT_ID,
212
+ GLOBAL_WORKSPACE_ID
213
+ )
214
+
215
+ # Update global IDs if they changed
216
+ GLOBAL_BOT_ID = updated_bot_id
217
+ GLOBAL_WORKSPACE_ID = updated_workspace_id
218
+
219
+ return jsonify({"assistant_response": assistant_response})
220
+
221
 
222
+ # -------------------------------------------------------------------
223
+ # Run the Flask app (example)
224
+ # -------------------------------------------------------------------
225
  if __name__ == "__main__":
226
+ app.run(host="0.0.0.0", port=7860, debug=True)