Bing.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. from __future__ import annotations
  2. import random
  3. import json
  4. import uuid
  5. import time
  6. import asyncio
  7. from urllib import parse
  8. from datetime import datetime, date
  9. from ...typing import AsyncResult, Messages, ImageType, Cookies
  10. from ...image import ImageRequest
  11. from ...errors import ResponseError, ResponseStatusError, RateLimitError
  12. from ...requests import DEFAULT_HEADERS
  13. from ...requests.aiohttp import StreamSession
  14. from ..base_provider import AsyncGeneratorProvider, ProviderModelMixin
  15. from ..helper import get_random_hex
  16. from ..bing.upload_image import upload_image
  17. from ..bing.conversation import Conversation, create_conversation, delete_conversation
  18. from ..needs_auth.BingCreateImages import BingCreateImages
  19. from ... import debug
  20. class Tones:
  21. """
  22. Defines the different tone options for the Bing provider.
  23. """
  24. creative = "Creative"
  25. balanced = "Balanced"
  26. precise = "Precise"
  27. copilot = "Copilot"
  28. class Bing(AsyncGeneratorProvider, ProviderModelMixin):
  29. """
  30. Bing provider for generating responses using the Bing API.
  31. """
  32. label = "Microsoft Copilot in Bing"
  33. url = "https://bing.com/chat"
  34. working = False
  35. supports_message_history = True
  36. default_model = "Balanced"
  37. default_vision_model = "gpt-4-vision"
  38. models = [getattr(Tones, key) for key in Tones.__dict__ if not key.startswith("__")]
  39. @classmethod
  40. def create_async_generator(
  41. cls,
  42. model: str,
  43. messages: Messages,
  44. proxy: str = None,
  45. timeout: int = 900,
  46. api_key: str = None,
  47. cookies: Cookies = None,
  48. tone: str = None,
  49. image: ImageType = None,
  50. web_search: bool = False,
  51. context: str = None,
  52. **kwargs
  53. ) -> AsyncResult:
  54. """
  55. Creates an asynchronous generator for producing responses from Bing.
  56. :param model: The model to use.
  57. :param messages: Messages to process.
  58. :param proxy: Proxy to use for requests.
  59. :param timeout: Timeout for requests.
  60. :param cookies: Cookies for the session.
  61. :param tone: The tone of the response.
  62. :param image: The image type to be used.
  63. :param web_search: Flag to enable or disable web search.
  64. :return: An asynchronous result object.
  65. """
  66. prompt = messages[-1]["content"]
  67. if context is None:
  68. context = create_context(messages[:-1]) if len(messages) > 1 else None
  69. if tone is None:
  70. tone = tone if model.startswith("gpt-4") else model
  71. tone = cls.get_model("" if tone is None else tone)
  72. gpt4_turbo = True if model.startswith("gpt-4-turbo") else False
  73. return stream_generate(
  74. prompt, tone, image, context, cookies, api_key,
  75. proxy, web_search, gpt4_turbo, timeout,
  76. **kwargs
  77. )
  78. def create_context(messages: Messages) -> str:
  79. """
  80. Creates a context string from a list of messages.
  81. :param messages: A list of message dictionaries.
  82. :return: A string representing the context created from the messages.
  83. """
  84. return "".join(
  85. f"[{message['role']}]" + ("(#message)"
  86. if message['role'] != "system"
  87. else "(#additional_instructions)") + f"\n{message['content']}"
  88. for message in messages
  89. ) + "\n\n"
  90. def get_ip_address() -> str:
  91. return f"13.{random.randint(104, 107)}.{random.randint(0, 255)}.{random.randint(0, 255)}"
  92. def get_default_cookies():
  93. #muid = get_random_hex().upper()
  94. sid = get_random_hex().upper()
  95. guid = get_random_hex().upper()
  96. isodate = date.today().isoformat()
  97. timestamp = int(time.time())
  98. zdate = "0001-01-01T00:00:00.0000000"
  99. return {
  100. "_C_Auth": "",
  101. #"MUID": muid,
  102. #"MUIDB": muid,
  103. "_EDGE_S": f"F=1&SID={sid}",
  104. "_EDGE_V": "1",
  105. "SRCHD": "AF=hpcodx",
  106. "SRCHUID": f"V=2&GUID={guid}&dmnchg=1",
  107. "_RwBf": (
  108. f"r=0&ilt=1&ihpd=0&ispd=0&rc=3&rb=0&gb=0&rg=200&pc=0&mtu=0&rbb=0&g=0&cid="
  109. f"&clo=0&v=1&l={isodate}&lft={zdate}&aof=0&ard={zdate}"
  110. f"&rwdbt={zdate}&rwflt={zdate}&o=2&p=&c=&t=0&s={zdate}"
  111. f"&ts={isodate}&rwred=0&wls=&wlb="
  112. "&wle=&ccp=&cpt=&lka=0&lkt=0&aad=0&TH="
  113. ),
  114. '_Rwho': f'u=d&ts={isodate}',
  115. "_SS": f"SID={sid}&R=3&RB=0&GB=0&RG=200&RP=0",
  116. "SRCHUSR": f"DOB={date.today().strftime('%Y%m%d')}&T={timestamp}",
  117. "SRCHHPGUSR": f"HV={int(time.time())}",
  118. "BCP": "AD=1&AL=1&SM=1",
  119. "ipv6": f"hit={timestamp}",
  120. '_C_ETH' : '1',
  121. }
  122. async def create_headers(cookies: Cookies = None, api_key: str = None) -> dict:
  123. if cookies is None:
  124. # import nodriver as uc
  125. # browser = await uc.start(headless=False)
  126. # page = await browser.get(Defaults.home)
  127. # await asyncio.sleep(10)
  128. # cookies = {}
  129. # for c in await page.browser.cookies.get_all():
  130. # if c.domain.endswith(".bing.com"):
  131. # cookies[c.name] = c.value
  132. # user_agent = await page.evaluate("window.navigator.userAgent")
  133. # await page.close()
  134. cookies = get_default_cookies()
  135. if api_key is not None:
  136. cookies["_U"] = api_key
  137. headers = Defaults.headers.copy()
  138. headers["cookie"] = "; ".join(f"{k}={v}" for k, v in cookies.items())
  139. return headers
  140. class Defaults:
  141. """
  142. Default settings and configurations for the Bing provider.
  143. """
  144. delimiter = "\x1e"
  145. # List of allowed message types for Bing responses
  146. allowedMessageTypes = [
  147. "ActionRequest","Chat",
  148. "ConfirmationCard", "Context",
  149. "InternalSearchQuery", #"InternalSearchResult",
  150. #"Disengaged", "InternalLoaderMessage",
  151. "Progress", "RenderCardRequest",
  152. "RenderContentRequest", "AdsQuery",
  153. "SemanticSerp", "GenerateContentQuery",
  154. "SearchQuery", "GeneratedCode",
  155. "InternalTasksMessage"
  156. ]
  157. sliceIds = {
  158. "balanced": [
  159. "supllmnfe","archnewtf",
  160. "stpstream", "stpsig", "vnextvoicecf", "scmcbase", "cmcpupsalltf", "sydtransctrl",
  161. "thdnsrch", "220dcl1s0", "0215wcrwips0", "0305hrthrots0", "0130gpt4t",
  162. "bingfc", "0225unsticky1", "0228scss0",
  163. "defquerycf", "defcontrol", "3022tphpv"
  164. ],
  165. "creative": [
  166. "bgstream", "fltltst2c",
  167. "stpstream", "stpsig", "vnextvoicecf", "cmcpupsalltf", "sydtransctrl",
  168. "0301techgnd", "220dcl1bt15", "0215wcrwip", "0305hrthrot", "0130gpt4t",
  169. "bingfccf", "0225unsticky1", "0228scss0",
  170. "3022tpvs0"
  171. ],
  172. "precise": [
  173. "bgstream", "fltltst2c",
  174. "stpstream", "stpsig", "vnextvoicecf", "cmcpupsalltf", "sydtransctrl",
  175. "0301techgnd", "220dcl1bt15", "0215wcrwip", "0305hrthrot", "0130gpt4t",
  176. "bingfccf", "0225unsticky1", "0228scss0",
  177. "defquerycf", "3022tpvs0"
  178. ],
  179. "copilot": []
  180. }
  181. optionsSets = {
  182. "balanced": {
  183. "default": [
  184. "nlu_direct_response_filter", "deepleo",
  185. "disable_emoji_spoken_text", "responsible_ai_policy_235",
  186. "enablemm", "dv3sugg", "autosave",
  187. "iyxapbing", "iycapbing",
  188. "galileo", "saharagenconv5", "gldcl1p",
  189. "gpt4tmncnp"
  190. ],
  191. "nosearch": [
  192. "nlu_direct_response_filter", "deepleo",
  193. "disable_emoji_spoken_text", "responsible_ai_policy_235",
  194. "enablemm", "dv3sugg", "autosave",
  195. "iyxapbing", "iycapbing",
  196. "galileo", "sunoupsell", "base64filter", "uprv4p1upd",
  197. "hourthrot", "noctprf", "gndlogcf", "nosearchall"
  198. ]
  199. },
  200. "creative": {
  201. "default": [
  202. "nlu_direct_response_filter", "deepleo",
  203. "disable_emoji_spoken_text", "responsible_ai_policy_235",
  204. "enablemm", "dv3sugg",
  205. "iyxapbing", "iycapbing",
  206. "h3imaginative", "techinstgnd", "hourthrot", "clgalileo", "gencontentv3",
  207. "gpt4tmncnp"
  208. ],
  209. "nosearch": [
  210. "nlu_direct_response_filter", "deepleo",
  211. "disable_emoji_spoken_text", "responsible_ai_policy_235",
  212. "enablemm", "dv3sugg", "autosave",
  213. "iyxapbing", "iycapbing",
  214. "h3imaginative", "sunoupsell", "base64filter", "uprv4p1upd",
  215. "hourthrot", "noctprf", "gndlogcf", "nosearchall",
  216. "clgalileo", "nocache", "up4rp14bstcst"
  217. ]
  218. },
  219. "precise": {
  220. "default": [
  221. "nlu_direct_response_filter", "deepleo",
  222. "disable_emoji_spoken_text", "responsible_ai_policy_235",
  223. "enablemm", "dv3sugg",
  224. "iyxapbing", "iycapbing",
  225. "h3precise", "techinstgnd", "hourthrot", "techinstgnd", "hourthrot",
  226. "clgalileo", "gencontentv3"
  227. ],
  228. "nosearch": [
  229. "nlu_direct_response_filter", "deepleo",
  230. "disable_emoji_spoken_text", "responsible_ai_policy_235",
  231. "enablemm", "dv3sugg", "autosave",
  232. "iyxapbing", "iycapbing",
  233. "h3precise", "sunoupsell", "base64filter", "uprv4p1upd",
  234. "hourthrot", "noctprf", "gndlogcf", "nosearchall",
  235. "clgalileo", "nocache", "up4rp14bstcst"
  236. ]
  237. },
  238. "copilot": [
  239. "nlu_direct_response_filter", "deepleo",
  240. "disable_emoji_spoken_text", "responsible_ai_policy_235",
  241. "enablemm", "dv3sugg",
  242. "iyxapbing", "iycapbing",
  243. "h3precise", "clgalileo", "gencontentv3", "prjupy"
  244. ],
  245. }
  246. # Default location settings
  247. location = {
  248. "locale": "en-US", "market": "en-US", "region": "US",
  249. "location":"lat:34.0536909;long:-118.242766;re=1000m;",
  250. "locationHints": [{
  251. "country": "United States", "state": "California", "city": "Los Angeles",
  252. "timezoneoffset": 8, "countryConfidence": 8,
  253. "Center": {"Latitude": 34.0536909, "Longitude": -118.242766},
  254. "RegionType": 2, "SourceType": 1
  255. }],
  256. }
  257. # Default headers for requests
  258. home = "https://www.bing.com/chat?q=Microsoft+Copilot&FORM=hpcodx"
  259. headers = {
  260. **DEFAULT_HEADERS,
  261. "accept": "application/json",
  262. "referer": home,
  263. "x-ms-client-request-id": str(uuid.uuid4()),
  264. "x-ms-useragent": "azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.15.1 OS/Windows",
  265. }
  266. def format_message(msg: dict) -> str:
  267. """
  268. Formats a message dictionary into a JSON string with a delimiter.
  269. :param msg: The message dictionary to format.
  270. :return: A formatted string representation of the message.
  271. """
  272. return json.dumps(msg, ensure_ascii=False) + Defaults.delimiter
  273. def create_message(
  274. conversation: Conversation,
  275. prompt: str,
  276. tone: str,
  277. context: str = None,
  278. image_request: ImageRequest = None,
  279. web_search: bool = False,
  280. gpt4_turbo: bool = False,
  281. new_conversation: bool = True
  282. ) -> str:
  283. """
  284. Creates a message for the Bing API with specified parameters.
  285. :param conversation: The current conversation object.
  286. :param prompt: The user's input prompt.
  287. :param tone: The desired tone for the response.
  288. :param context: Additional context for the prompt.
  289. :param image_request: The image request with the url.
  290. :param web_search: Flag to enable web search.
  291. :param gpt4_turbo: Flag to enable GPT-4 Turbo.
  292. :return: A formatted string message for the Bing API.
  293. """
  294. options_sets = Defaults.optionsSets[tone.lower()]
  295. if not web_search and "nosearch" in options_sets:
  296. options_sets = options_sets["nosearch"]
  297. elif "default" in options_sets:
  298. options_sets = options_sets["default"]
  299. options_sets = options_sets.copy()
  300. if gpt4_turbo:
  301. options_sets.append("dlgpt4t")
  302. request_id = str(uuid.uuid4())
  303. struct = {
  304. "arguments":[{
  305. "source": "cib",
  306. "optionsSets": options_sets,
  307. "allowedMessageTypes": Defaults.allowedMessageTypes,
  308. "sliceIds": Defaults.sliceIds[tone.lower()],
  309. "verbosity": "verbose",
  310. "scenario": "CopilotMicrosoftCom" if tone == Tones.copilot else "SERP",
  311. "plugins": [{"id": "c310c353-b9f0-4d76-ab0d-1dd5e979cf68", "category": 1}] if web_search else [],
  312. "traceId": get_random_hex(40),
  313. "conversationHistoryOptionsSets": ["autosave","savemem","uprofupd","uprofgen"],
  314. "gptId": "copilot",
  315. "isStartOfSession": new_conversation,
  316. "requestId": request_id,
  317. "message":{
  318. **Defaults.location,
  319. "userIpAddress": get_ip_address(),
  320. "timestamp": datetime.now().isoformat(),
  321. "author": "user",
  322. "inputMethod": "Keyboard",
  323. "text": prompt,
  324. "messageType": "Chat",
  325. "requestId": request_id,
  326. "messageId": request_id
  327. },
  328. "tone": "Balanced" if tone == Tones.copilot else tone,
  329. "spokenTextMode": "None",
  330. "conversationId": conversation.conversationId,
  331. "participant": {"id": conversation.clientId}
  332. }],
  333. "invocationId": "0",
  334. "target": "chat",
  335. "type": 4
  336. }
  337. if image_request and image_request.get('imageUrl') and image_request.get('originalImageUrl'):
  338. struct['arguments'][0]['message']['originalImageUrl'] = image_request.get('originalImageUrl')
  339. struct['arguments'][0]['message']['imageUrl'] = image_request.get('imageUrl')
  340. struct['arguments'][0]['experienceType'] = None
  341. struct['arguments'][0]['attachedFileInfo'] = {"fileName": None, "fileType": None}
  342. if context:
  343. struct['arguments'][0]['previousMessages'] = [{
  344. "author": "user",
  345. "description": context,
  346. "contextType": "ClientApp",
  347. "messageType": "Context",
  348. "messageId": "discover-web--page-ping-mriduna-----"
  349. }]
  350. return format_message(struct)
  351. async def stream_generate(
  352. prompt: str,
  353. tone: str,
  354. image: ImageType = None,
  355. context: str = None,
  356. cookies: dict = None,
  357. api_key: str = None,
  358. proxy: str = None,
  359. web_search: bool = False,
  360. gpt4_turbo: bool = False,
  361. timeout: int = 900,
  362. conversation: Conversation = None,
  363. return_conversation: bool = False,
  364. raise_apology: bool = False,
  365. max_retries: int = None,
  366. sleep_retry: int = 15,
  367. **kwargs
  368. ):
  369. """
  370. Asynchronously streams generated responses from the Bing API.
  371. :param prompt: The user's input prompt.
  372. :param tone: The desired tone for the response.
  373. :param image: The image type involved in the response.
  374. :param context: Additional context for the prompt.
  375. :param cookies: Cookies for the session.
  376. :param web_search: Flag to enable web search.
  377. :param gpt4_turbo: Flag to enable GPT-4 Turbo.
  378. :param timeout: Timeout for the request.
  379. :return: An asynchronous generator yielding responses.
  380. """
  381. headers = await create_headers(cookies, api_key)
  382. new_conversation = conversation is None
  383. max_retries = (5 if new_conversation else 0) if max_retries is None else max_retries
  384. first = True
  385. while first or conversation is None:
  386. async with StreamSession(timeout=timeout, proxy=proxy) as session:
  387. first = False
  388. do_read = True
  389. try:
  390. if conversation is None:
  391. conversation = await create_conversation(session, headers, tone)
  392. if return_conversation:
  393. yield conversation
  394. except (ResponseStatusError, RateLimitError) as e:
  395. max_retries -= 1
  396. if max_retries < 1:
  397. raise e
  398. if debug.logging:
  399. print(f"Bing: Retry: {e}")
  400. headers = await create_headers()
  401. await asyncio.sleep(sleep_retry)
  402. continue
  403. image_request = await upload_image(
  404. session,
  405. image,
  406. "Balanced" if tone == Tones.copilot else tone,
  407. headers
  408. ) if image else None
  409. async with session.ws_connect(
  410. 'wss://s.copilot.microsoft.com/sydney/ChatHub'
  411. if tone == "Copilot" else
  412. 'wss://sydney.bing.com/sydney/ChatHub',
  413. autoping=False,
  414. params={'sec_access_token': conversation.conversationSignature},
  415. headers=headers
  416. ) as wss:
  417. await wss.send_str(format_message({'protocol': 'json', 'version': 1}))
  418. await wss.send_str(format_message({"type": 6}))
  419. await wss.receive_str()
  420. await wss.send_str(create_message(
  421. conversation, prompt, tone,
  422. context if new_conversation else None,
  423. image_request, web_search, gpt4_turbo,
  424. new_conversation
  425. ))
  426. response_txt = ''
  427. returned_text = ''
  428. message_id = None
  429. while do_read:
  430. try:
  431. msg = await wss.receive_str()
  432. except TypeError:
  433. continue
  434. objects = msg.split(Defaults.delimiter)
  435. for obj in objects:
  436. if not obj:
  437. continue
  438. try:
  439. response = json.loads(obj)
  440. except ValueError:
  441. continue
  442. if response and response.get('type') == 1 and response['arguments'][0].get('messages'):
  443. message = response['arguments'][0]['messages'][0]
  444. if message_id is not None and message_id != message["messageId"]:
  445. returned_text = ''
  446. message_id = message["messageId"]
  447. image_response = None
  448. if (raise_apology and message['contentOrigin'] == 'Apology'):
  449. raise ResponseError("Apology Response Error")
  450. if 'adaptiveCards' in message:
  451. card = message['adaptiveCards'][0]['body'][0]
  452. if "text" in card:
  453. response_txt = card.get('text')
  454. if message.get('messageType') and "inlines" in card:
  455. inline_txt = card['inlines'][0].get('text')
  456. response_txt += f"{inline_txt}\n"
  457. elif message.get('contentType') == "IMAGE":
  458. prompt = message.get('text')
  459. try:
  460. image_client = BingCreateImages(cookies, proxy, api_key)
  461. image_response = await image_client.create_async(prompt)
  462. except Exception as e:
  463. if debug.logging:
  464. print(f"Bing: Failed to create images: {e}")
  465. image_response = f"\nhttps://www.bing.com/images/create?q={parse.quote(prompt)}"
  466. if response_txt.startswith(returned_text):
  467. new = response_txt[len(returned_text):]
  468. if new not in ("", "\n"):
  469. yield new
  470. returned_text = response_txt
  471. if image_response is not None:
  472. yield image_response
  473. elif response.get('type') == 2:
  474. result = response['item']['result']
  475. do_read = False
  476. if result.get('error'):
  477. max_retries -= 1
  478. if max_retries < 1:
  479. if result["value"] == "CaptchaChallenge":
  480. raise RateLimitError(f"{result['value']}: Use other cookies or/and ip address")
  481. else:
  482. raise RuntimeError(f"{result['value']}: {result['message']}")
  483. if debug.logging:
  484. print(f"Bing: Retry: {result['value']}: {result['message']}")
  485. headers = await create_headers()
  486. conversation = None
  487. await asyncio.sleep(sleep_retry)
  488. break
  489. elif response.get('type') == 3:
  490. do_read = False
  491. break
  492. if conversation is not None:
  493. await delete_conversation(session, conversation, headers)