File size: 7,960 Bytes
7c908ce
 
 
bf42215
7c908ce
bf42215
ef4de38
 
7c908ce
9f7a351
7c908ce
 
 
 
 
 
 
 
 
 
 
 
 
 
ef4de38
7c908ce
 
 
 
 
9f7a351
7c908ce
 
 
 
 
 
 
ef4de38
7c908ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f7a351
7c908ce
 
 
 
 
 
9f7a351
 
 
 
 
bf42215
7c908ce
9f7a351
7c908ce
 
 
9f7a351
7c908ce
ef4de38
7c908ce
 
 
 
 
 
ef4de38
 
 
 
 
 
7c908ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f7a351
bf42215
9f7a351
7c908ce
 
 
 
 
 
 
9f7a351
 
7c908ce
 
 
bf42215
7c908ce
 
 
 
 
 
9f7a351
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c908ce
9f7a351
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c908ce
9f7a351
bf42215
9f7a351
7c908ce
9f7a351
7c908ce
9f7a351
 
 
7c908ce
ef4de38
9f7a351
7c908ce
9f7a351
7c908ce
bf42215
9f7a351
 
 
bf42215
9f7a351
 
 
 
 
 
 
7c908ce
9f7a351
 
 
 
 
bf42215
9f7a351
 
 
 
 
7c908ce
 
af09b23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf42215
9f7a351
af09b23
 
 
9f7a351
 
 
 
af09b23
9f7a351
 
f61bbb2
 
9f7a351
af09b23
bf42215
9f7a351
bf42215
 
af09b23
 
 
 
 
 
bf42215
 
7c908ce
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
"""
Main.py
"""
import asyncio
import json
import os
import uuid

import requests
import websockets.client as websockets


def append_identifier(msg: dict) -> str:
    """
    Appends special character to end of message to identify end of message
    """
    # Convert dict to json string
    return json.dumps(msg) + ""


class ChatHubRequest:
    """
    Request object for ChatHub
    """

    def __init__(
        self,
        conversation_signature: str,
        client_id: str,
        conversation_id: str,
        invocation_id: int = 0,
    ) -> None:
        self.struct: dict

        self.client_id: str = client_id
        self.conversation_id: str = conversation_id
        self.conversation_signature: str = conversation_signature
        self.invocation_id: int = invocation_id

    def update(
        self,
        prompt: str,
    ) -> None:
        """
        Updates request object
        """
        self.struct = {
            "arguments": [
                {
                    "source": "cib",
                    "optionsSets": [
                        "nlu_direct_response_filter",
                        "deepleo",
                        "enable_debug_commands",
                        "disable_emoji_spoken_text",
                        "responsible_ai_policy_235",
                        "enablemm",
                    ],
                    "isStartOfSession": self.invocation_id == 0,
                    "message": {
                        "author": "user",
                        "inputMethod": "Keyboard",
                        "text": prompt,
                        "messageType": "Chat",
                    },
                    "conversationSignature": self.conversation_signature,
                    "participant": {
                        "id": self.client_id,
                    },
                    "conversationId": self.conversation_id,
                },
            ],
            "invocationId": str(self.invocation_id),
            "target": "chat",
            "type": 4,
        }
        self.invocation_id += 1


class Conversation:
    """
    Conversation API
    """

    def __init__(self) -> None:
        self.struct: dict = {
            "conversationId": None,
            "clientId": None,
            "conversationSignature": None,
            "result": {"value": "Success", "message": None},
        }
        # Build request
        headers = {
            "accept": "application/json",
            "accept-encoding": "gzip, deflate, br",
            "accept-language": "en-US,en;q=0.9",
            "content-type": "application/json",
            "sec-ch-ua": '"Microsoft Edge";v="111", "Not(A:Brand";v="8", "Chromium";v="111"',
            "sec-ch-ua-arch": '"x86"',
            "sec-ch-ua-bitness": '"64"',
            "sec-ch-ua-full-version": '"111.0.1652.0"',
            "sec-ch-ua-full-version-list": '"Microsoft Edge";v="111.0.1652.0", "Not(A:Brand";v="8.0.0.0", "Chromium";v="111.0.5551.0"',
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-model": "",
            "sec-ch-ua-platform": '"Linux"',
            "sec-ch-ua-platform-version": '"5.19.0"',
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 Edg/111.0.0.0",
            "x-ms-client-request-id": str(uuid.uuid4()),
            "x-ms-useragent": "azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.10.0 OS/Linuxx86_64",
        }
        # Create cookies
        cookies = {
            "_U": os.environ.get("BING_U"),
        }
        # Send GET request
        response = requests.get(
            "https://www.bing.com/turing/conversation/create",
            headers=headers,
            cookies=cookies,
            timeout=30,
        )
        if response.status_code != 200:
            raise Exception("Authentication failed")
        # Return response
        self.struct = response.json()


class ChatHub:
    """
    Chat API
    """

    def __init__(self) -> None:
        self.wss: websockets.WebSocketClientProtocol
        self.request: ChatHubRequest
        self.loop: bool

    async def init(self, conversation: Conversation) -> None:
        """
        Separate initialization to allow async
        """
        self.wss = await websockets.connect("wss://sydney.bing.com/sydney/ChatHub")
        self.request = ChatHubRequest(
            conversation_signature=conversation.struct["conversationSignature"],
            client_id=conversation.struct["clientId"],
            conversation_id=conversation.struct["conversationId"],
        )
        self.loop = True
        await self.__initial_handshake()

        # Make async ping loop (long running)
        self.task = asyncio.create_task(self.__ping())

    async def ask(self, prompt: str) -> str:
        """
        Ask a question to the bot
        """
        # Construct a ChatHub request
        self.request.update(prompt=prompt)
        # Send request
        await self.wss.send(append_identifier(self.request.struct))
        while True:
            objects = str(await self.wss.recv()).split("")
            for obj in objects:
                if obj is None or obj == "":
                    continue
                response = json.loads(obj)
                if response.get("type") == 2:
                    return response

    async def __initial_handshake(self):
        await self.wss.send(append_identifier({"protocol": "json", "version": 1}))
        await self.wss.send(append_identifier({"type": 6}))

    async def __ping(self):
        while self.loop:
            try:
                await asyncio.sleep(5)
            except asyncio.CancelledError:
                break
            await self.wss.send(append_identifier({"type": 6}))

    async def close(self):
        """
        Close the connection
        """
        self.loop = False
        await self.wss.close()
        self.task.cancel()


class Chatbot:
    """
    Combines everything to make it seamless
    """

    def __init__(self) -> None:
        self.conversation: Conversation
        self.chat_hub: ChatHub

    async def a_start(self) -> None:
        """
        Separate initialization to allow async
        """
        self.conversation = Conversation()
        self.chat_hub = ChatHub()
        await self.chat_hub.init(conversation=self.conversation)

    async def a_ask(self, prompt: str) -> str:
        """
        Ask a question to the bot
        """
        return await self.chat_hub.ask(prompt=prompt)

    async def a_close(self):
        """
        Close the connection
        """
        await self.chat_hub.close()


def get_input(prompt):
    """
    Multi-line input function
    """
    # Display the prompt
    print(prompt, end="")

    # Initialize an empty list to store the input lines
    lines = []

    # Read lines of input until the user enters an empty line
    while True:
        line = input()
        if line == "":
            break
        lines.append(line)

    # Join the lines, separated by newlines, and store the result
    user_input = "\n".join(lines)

    # Return the input
    return user_input


async def main():
    """
    Main function
    """
    print("Initializing...")
    bot = Chatbot()
    await bot.a_start()
    while True:
        prompt = get_input("\nYou:\n")
        if prompt == "!exit":
            break
        print("Bot:")
        print((await bot.a_ask(prompt=prompt))["item"]["messages"][1]["text"])
    await bot.a_close()


if __name__ == "__main__":
    print(
        """
        BingGPT - A demo of reverse engineering the Bing GPT chatbot
        Repo: github.com/acheong08/BingGPT
        By: Antonio Cheong

        Type !exit to exit
        Enter twice to send message
    """
    )
    asyncio.run(main())