File size: 13,131 Bytes
5492f08
20a3b47
909eff0
 
e1d36ec
305d870
5492f08
c895ad2
909eff0
 
 
24fb0b6
 
e1d36ec
 
587f9e6
909eff0
 
 
 
 
 
 
 
 
 
 
 
 
 
e1d36ec
909eff0
 
e1d36ec
 
 
 
 
 
 
 
 
 
909eff0
 
 
 
 
 
e1d36ec
909eff0
e1d36ec
 
909eff0
 
e1d36ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
909eff0
 
 
e1d36ec
 
 
 
 
 
 
 
 
 
 
 
 
67974b7
e1d36ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
909eff0
 
 
e1d36ec
909eff0
e1d36ec
909eff0
e1d36ec
 
 
 
 
909eff0
 
 
 
 
e1d36ec
 
909eff0
e1d36ec
 
 
 
 
909eff0
 
 
e1d36ec
909eff0
 
 
e1d36ec
909eff0
 
 
 
e1d36ec
 
909eff0
e1d36ec
909eff0
 
e1d36ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
909eff0
67974b7
e1d36ec
 
c626b1c
e1d36ec
 
 
c626b1c
 
e1d36ec
 
909eff0
 
e1d36ec
 
 
909eff0
 
e1d36ec
 
 
909eff0
e1d36ec
 
 
 
 
2f62045
587f9e6
 
 
 
 
 
 
 
 
 
 
 
758e870
 
 
 
 
 
 
 
 
587f9e6
 
909eff0
758e870
e1d36ec
 
758e870
 
 
 
e1d36ec
758e870
 
e1d36ec
 
 
909eff0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1d36ec
 
909eff0
 
e1d36ec
909eff0
e1d36ec
909eff0
 
 
 
 
 
 
 
e1d36ec
 
 
909eff0
 
 
5492f08
909eff0
e1d36ec
909eff0
5492f08
909eff0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
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_01JR858H3H7EVBXV887X7HVFG4"
GLOBAL_BOT_ID = "271d3c6c-ad82-45d0-a26d-e2759b0b844e"

# Cookie value used in requests (should be updated with a valid cookie)
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"

# -------------------------------------------------------------------
# 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_01JN7C46RQXD380E6XNH094WHJ": {
                "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": "anthropic:generateContent",
        "input": {
            "model": {
                "id": "claude-3-7-sonnet-20250219"
            },
            "systemPrompt": system_prompt,
            "messages": messages,
            "temperature": 0.2,
            "topP": 0.95,
            "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

            # Handle 403 error specifically
            elif response.status_code == 403:
                # Step 1: Delete the current bot and workspace
                if bot_id and workspace_id:
                    delete_bot(bot_id, workspace_id)
                    delete_workspace(workspace_id)

                # Step 2: Create a new workspace and bot
                new_workspace_id = create_workspace()
                if new_workspace_id:
                    new_bot_id = create_bot(new_workspace_id)

                    # Step 3: Retry with the new IDs
                    headers["x-bot-id"] = new_bot_id
                    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_id, new_workspace_id
                    else:
                        return f"Unable to get a response from the assistant.", new_bot_id, new_workspace_id

            # Any other error status code
            else:
                raise Exception("Unexpected error occurred.")

        except Exception as e:
            # If this is not the last attempt, retry the same request
            if attempt < max_retries - 1:
                time.sleep(2)  # Wait before retrying
                continue

            # If this is the last attempt, handle it gracefully
            return f"Unable to get a response from the assistant after multiple attempts.", bot_id, workspace_id

    # 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
# -------------------------------------------------------------------
@app.route("/chat", methods=["POST"])
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)