Spaces:
Sleeping
Sleeping
| from flask import Flask, request, jsonify | |
| import requests | |
| import random | |
| import string | |
| import time | |
| app = Flask(__name__) | |
| # ------------------------------------------------------------------- | |
| # Global variables to hold workspace and bot IDs across requests | |
| # ------------------------------------------------------------------- | |
| GLOBAL_WORKSPACE_ID = "wkspace_01JMHB3QHE7GRWYTGAQV7KGWYN" | |
| GLOBAL_BOT_ID = "6d6e5198-a4aa-4eb6-9617-67cdde390664" | |
| # Cookie value used in requests (should be updated with a valid cookie) | |
| AUTH_COOKIE = "pscd=try.botpress.com; _gcl_au=1.1.2059955793.1735718381; _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%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; csrf_token_bd9ac21c34b9f0915e733c3e5305d737d0722c1168be7376b889426b5ec2a298=bB0iEVQewW7/y7AXh62+8RwDCxwDgtPnCBtc4A9z1e0=; ory_kratos_session=MTc0MTI2MzIyM3w1SHF2Y0VvczBhS3hDaWFPVmV2WlFsWWJFYmFrNWdVMGpndGZEcnRtcU5JR2NSejNabGFJWDBhRkN6UWJpT21ILWcydHhwb21LdGhfTVNycFkzblRhZGRuSjU0dGdRNHBXUHlqOFZSaFJEZnoxYklxTjRicTVsSlJBRGQ1Vmc2bk1wNVFNRDRLZVJMM2NLQ2RoZENMZUYxZVlhN3FIWUdUaUR1TzNYekJSTUh3NXdMTWktcjNxVTRQSUljSkRsUVVuRTUxM0wyTzctZGVnZXB4cDdhSUc1aERDQ3VpQUFmT05Wd2pXMkFIeS12Ty1kTF9CRzRncTdIcElhMWZlMkFjbmMzcXpEd1NUeTZvMHZVclZUODBPZz09fA6qpO0Au1OyH-59O1SwM5mq5gyMyx_2XrDmAulQo2W7; ajs_user_id=d403ad7b-ea73-4d29-b977-5fd95afd585c; ajs_anonymous_id=cda6139d-cb82-4906-bfac-adaea115b097; __hstc=59821234.75739411a4d011b2164c4f3d944ecb94.1735718442141.1740216976796.1741285217391.50; _ga_CYSS87Q508=GS1.2.1741285205.50.1.1741285220.0.0.0; _ga_W6YT9YSNLH=GS1.2.1741285204.50.1.1741285220.0.0.0; intercom-session-bjzkw2xf=bUhCbWZKY29aeXdtQjF4MmFSdE9LMjFVTTAzMThQNk5CU2RNWXJmcERPL1ZoMllmOUN0M3FYWHluTDArOU1wRkgrZXpGMXhYdHEwY0RxaVdOdVAxdFhyRnFqQ0ZYSnJPd2FTWkRxMUxqR1k9LS16dGtZdnZCSnlWVzZtQmx0OHV2WFdRPT0=--ddd74fc3758dd5ee94b13b08e2a6b5379357b06f; _ga_HKHSWES9V9=GS1.1.1741285202.64.1.1741285223.39.0.1401653535; _hjSession_2931810=eyJpZCI6IjY4MDdjZjIxLTlmMzYtNGNiNy1iZTNhLTZmNDMyMTc0MzZjNyIsImMiOjE3NDEzNzk0OTk3MjgsInMiOjAsInIiOjAsInNiIjowLCJzciI6MCwic2UiOjAsImZzIjowLCJzcCI6MH0=; _gid=GA1.2.270620776.1741379504; _gat_UA-226900660-1=1; _gat_UA-226900660-2=1; _ga=GA1.1.1726154447.1735718383; _ga_PCC6TBWJY6=" | |
| # ------------------------------------------------------------------- | |
| # Helper functions for random bot/workspace names | |
| # ------------------------------------------------------------------- | |
| def generate_random_name(length=5): | |
| return ''.join(random.choices(string.ascii_letters, k=length)) | |
| # ------------------------------------------------------------------- | |
| # Functions to create/delete workspaces and bots | |
| # ------------------------------------------------------------------- | |
| def create_workspace(): | |
| ws_url = "https://api.botpress.cloud/v1/admin/workspaces" | |
| headers = { | |
| "User-Agent": "Mozilla/5.0", | |
| "Cookie": AUTH_COOKIE | |
| } | |
| payload = {"name": generate_random_name()} | |
| try: | |
| response = requests.post(ws_url, headers=headers, json=payload) | |
| if response.status_code == 200: | |
| response_json = response.json() | |
| return response_json.get('id') | |
| else: | |
| print(f"Workspace creation failed with: {response.status_code}, {response.text}") | |
| return None | |
| except Exception as e: | |
| print(f"Error creating workspace: {str(e)}") | |
| return None | |
| def create_bot(workspace_id): | |
| bot_url = "https://api.botpress.cloud/v1/admin/bots" | |
| headers = { | |
| "User-Agent": "Mozilla/5.0", | |
| "x-workspace-id": workspace_id, | |
| "Cookie": AUTH_COOKIE, | |
| "Content-Type": "application/json" | |
| } | |
| payload = {"name": generate_random_name()} | |
| try: | |
| response = requests.post(bot_url, headers=headers, json=payload) | |
| if response.status_code == 200: | |
| response_json = response.json() | |
| bot_id = response_json.get("bot", {}).get("id") | |
| if not bot_id: | |
| print("Bot ID not found in the response.") | |
| # Install integration for the new bot | |
| if bot_id: | |
| install_bot_integration(bot_id, workspace_id) | |
| return bot_id | |
| else: | |
| print(f"Bot creation failed with: {response.status_code}, {response.text}") | |
| return None | |
| except Exception as e: | |
| print(f"Error creating bot: {str(e)}") | |
| return None | |
| def install_bot_integration(bot_id, workspace_id): | |
| """Install required integration for the bot to function properly""" | |
| url = f"https://api.botpress.cloud/v1/admin/bots/{bot_id}" | |
| headers = { | |
| "User-Agent": "Mozilla/5.0", | |
| "Cookie": AUTH_COOKIE, | |
| "Content-Type": "application/json", | |
| "x-bot-id": bot_id, | |
| "x-workspace-id": workspace_id | |
| } | |
| # Integration payload | |
| payload = { | |
| "integrations": { | |
| "intver_01JN7C5S1SHM0EC647KWF8AZ0T": { | |
| "enabled": True | |
| } | |
| } | |
| } | |
| try: | |
| response = requests.put(url, headers=headers, json=payload) | |
| if response.status_code == 200: | |
| print(f"Successfully installed integration for bot {bot_id}") | |
| return True | |
| else: | |
| print(f"Failed to install integration: {response.status_code}, {response.text}") | |
| return False | |
| except Exception as e: | |
| print(f"Error installing integration: {str(e)}") | |
| return False | |
| def delete_bot(bot_id, workspace_id): | |
| url = f"https://api.botpress.cloud/v1/admin/bots/{bot_id}" | |
| headers = { | |
| "User-Agent": "Mozilla/5.0", | |
| "x-workspace-id": workspace_id, | |
| "Cookie": AUTH_COOKIE | |
| } | |
| try: | |
| return requests.delete(url, headers=headers) | |
| except Exception as e: | |
| print(f"Error deleting bot: {str(e)}") | |
| return None | |
| def delete_workspace(workspace_id): | |
| url = f"https://api.botpress.cloud/v1/admin/workspaces/{workspace_id}" | |
| headers = { | |
| "User-Agent": "Mozilla/5.0", | |
| "Cookie": AUTH_COOKIE | |
| } | |
| try: | |
| return requests.delete(url, headers=headers) | |
| except Exception as e: | |
| print(f"Error deleting workspace: {str(e)}") | |
| return None | |
| # ------------------------------------------------------------------- | |
| # Main function that calls the Botpress API endpoint | |
| # ------------------------------------------------------------------- | |
| def chat_with_assistant(user_input, chat_history, bot_id, workspace_id): | |
| """ | |
| Sends the user input and chat history to the Botpress API endpoint, | |
| returns the assistant's response and (possibly updated) bot/workspace IDs. | |
| """ | |
| # Prepare the headers | |
| headers = { | |
| "User-Agent": "Mozilla/5.0", | |
| "x-bot-id": bot_id, | |
| "Content-Type": "application/json", | |
| "Cookie": AUTH_COOKIE | |
| } | |
| # Process chat history into the format expected by the new API | |
| messages = [] | |
| system_prompt = "" | |
| for msg in chat_history: | |
| if msg["role"] == "system": | |
| system_prompt = msg["content"] | |
| else: | |
| messages.append({ | |
| "role": msg["role"], | |
| "content": msg["content"], | |
| "type": "text" | |
| }) | |
| # Add the latest user input if not already in chat history | |
| if user_input and (not messages or messages[-1]["role"] != "user" or messages[-1]["content"] != user_input): | |
| messages.append({ | |
| "role": "user", | |
| "content": user_input, | |
| "type": "text" | |
| }) | |
| # Prepare the payload for the new API | |
| payload = { | |
| "type": "openai:generateContent", | |
| "input": { | |
| "model": { | |
| "id": "o1-2024-12-17" | |
| }, | |
| "systemPrompt": system_prompt, | |
| "messages": messages, | |
| "temperature": 0.75, | |
| "topP": 1, | |
| "debug": False, | |
| } | |
| } | |
| botpress_url = "https://api.botpress.cloud/v1/chat/actions" | |
| max_retries = 5 | |
| timeout = 60 # seconds | |
| # Attempt to send the request | |
| for attempt in range(max_retries): | |
| try: | |
| response = requests.post(botpress_url, json=payload, headers=headers, timeout=timeout) | |
| # If successful (200) | |
| if response.status_code == 200: | |
| data = response.json() | |
| assistant_content = data.get('output', {}).get('choices', [{}])[0].get('content', '') | |
| return assistant_content, bot_id, workspace_id | |
| # Any error status code - treat as invalid bot ID | |
| else: | |
| raise Exception("Invalid or expired bot ID.") | |
| except Exception as e: | |
| # If invalid/expired bot or any other error, regenerate workspace/bot | |
| if attempt == max_retries - 1: # Last attempt | |
| # Attempt to delete old IDs if they exist | |
| if bot_id and workspace_id: | |
| delete_bot(bot_id, workspace_id) | |
| delete_workspace(workspace_id) | |
| # Create fresh IDs | |
| new_workspace = create_workspace() | |
| if new_workspace: | |
| new_bot = create_bot(new_workspace) | |
| if new_bot: | |
| # Update headers with the new bot ID | |
| headers["x-bot-id"] = new_bot | |
| # Retry with new IDs | |
| try: | |
| retry_response = requests.post(botpress_url, json=payload, headers=headers, timeout=timeout) | |
| if retry_response.status_code == 200: | |
| data = retry_response.json() | |
| assistant_content = data.get('output', {}).get('choices', [{}])[0].get('content', '') | |
| return assistant_content, new_bot, new_workspace | |
| else: | |
| return f"Unable to get a response from the assistant.", new_bot, new_workspace | |
| except Exception as retry_error: | |
| return f"Unable to get a response from the assistant.", new_bot, new_workspace | |
| # If we get here, all regeneration attempts failed | |
| return "Unable to get a response from the assistant.", None, None | |
| # Not the last attempt, wait and retry | |
| time.sleep(2) | |
| # Should not reach here due to the handling in the loop | |
| return "Unable to get a response from the assistant.", bot_id, workspace_id | |
| # ------------------------------------------------------------------- | |
| # Flask Endpoint | |
| # ------------------------------------------------------------------- | |
| def chat_endpoint(): | |
| """ | |
| Expects JSON with: | |
| { | |
| "user_input": "string", | |
| "chat_history": [ | |
| {"role": "system", "content": "..."}, | |
| {"role": "user", "content": "..."}, | |
| ... | |
| ] | |
| } | |
| Returns JSON with: | |
| { | |
| "assistant_response": "string" | |
| } | |
| """ | |
| global GLOBAL_WORKSPACE_ID, GLOBAL_BOT_ID | |
| # Parse JSON from request | |
| data = request.get_json(force=True) | |
| user_input = data.get("user_input", "") | |
| chat_history = data.get("chat_history", []) | |
| # If we don't yet have a workspace or bot, create them | |
| if not GLOBAL_WORKSPACE_ID or not GLOBAL_BOT_ID: | |
| GLOBAL_WORKSPACE_ID = create_workspace() | |
| if GLOBAL_WORKSPACE_ID: | |
| GLOBAL_BOT_ID = create_bot(GLOBAL_WORKSPACE_ID) | |
| # If creation failed | |
| if not GLOBAL_WORKSPACE_ID or not GLOBAL_BOT_ID: | |
| return jsonify({"assistant_response": "I'm currently unavailable. Please try again later."}), 500 | |
| # Call our function that interacts with Botpress API | |
| assistant_response, updated_bot_id, updated_workspace_id = chat_with_assistant( | |
| user_input, | |
| chat_history, | |
| GLOBAL_BOT_ID, | |
| GLOBAL_WORKSPACE_ID | |
| ) | |
| # Update global IDs if they changed | |
| if updated_bot_id and updated_workspace_id: | |
| GLOBAL_BOT_ID = updated_bot_id | |
| GLOBAL_WORKSPACE_ID = updated_workspace_id | |
| return jsonify({"assistant_response": assistant_response}) | |
| # ------------------------------------------------------------------- | |
| # Run the Flask app | |
| # ------------------------------------------------------------------- | |
| if __name__ == "__main__": | |
| app.run(host="0.0.0.0", port=7860, debug=True) |