2023-03-10 10:45:38 -05:00
|
|
|
import aiohttp
|
|
|
|
import json
|
|
|
|
import asyncio
|
|
|
|
from log import getlogger
|
2023-05-29 22:26:39 -04:00
|
|
|
|
2023-03-10 10:45:38 -05:00
|
|
|
# api_endpoint = "http://localhost:3000/conversation"
|
|
|
|
logger = getlogger()
|
|
|
|
|
|
|
|
|
|
|
|
class BingBot:
|
2023-05-29 22:26:39 -04:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
session: aiohttp.ClientSession,
|
|
|
|
bing_api_endpoint: str,
|
|
|
|
jailbreakEnabled: bool = True,
|
|
|
|
):
|
2023-03-10 10:45:38 -05:00
|
|
|
self.data = {
|
2023-05-29 22:26:39 -04:00
|
|
|
"clientOptions.clientToUse": "bing",
|
2023-03-10 10:45:38 -05:00
|
|
|
}
|
|
|
|
self.bing_api_endpoint = bing_api_endpoint
|
|
|
|
|
2023-04-13 09:31:11 -04:00
|
|
|
self.session = session
|
2023-04-09 22:52:18 -04:00
|
|
|
|
2023-03-17 19:20:55 -04:00
|
|
|
self.jailbreakEnabled = jailbreakEnabled
|
|
|
|
|
|
|
|
if self.jailbreakEnabled:
|
2023-05-29 22:26:39 -04:00
|
|
|
self.data["jailbreakConversationId"] = True
|
2023-03-17 19:20:55 -04:00
|
|
|
|
2023-03-10 10:45:38 -05:00
|
|
|
async def ask_bing(self, prompt) -> str:
|
2023-05-29 22:26:39 -04:00
|
|
|
self.data["message"] = prompt
|
2023-04-13 09:31:11 -04:00
|
|
|
max_try = 2
|
2023-04-09 22:52:18 -04:00
|
|
|
while max_try > 0:
|
|
|
|
try:
|
2023-05-29 22:26:39 -04:00
|
|
|
resp = await self.session.post(
|
|
|
|
url=self.bing_api_endpoint, json=self.data, timeout=120
|
|
|
|
)
|
2023-04-09 22:52:18 -04:00
|
|
|
status_code = resp.status
|
|
|
|
body = await resp.read()
|
|
|
|
if not status_code == 200:
|
|
|
|
# print failed reason
|
|
|
|
logger.warning(str(resp.reason))
|
|
|
|
max_try = max_try - 1
|
|
|
|
# print(await resp.text())
|
|
|
|
await asyncio.sleep(2)
|
|
|
|
continue
|
|
|
|
json_body = json.loads(body)
|
|
|
|
if self.jailbreakEnabled:
|
2023-05-29 22:26:39 -04:00
|
|
|
self.data["jailbreakConversationId"] = json_body[
|
|
|
|
"jailbreakConversationId"
|
|
|
|
]
|
|
|
|
self.data["parentMessageId"] = json_body["messageId"]
|
2023-04-09 22:52:18 -04:00
|
|
|
else:
|
2023-05-29 22:26:39 -04:00
|
|
|
self.data["conversationSignature"] = json_body[
|
|
|
|
"conversationSignature"
|
|
|
|
]
|
|
|
|
self.data["conversationId"] = json_body["conversationId"]
|
|
|
|
self.data["clientId"] = json_body["clientId"]
|
|
|
|
self.data["invocationId"] = json_body["invocationId"]
|
|
|
|
return json_body["details"]["adaptiveCards"][0]["body"][0]["text"]
|
2023-04-09 22:52:18 -04:00
|
|
|
except Exception as e:
|
|
|
|
logger.error("Error Exception", exc_info=True)
|
2023-05-29 22:26:39 -04:00
|
|
|
|
2023-04-09 22:52:18 -04:00
|
|
|
return "Error, please retry"
|