2023-09-03 08:26:26 +00:00
|
|
|
from __future__ import annotations
|
2023-07-28 10:07:17 +00:00
|
|
|
|
2023-09-05 15:35:51 +00:00
|
|
|
import random
|
|
|
|
import json
|
2023-10-05 03:13:37 +00:00
|
|
|
import uuid
|
2023-12-18 12:07:00 +00:00
|
|
|
import time
|
2024-03-12 17:45:22 +00:00
|
|
|
import asyncio
|
2024-01-10 09:34:56 +00:00
|
|
|
from urllib import parse
|
2024-04-12 18:58:40 +00:00
|
|
|
from datetime import datetime, date
|
2024-01-10 09:34:56 +00:00
|
|
|
|
2024-03-12 01:06:06 +00:00
|
|
|
from ..typing import AsyncResult, Messages, ImageType, Cookies
|
2024-03-13 04:27:54 +00:00
|
|
|
from ..image import ImageRequest
|
2024-04-21 05:22:59 +00:00
|
|
|
from ..errors import ResponseError, ResponseStatusError, RateLimitError
|
2024-05-07 05:33:22 +00:00
|
|
|
from ..requests import DEFAULT_HEADERS
|
|
|
|
from ..requests.aiohttp import StreamSession
|
2024-03-13 16:52:48 +00:00
|
|
|
from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
|
2024-04-21 05:22:59 +00:00
|
|
|
from .helper import get_random_hex
|
2024-01-10 09:34:56 +00:00
|
|
|
from .bing.upload_image import upload_image
|
|
|
|
from .bing.conversation import Conversation, create_conversation, delete_conversation
|
2024-03-13 04:27:54 +00:00
|
|
|
from .BingCreateImages import BingCreateImages
|
2024-03-12 17:45:22 +00:00
|
|
|
from .. import debug
|
2023-07-28 10:07:17 +00:00
|
|
|
|
2024-01-14 06:45:41 +00:00
|
|
|
class Tones:
|
|
|
|
"""
|
|
|
|
Defines the different tone options for the Bing provider.
|
|
|
|
"""
|
2023-10-02 20:43:36 +00:00
|
|
|
creative = "Creative"
|
|
|
|
balanced = "Balanced"
|
|
|
|
precise = "Precise"
|
2024-03-19 17:48:32 +00:00
|
|
|
copilot = "Copilot"
|
2023-09-03 08:26:26 +00:00
|
|
|
|
2024-03-13 16:52:48 +00:00
|
|
|
class Bing(AsyncGeneratorProvider, ProviderModelMixin):
|
2024-01-14 06:45:41 +00:00
|
|
|
"""
|
|
|
|
Bing provider for generating responses using the Bing API.
|
|
|
|
"""
|
2024-04-12 18:58:40 +00:00
|
|
|
label = "Microsoft Copilot in Bing"
|
2023-10-27 20:59:14 +00:00
|
|
|
url = "https://bing.com/chat"
|
|
|
|
working = True
|
2023-10-24 21:44:44 +00:00
|
|
|
supports_message_history = True
|
2023-10-27 20:59:14 +00:00
|
|
|
supports_gpt_4 = True
|
2024-03-19 17:48:32 +00:00
|
|
|
default_model = "Balanced"
|
2024-04-21 23:27:48 +00:00
|
|
|
default_vision_model = "gpt-4-vision"
|
2024-03-19 17:48:32 +00:00
|
|
|
models = [getattr(Tones, key) for key in Tones.__dict__ if not key.startswith("__")]
|
2024-04-21 23:27:48 +00:00
|
|
|
|
2024-03-13 16:52:48 +00:00
|
|
|
@classmethod
|
2023-08-23 00:16:35 +00:00
|
|
|
def create_async_generator(
|
2024-03-13 16:52:48 +00:00
|
|
|
cls,
|
2023-10-02 20:43:36 +00:00
|
|
|
model: str,
|
2023-10-09 08:22:17 +00:00
|
|
|
messages: Messages,
|
|
|
|
proxy: str = None,
|
2024-01-10 09:41:15 +00:00
|
|
|
timeout: int = 900,
|
2024-04-09 17:19:33 +00:00
|
|
|
api_key: str = None,
|
2024-04-12 18:58:40 +00:00
|
|
|
cookies: Cookies = None,
|
2024-03-13 16:52:48 +00:00
|
|
|
tone: str = None,
|
2024-01-13 14:37:36 +00:00
|
|
|
image: ImageType = None,
|
2023-12-19 20:44:56 +00:00
|
|
|
web_search: bool = False,
|
2024-03-16 17:07:53 +00:00
|
|
|
context: str = None,
|
2023-10-02 20:43:36 +00:00
|
|
|
**kwargs
|
2023-10-09 08:22:17 +00:00
|
|
|
) -> AsyncResult:
|
2024-01-14 06:45:41 +00:00
|
|
|
"""
|
|
|
|
Creates an asynchronous generator for producing responses from Bing.
|
|
|
|
|
|
|
|
:param model: The model to use.
|
|
|
|
:param messages: Messages to process.
|
|
|
|
:param proxy: Proxy to use for requests.
|
|
|
|
:param timeout: Timeout for requests.
|
|
|
|
:param cookies: Cookies for the session.
|
|
|
|
:param tone: The tone of the response.
|
|
|
|
:param image: The image type to be used.
|
|
|
|
:param web_search: Flag to enable or disable web search.
|
|
|
|
:return: An asynchronous result object.
|
|
|
|
"""
|
2024-03-13 16:52:48 +00:00
|
|
|
prompt = messages[-1]["content"]
|
2024-03-16 17:07:53 +00:00
|
|
|
if context is None:
|
|
|
|
context = create_context(messages[:-1]) if len(messages) > 1 else None
|
2024-03-13 16:52:48 +00:00
|
|
|
if tone is None:
|
|
|
|
tone = tone if model.startswith("gpt-4") else model
|
2024-03-19 17:48:32 +00:00
|
|
|
tone = cls.get_model("" if tone is None else tone)
|
2023-12-21 00:03:15 +00:00
|
|
|
gpt4_turbo = True if model.startswith("gpt-4-turbo") else False
|
|
|
|
|
2024-03-13 12:01:22 +00:00
|
|
|
return stream_generate(
|
2024-04-12 19:16:26 +00:00
|
|
|
prompt, tone, image, context, cookies, api_key,
|
2024-03-13 12:01:22 +00:00
|
|
|
proxy, web_search, gpt4_turbo, timeout,
|
|
|
|
**kwargs
|
|
|
|
)
|
2023-07-28 10:07:17 +00:00
|
|
|
|
2024-01-14 06:45:41 +00:00
|
|
|
def create_context(messages: Messages) -> str:
|
|
|
|
"""
|
|
|
|
Creates a context string from a list of messages.
|
|
|
|
|
|
|
|
:param messages: A list of message dictionaries.
|
|
|
|
:return: A string representing the context created from the messages.
|
|
|
|
"""
|
2024-03-13 12:01:22 +00:00
|
|
|
return "".join(
|
2024-03-13 16:52:48 +00:00
|
|
|
f"[{message['role']}]" + ("(#message)"
|
|
|
|
if message['role'] != "system"
|
|
|
|
else "(#additional_instructions)") + f"\n{message['content']}"
|
2023-10-23 07:46:25 +00:00
|
|
|
for message in messages
|
2024-03-13 12:01:22 +00:00
|
|
|
) + "\n\n"
|
2023-07-28 10:07:17 +00:00
|
|
|
|
2024-03-12 01:06:06 +00:00
|
|
|
def get_ip_address() -> str:
|
|
|
|
return f"13.{random.randint(104, 107)}.{random.randint(0, 255)}.{random.randint(0, 255)}"
|
|
|
|
|
2024-03-12 17:45:22 +00:00
|
|
|
def get_default_cookies():
|
2024-04-21 05:22:59 +00:00
|
|
|
#muid = get_random_hex().upper()
|
|
|
|
sid = get_random_hex().upper()
|
|
|
|
guid = get_random_hex().upper()
|
|
|
|
isodate = date.today().isoformat()
|
|
|
|
timestamp = int(time.time())
|
|
|
|
zdate = "0001-01-01T00:00:00.0000000"
|
2024-03-12 17:45:22 +00:00
|
|
|
return {
|
2024-04-21 05:22:59 +00:00
|
|
|
"_C_Auth": "",
|
|
|
|
#"MUID": muid,
|
|
|
|
#"MUIDB": muid,
|
|
|
|
"_EDGE_S": f"F=1&SID={sid}",
|
|
|
|
"_EDGE_V": "1",
|
|
|
|
"SRCHD": "AF=hpcodx",
|
|
|
|
"SRCHUID": f"V=2&GUID={guid}&dmnchg=1",
|
|
|
|
"_RwBf": (
|
|
|
|
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="
|
|
|
|
f"&clo=0&v=1&l={isodate}&lft={zdate}&aof=0&ard={zdate}"
|
|
|
|
f"&rwdbt={zdate}&rwflt={zdate}&o=2&p=&c=&t=0&s={zdate}"
|
|
|
|
f"&ts={isodate}&rwred=0&wls=&wlb="
|
|
|
|
"&wle=&ccp=&cpt=&lka=0&lkt=0&aad=0&TH="
|
|
|
|
),
|
|
|
|
'_Rwho': f'u=d&ts={isodate}',
|
|
|
|
"_SS": f"SID={sid}&R=3&RB=0&GB=0&RG=200&RP=0",
|
|
|
|
"SRCHUSR": f"DOB={date.today().strftime('%Y%m%d')}&T={timestamp}",
|
|
|
|
"SRCHHPGUSR": f"HV={int(time.time())}",
|
|
|
|
"BCP": "AD=1&AL=1&SM=1",
|
|
|
|
"ipv6": f"hit={timestamp}",
|
|
|
|
'_C_ETH' : '1',
|
2024-03-12 17:45:22 +00:00
|
|
|
}
|
|
|
|
|
2024-04-21 05:22:59 +00:00
|
|
|
async def create_headers(cookies: Cookies = None, api_key: str = None) -> dict:
|
2024-03-12 17:45:22 +00:00
|
|
|
if cookies is None:
|
2024-04-21 05:22:59 +00:00
|
|
|
# import nodriver as uc
|
|
|
|
# browser = await uc.start(headless=False)
|
|
|
|
# page = await browser.get(Defaults.home)
|
|
|
|
# await asyncio.sleep(10)
|
|
|
|
# cookies = {}
|
|
|
|
# for c in await page.browser.cookies.get_all():
|
|
|
|
# if c.domain.endswith(".bing.com"):
|
|
|
|
# cookies[c.name] = c.value
|
|
|
|
# user_agent = await page.evaluate("window.navigator.userAgent")
|
|
|
|
# await page.close()
|
2024-03-12 17:45:22 +00:00
|
|
|
cookies = get_default_cookies()
|
2024-04-12 18:58:40 +00:00
|
|
|
if api_key is not None:
|
|
|
|
cookies["_U"] = api_key
|
2024-03-12 17:45:22 +00:00
|
|
|
headers = Defaults.headers.copy()
|
|
|
|
headers["cookie"] = "; ".join(f"{k}={v}" for k, v in cookies.items())
|
|
|
|
return headers
|
|
|
|
|
2023-07-28 10:07:17 +00:00
|
|
|
class Defaults:
|
2024-01-14 06:45:41 +00:00
|
|
|
"""
|
|
|
|
Default settings and configurations for the Bing provider.
|
|
|
|
"""
|
2023-07-28 10:07:17 +00:00
|
|
|
delimiter = "\x1e"
|
|
|
|
|
2024-01-14 06:45:41 +00:00
|
|
|
# List of allowed message types for Bing responses
|
2023-07-28 10:07:17 +00:00
|
|
|
allowedMessageTypes = [
|
2024-03-12 01:06:06 +00:00
|
|
|
"ActionRequest","Chat",
|
|
|
|
"ConfirmationCard", "Context",
|
|
|
|
"InternalSearchQuery", #"InternalSearchResult",
|
2024-03-16 17:07:53 +00:00
|
|
|
#"Disengaged", "InternalLoaderMessage",
|
2024-03-12 01:06:06 +00:00
|
|
|
"Progress", "RenderCardRequest",
|
|
|
|
"RenderContentRequest", "AdsQuery",
|
|
|
|
"SemanticSerp", "GenerateContentQuery",
|
|
|
|
"SearchQuery", "GeneratedCode",
|
|
|
|
"InternalTasksMessage"
|
2023-07-28 10:07:17 +00:00
|
|
|
]
|
|
|
|
|
2024-03-12 01:06:06 +00:00
|
|
|
sliceIds = {
|
2024-03-16 13:40:06 +00:00
|
|
|
"balanced": [
|
2024-03-12 01:06:06 +00:00
|
|
|
"supllmnfe","archnewtf",
|
|
|
|
"stpstream", "stpsig", "vnextvoicecf", "scmcbase", "cmcpupsalltf", "sydtransctrl",
|
|
|
|
"thdnsrch", "220dcl1s0", "0215wcrwips0", "0305hrthrots0", "0130gpt4t",
|
|
|
|
"bingfc", "0225unsticky1", "0228scss0",
|
|
|
|
"defquerycf", "defcontrol", "3022tphpv"
|
|
|
|
],
|
2024-03-16 13:40:06 +00:00
|
|
|
"creative": [
|
2024-03-12 01:06:06 +00:00
|
|
|
"bgstream", "fltltst2c",
|
|
|
|
"stpstream", "stpsig", "vnextvoicecf", "cmcpupsalltf", "sydtransctrl",
|
|
|
|
"0301techgnd", "220dcl1bt15", "0215wcrwip", "0305hrthrot", "0130gpt4t",
|
|
|
|
"bingfccf", "0225unsticky1", "0228scss0",
|
|
|
|
"3022tpvs0"
|
|
|
|
],
|
2024-03-16 13:40:06 +00:00
|
|
|
"precise": [
|
2024-03-12 01:06:06 +00:00
|
|
|
"bgstream", "fltltst2c",
|
|
|
|
"stpstream", "stpsig", "vnextvoicecf", "cmcpupsalltf", "sydtransctrl",
|
|
|
|
"0301techgnd", "220dcl1bt15", "0215wcrwip", "0305hrthrot", "0130gpt4t",
|
|
|
|
"bingfccf", "0225unsticky1", "0228scss0",
|
|
|
|
"defquerycf", "3022tpvs0"
|
|
|
|
],
|
2024-03-16 13:40:06 +00:00
|
|
|
"copilot": []
|
2024-03-12 01:06:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
optionsSets = {
|
2024-03-16 17:07:53 +00:00
|
|
|
"balanced": {
|
|
|
|
"default": [
|
|
|
|
"nlu_direct_response_filter", "deepleo",
|
|
|
|
"disable_emoji_spoken_text", "responsible_ai_policy_235",
|
|
|
|
"enablemm", "dv3sugg", "autosave",
|
|
|
|
"iyxapbing", "iycapbing",
|
|
|
|
"galileo", "saharagenconv5", "gldcl1p",
|
|
|
|
"gpt4tmncnp"
|
|
|
|
],
|
|
|
|
"nosearch": [
|
|
|
|
"nlu_direct_response_filter", "deepleo",
|
|
|
|
"disable_emoji_spoken_text", "responsible_ai_policy_235",
|
|
|
|
"enablemm", "dv3sugg", "autosave",
|
|
|
|
"iyxapbing", "iycapbing",
|
|
|
|
"galileo", "sunoupsell", "base64filter", "uprv4p1upd",
|
|
|
|
"hourthrot", "noctprf", "gndlogcf", "nosearchall"
|
|
|
|
]
|
|
|
|
},
|
|
|
|
"creative": {
|
|
|
|
"default": [
|
|
|
|
"nlu_direct_response_filter", "deepleo",
|
|
|
|
"disable_emoji_spoken_text", "responsible_ai_policy_235",
|
|
|
|
"enablemm", "dv3sugg",
|
|
|
|
"iyxapbing", "iycapbing",
|
|
|
|
"h3imaginative", "techinstgnd", "hourthrot", "clgalileo", "gencontentv3",
|
|
|
|
"gpt4tmncnp"
|
|
|
|
],
|
|
|
|
"nosearch": [
|
|
|
|
"nlu_direct_response_filter", "deepleo",
|
|
|
|
"disable_emoji_spoken_text", "responsible_ai_policy_235",
|
|
|
|
"enablemm", "dv3sugg", "autosave",
|
|
|
|
"iyxapbing", "iycapbing",
|
|
|
|
"h3imaginative", "sunoupsell", "base64filter", "uprv4p1upd",
|
|
|
|
"hourthrot", "noctprf", "gndlogcf", "nosearchall",
|
|
|
|
"clgalileo", "nocache", "up4rp14bstcst"
|
|
|
|
]
|
|
|
|
},
|
|
|
|
"precise": {
|
|
|
|
"default": [
|
|
|
|
"nlu_direct_response_filter", "deepleo",
|
|
|
|
"disable_emoji_spoken_text", "responsible_ai_policy_235",
|
|
|
|
"enablemm", "dv3sugg",
|
|
|
|
"iyxapbing", "iycapbing",
|
|
|
|
"h3precise", "techinstgnd", "hourthrot", "techinstgnd", "hourthrot",
|
|
|
|
"clgalileo", "gencontentv3"
|
|
|
|
],
|
|
|
|
"nosearch": [
|
|
|
|
"nlu_direct_response_filter", "deepleo",
|
|
|
|
"disable_emoji_spoken_text", "responsible_ai_policy_235",
|
|
|
|
"enablemm", "dv3sugg", "autosave",
|
|
|
|
"iyxapbing", "iycapbing",
|
|
|
|
"h3precise", "sunoupsell", "base64filter", "uprv4p1upd",
|
|
|
|
"hourthrot", "noctprf", "gndlogcf", "nosearchall",
|
|
|
|
"clgalileo", "nocache", "up4rp14bstcst"
|
|
|
|
]
|
|
|
|
},
|
2024-03-16 13:40:06 +00:00
|
|
|
"copilot": [
|
|
|
|
"nlu_direct_response_filter", "deepleo",
|
|
|
|
"disable_emoji_spoken_text", "responsible_ai_policy_235",
|
|
|
|
"enablemm", "dv3sugg",
|
|
|
|
"iyxapbing", "iycapbing",
|
|
|
|
"h3precise", "clgalileo", "gencontentv3", "prjupy"
|
|
|
|
],
|
2024-03-12 01:06:06 +00:00
|
|
|
}
|
2023-07-28 10:07:17 +00:00
|
|
|
|
2024-01-14 06:45:41 +00:00
|
|
|
# Default location settings
|
2023-07-28 10:07:17 +00:00
|
|
|
location = {
|
2024-01-14 06:45:41 +00:00
|
|
|
"locale": "en-US", "market": "en-US", "region": "US",
|
2024-03-12 01:06:06 +00:00
|
|
|
"location":"lat:34.0536909;long:-118.242766;re=1000m;",
|
2024-01-14 06:45:41 +00:00
|
|
|
"locationHints": [{
|
|
|
|
"country": "United States", "state": "California", "city": "Los Angeles",
|
|
|
|
"timezoneoffset": 8, "countryConfidence": 8,
|
|
|
|
"Center": {"Latitude": 34.0536909, "Longitude": -118.242766},
|
|
|
|
"RegionType": 2, "SourceType": 1
|
|
|
|
}],
|
2023-07-28 10:07:17 +00:00
|
|
|
}
|
|
|
|
|
2024-01-14 06:45:41 +00:00
|
|
|
# Default headers for requests
|
2024-04-21 05:22:59 +00:00
|
|
|
home = "https://www.bing.com/chat?q=Microsoft+Copilot&FORM=hpcodx"
|
2023-08-21 20:39:57 +00:00
|
|
|
headers = {
|
2024-04-21 05:22:59 +00:00
|
|
|
**DEFAULT_HEADERS,
|
|
|
|
"accept": "application/json",
|
|
|
|
"referer": home,
|
2024-03-12 17:45:22 +00:00
|
|
|
"x-ms-client-request-id": str(uuid.uuid4()),
|
2024-04-21 05:22:59 +00:00
|
|
|
"x-ms-useragent": "azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.15.1 OS/Windows",
|
2024-01-10 09:34:56 +00:00
|
|
|
}
|
2023-08-21 20:39:57 +00:00
|
|
|
|
2023-08-27 16:58:36 +00:00
|
|
|
def format_message(msg: dict) -> str:
|
2024-01-14 06:45:41 +00:00
|
|
|
"""
|
|
|
|
Formats a message dictionary into a JSON string with a delimiter.
|
|
|
|
|
|
|
|
:param msg: The message dictionary to format.
|
|
|
|
:return: A formatted string representation of the message.
|
|
|
|
"""
|
2023-08-27 16:58:36 +00:00
|
|
|
return json.dumps(msg, ensure_ascii=False) + Defaults.delimiter
|
2023-08-21 20:39:57 +00:00
|
|
|
|
2024-01-10 09:34:56 +00:00
|
|
|
def create_message(
|
|
|
|
conversation: Conversation,
|
|
|
|
prompt: str,
|
|
|
|
tone: str,
|
|
|
|
context: str = None,
|
2024-01-26 06:54:13 +00:00
|
|
|
image_request: ImageRequest = None,
|
2024-01-10 09:34:56 +00:00
|
|
|
web_search: bool = False,
|
2024-03-16 17:07:53 +00:00
|
|
|
gpt4_turbo: bool = False,
|
|
|
|
new_conversation: bool = True
|
2024-01-10 09:34:56 +00:00
|
|
|
) -> str:
|
2024-01-14 06:45:41 +00:00
|
|
|
"""
|
|
|
|
Creates a message for the Bing API with specified parameters.
|
|
|
|
|
|
|
|
:param conversation: The current conversation object.
|
|
|
|
:param prompt: The user's input prompt.
|
|
|
|
:param tone: The desired tone for the response.
|
|
|
|
:param context: Additional context for the prompt.
|
2024-01-26 06:54:13 +00:00
|
|
|
:param image_request: The image request with the url.
|
2024-01-14 06:45:41 +00:00
|
|
|
:param web_search: Flag to enable web search.
|
|
|
|
:param gpt4_turbo: Flag to enable GPT-4 Turbo.
|
|
|
|
:return: A formatted string message for the Bing API.
|
|
|
|
"""
|
|
|
|
|
2024-03-19 17:52:17 +00:00
|
|
|
options_sets = Defaults.optionsSets[tone.lower()]
|
2024-03-16 17:07:53 +00:00
|
|
|
if not web_search and "nosearch" in options_sets:
|
|
|
|
options_sets = options_sets["nosearch"]
|
|
|
|
elif "default" in options_sets:
|
|
|
|
options_sets = options_sets["default"]
|
|
|
|
options_sets = options_sets.copy()
|
2023-12-21 00:03:15 +00:00
|
|
|
if gpt4_turbo:
|
|
|
|
options_sets.append("dlgpt4t")
|
2024-01-14 06:45:41 +00:00
|
|
|
|
2023-10-05 03:13:37 +00:00
|
|
|
request_id = str(uuid.uuid4())
|
2023-08-21 20:39:57 +00:00
|
|
|
struct = {
|
2024-03-12 01:06:06 +00:00
|
|
|
"arguments":[{
|
|
|
|
"source": "cib",
|
2024-03-16 17:07:53 +00:00
|
|
|
"optionsSets": options_sets,
|
2024-03-12 01:06:06 +00:00
|
|
|
"allowedMessageTypes": Defaults.allowedMessageTypes,
|
2024-03-19 17:52:17 +00:00
|
|
|
"sliceIds": Defaults.sliceIds[tone.lower()],
|
2024-01-14 06:45:41 +00:00
|
|
|
"verbosity": "verbose",
|
2024-03-19 17:48:32 +00:00
|
|
|
"scenario": "CopilotMicrosoftCom" if tone == Tones.copilot else "SERP",
|
2024-01-14 06:45:41 +00:00
|
|
|
"plugins": [{"id": "c310c353-b9f0-4d76-ab0d-1dd5e979cf68", "category": 1}] if web_search else [],
|
2024-03-12 17:45:22 +00:00
|
|
|
"traceId": get_random_hex(40),
|
2024-03-12 01:06:06 +00:00
|
|
|
"conversationHistoryOptionsSets": ["autosave","savemem","uprofupd","uprofgen"],
|
|
|
|
"gptId": "copilot",
|
2024-03-16 17:07:53 +00:00
|
|
|
"isStartOfSession": new_conversation,
|
2024-03-12 01:06:06 +00:00
|
|
|
"requestId": request_id,
|
|
|
|
"message":{
|
|
|
|
**Defaults.location,
|
|
|
|
"userIpAddress": get_ip_address(),
|
2024-03-12 17:45:22 +00:00
|
|
|
"timestamp": datetime.now().isoformat(),
|
2024-03-12 01:06:06 +00:00
|
|
|
"author": "user",
|
|
|
|
"inputMethod": "Keyboard",
|
|
|
|
"text": prompt,
|
|
|
|
"messageType": "Chat",
|
|
|
|
"requestId": request_id,
|
|
|
|
"messageId": request_id
|
|
|
|
},
|
2024-03-19 17:48:32 +00:00
|
|
|
"tone": "Balanced" if tone == Tones.copilot else tone,
|
2024-03-12 01:06:06 +00:00
|
|
|
"spokenTextMode": "None",
|
|
|
|
"conversationId": conversation.conversationId,
|
|
|
|
"participant": {"id": conversation.clientId}
|
2024-01-14 06:45:41 +00:00
|
|
|
}],
|
2024-03-12 01:06:06 +00:00
|
|
|
"invocationId": "0",
|
|
|
|
"target": "chat",
|
|
|
|
"type": 4
|
2023-08-21 20:39:57 +00:00
|
|
|
}
|
2024-01-14 06:45:41 +00:00
|
|
|
|
2024-01-26 06:54:13 +00:00
|
|
|
if image_request and image_request.get('imageUrl') and image_request.get('originalImageUrl'):
|
|
|
|
struct['arguments'][0]['message']['originalImageUrl'] = image_request.get('originalImageUrl')
|
|
|
|
struct['arguments'][0]['message']['imageUrl'] = image_request.get('imageUrl')
|
Major Update for Bing - Supports latest bundle version and image analysis
Here it is, a much-needed update to this service which offers numerous functionalities that the old code was unable to deliver to us.
As you may know, ChatGPT Plus subscribers now have the opportunity to request image analysis directly from GPT within the chat bar. Bing has also integrated this feature into its chatbot. With this new code, you can now provide an image using a data URI, with all the following supported extensions: jpg, jpeg, png, and gif!
**What is a data URI and how can I provide an image to Bing?**
Just to clarify, a data URI is a method for encoding data directly into a URI (Uniform Resource Identifier). It is typically used for embedding small data objects like images, text, or other resources within web pages or documents. Data URIs are widely used in web applications.
To provide an image from your desktop and retrieve it as a data URI, you can use this code: [GitHub link](https://gist.github.com/jsocol/1089733).
Now, here is a code snippet you can use to provide images to Bing:
```python
import g4f
provider = g4f.Provider.Bing
user_message = [{"role": "user", "content": "Hi, describe this image."}]
response = g4f.ChatCompletion.create(
model = g4f.models.gpt_4,
provider = g4f.provider, # Corrected the provider value
messages = user_message,
stream = True,
image = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/4RiSRXhpZgAASUkqAAg..." # Insert your full data URI image here
)
for message in response:
print(message, flush=True, end='')
```
If you don't want to analyze the image, just do not specify the image parameter.
Regarding the implementation, the image is preprocessed within the Bing.py code, which can be resource-intensive for a server-side implementation. When using the Bing chatbot in your web browser, the image is preprocessed on your computer before being sent to the server. This preprocessing includes tasks like image rotation and compression. Although this implementation works, it would be more efficient to delegate image preprocessing to the client as it happens in reality. I will try to provide a JavaScript code for that at a later time.
As you saw, I did mention in the title that it is in Beta. The way the code is written, Bing can sometimes mess up its answers. Indeed, Bing does not really stream its responses as the other providers do. Bing sends its answers like this on each iteration:
"Hi,"
"Hi, this,"
"Hi, this is,"
"Hi, this is Bing."
Instead of sending each segment one at a time, it already adds them on each iteration. So, to simulate a normal streaming response, other contributors made the code wait for the next iteration to retrieve the newer segments and yield them. However, this method ignores something that Bing does.
Bing processes its responses in a markdown detector, which searches for links while the AI answers. If it finds a link, it saves it and waits until the AI finishes its answer to put all the found links at the very end of the answer. So if the AI is writing a link, but then on the next iteration, it finishes writing this link, it will then be deleted from the answer and appear later at the very end. Example:
"Here is your link reference ["
"Here is your link reference [^"
"Here is your link reference [^1"
"Here is your link reference [^1^"
And then the response would get stuck there because the markdown detector would have deleted this link reference in the next response and waited until the AI is finished to put it at the very end.
For this reason, I am working on an update to anticipate the markdown detector.
So please, if you guys notice any bugs with this new implementation, I would greatly appreciate it if you could report them on the issue tab of this repo. Thanks in advance, and I hope that all these explanations were clear to you!
2023-10-22 13:59:56 +00:00
|
|
|
struct['arguments'][0]['experienceType'] = None
|
|
|
|
struct['arguments'][0]['attachedFileInfo'] = {"fileName": None, "fileType": None}
|
2024-01-14 06:45:41 +00:00
|
|
|
|
2023-08-21 20:39:57 +00:00
|
|
|
if context:
|
|
|
|
struct['arguments'][0]['previousMessages'] = [{
|
|
|
|
"author": "user",
|
|
|
|
"description": context,
|
2024-03-14 12:53:57 +00:00
|
|
|
"contextType": "ClientApp",
|
2023-08-21 20:39:57 +00:00
|
|
|
"messageType": "Context",
|
|
|
|
"messageId": "discover-web--page-ping-mriduna-----"
|
|
|
|
}]
|
2024-01-14 06:45:41 +00:00
|
|
|
|
2023-08-21 20:39:57 +00:00
|
|
|
return format_message(struct)
|
|
|
|
|
|
|
|
async def stream_generate(
|
2024-01-14 06:45:41 +00:00
|
|
|
prompt: str,
|
|
|
|
tone: str,
|
|
|
|
image: ImageType = None,
|
|
|
|
context: str = None,
|
|
|
|
cookies: dict = None,
|
2024-04-12 18:58:40 +00:00
|
|
|
api_key: str = None,
|
2024-03-13 04:27:54 +00:00
|
|
|
proxy: str = None,
|
2024-01-14 06:45:41 +00:00
|
|
|
web_search: bool = False,
|
|
|
|
gpt4_turbo: bool = False,
|
2024-03-12 17:45:22 +00:00
|
|
|
timeout: int = 900,
|
|
|
|
conversation: Conversation = None,
|
2024-03-16 13:40:06 +00:00
|
|
|
return_conversation: bool = False,
|
2024-03-13 12:01:22 +00:00
|
|
|
raise_apology: bool = False,
|
2024-03-16 17:07:53 +00:00
|
|
|
max_retries: int = None,
|
2024-03-13 12:01:22 +00:00
|
|
|
sleep_retry: int = 15,
|
|
|
|
**kwargs
|
2024-01-14 06:45:41 +00:00
|
|
|
):
|
|
|
|
"""
|
|
|
|
Asynchronously streams generated responses from the Bing API.
|
|
|
|
|
|
|
|
:param prompt: The user's input prompt.
|
|
|
|
:param tone: The desired tone for the response.
|
|
|
|
:param image: The image type involved in the response.
|
|
|
|
:param context: Additional context for the prompt.
|
|
|
|
:param cookies: Cookies for the session.
|
|
|
|
:param web_search: Flag to enable web search.
|
|
|
|
:param gpt4_turbo: Flag to enable GPT-4 Turbo.
|
|
|
|
:param timeout: Timeout for the request.
|
|
|
|
:return: An asynchronous generator yielding responses.
|
|
|
|
"""
|
2024-04-21 05:22:59 +00:00
|
|
|
headers = await create_headers(cookies, api_key)
|
2024-03-16 17:07:53 +00:00
|
|
|
new_conversation = conversation is None
|
|
|
|
max_retries = (5 if new_conversation else 0) if max_retries is None else max_retries
|
2024-04-21 05:22:59 +00:00
|
|
|
first = True
|
|
|
|
while first or conversation is None:
|
|
|
|
async with StreamSession(timeout=timeout, proxy=proxy) as session:
|
2024-03-16 13:40:06 +00:00
|
|
|
first = False
|
2024-03-12 17:45:22 +00:00
|
|
|
do_read = True
|
|
|
|
try:
|
2024-03-16 13:40:06 +00:00
|
|
|
if conversation is None:
|
2024-03-16 17:07:53 +00:00
|
|
|
conversation = await create_conversation(session, headers, tone)
|
|
|
|
if return_conversation:
|
|
|
|
yield conversation
|
2024-04-21 05:22:59 +00:00
|
|
|
except (ResponseStatusError, RateLimitError) as e:
|
2024-03-12 17:45:22 +00:00
|
|
|
max_retries -= 1
|
|
|
|
if max_retries < 1:
|
|
|
|
raise e
|
|
|
|
if debug.logging:
|
|
|
|
print(f"Bing: Retry: {e}")
|
2024-04-21 05:22:59 +00:00
|
|
|
headers = await create_headers()
|
2024-03-12 17:45:22 +00:00
|
|
|
await asyncio.sleep(sleep_retry)
|
|
|
|
continue
|
|
|
|
|
2024-03-19 17:48:32 +00:00
|
|
|
image_request = await upload_image(
|
|
|
|
session,
|
|
|
|
image,
|
2024-03-22 11:48:59 +00:00
|
|
|
"Balanced" if tone == Tones.copilot else tone,
|
2024-03-19 17:48:32 +00:00
|
|
|
headers
|
|
|
|
) if image else None
|
2024-01-10 09:34:56 +00:00
|
|
|
async with session.ws_connect(
|
2024-03-16 17:07:53 +00:00
|
|
|
'wss://s.copilot.microsoft.com/sydney/ChatHub'
|
2024-03-19 17:48:32 +00:00
|
|
|
if tone == "Copilot" else
|
2024-01-10 09:34:56 +00:00
|
|
|
'wss://sydney.bing.com/sydney/ChatHub',
|
|
|
|
autoping=False,
|
2024-03-12 17:45:22 +00:00
|
|
|
params={'sec_access_token': conversation.conversationSignature},
|
|
|
|
headers=headers
|
2024-01-10 09:34:56 +00:00
|
|
|
) as wss:
|
2023-08-21 20:39:57 +00:00
|
|
|
await wss.send_str(format_message({'protocol': 'json', 'version': 1}))
|
2024-03-12 01:06:06 +00:00
|
|
|
await wss.send_str(format_message({"type": 6}))
|
2024-04-21 05:22:59 +00:00
|
|
|
await wss.receive_str()
|
2024-03-16 17:07:53 +00:00
|
|
|
await wss.send_str(create_message(
|
|
|
|
conversation, prompt, tone,
|
|
|
|
context if new_conversation else None,
|
|
|
|
image_request, web_search, gpt4_turbo,
|
|
|
|
new_conversation
|
|
|
|
))
|
2023-08-21 20:39:57 +00:00
|
|
|
response_txt = ''
|
|
|
|
returned_text = ''
|
2024-03-12 01:06:06 +00:00
|
|
|
message_id = None
|
2024-03-12 17:45:22 +00:00
|
|
|
while do_read:
|
2024-05-05 21:38:31 +00:00
|
|
|
try:
|
|
|
|
msg = await wss.receive_str()
|
|
|
|
except TypeError:
|
|
|
|
continue
|
2024-04-21 05:22:59 +00:00
|
|
|
objects = msg.split(Defaults.delimiter)
|
2023-08-21 20:39:57 +00:00
|
|
|
for obj in objects:
|
2024-05-05 21:38:31 +00:00
|
|
|
if not obj:
|
2023-08-21 20:39:57 +00:00
|
|
|
continue
|
2024-04-21 05:22:59 +00:00
|
|
|
try:
|
|
|
|
response = json.loads(obj)
|
2024-05-07 05:41:58 +00:00
|
|
|
except ValueError:
|
2024-04-21 05:22:59 +00:00
|
|
|
continue
|
2024-01-14 06:45:41 +00:00
|
|
|
if response and response.get('type') == 1 and response['arguments'][0].get('messages'):
|
2023-08-21 20:39:57 +00:00
|
|
|
message = response['arguments'][0]['messages'][0]
|
2024-03-12 01:06:06 +00:00
|
|
|
if message_id is not None and message_id != message["messageId"]:
|
|
|
|
returned_text = ''
|
|
|
|
message_id = message["messageId"]
|
2024-01-13 17:10:43 +00:00
|
|
|
image_response = None
|
2024-03-13 12:01:22 +00:00
|
|
|
if (raise_apology and message['contentOrigin'] == 'Apology'):
|
2024-04-21 05:22:59 +00:00
|
|
|
raise ResponseError("Apology Response Error")
|
2024-03-13 12:01:22 +00:00
|
|
|
if 'adaptiveCards' in message:
|
|
|
|
card = message['adaptiveCards'][0]['body'][0]
|
|
|
|
if "text" in card:
|
|
|
|
response_txt = card.get('text')
|
|
|
|
if message.get('messageType') and "inlines" in card:
|
|
|
|
inline_txt = card['inlines'][0].get('text')
|
2024-03-22 17:35:42 +00:00
|
|
|
response_txt += f"{inline_txt}\n"
|
2024-03-13 12:01:22 +00:00
|
|
|
elif message.get('contentType') == "IMAGE":
|
|
|
|
prompt = message.get('text')
|
|
|
|
try:
|
2024-04-23 15:34:42 +00:00
|
|
|
image_client = BingCreateImages(cookies, proxy, api_key)
|
2024-03-13 12:01:22 +00:00
|
|
|
image_response = await image_client.create_async(prompt)
|
|
|
|
except Exception as e:
|
2024-03-14 12:53:57 +00:00
|
|
|
if debug.logging:
|
|
|
|
print(f"Bing: Failed to create images: {e}")
|
2024-03-15 10:46:06 +00:00
|
|
|
image_response = f"\nhttps://www.bing.com/images/create?q={parse.quote(prompt)}"
|
2023-08-21 20:39:57 +00:00
|
|
|
if response_txt.startswith(returned_text):
|
|
|
|
new = response_txt[len(returned_text):]
|
2024-03-13 16:52:48 +00:00
|
|
|
if new not in ("", "\n"):
|
2023-08-21 20:39:57 +00:00
|
|
|
yield new
|
|
|
|
returned_text = response_txt
|
2024-03-15 10:46:06 +00:00
|
|
|
if image_response is not None:
|
2024-01-13 17:10:43 +00:00
|
|
|
yield image_response
|
2023-08-21 20:39:57 +00:00
|
|
|
elif response.get('type') == 2:
|
|
|
|
result = response['item']['result']
|
2024-04-21 05:22:59 +00:00
|
|
|
do_read = False
|
2023-08-21 20:39:57 +00:00
|
|
|
if result.get('error'):
|
2024-03-12 17:45:22 +00:00
|
|
|
max_retries -= 1
|
|
|
|
if max_retries < 1:
|
|
|
|
if result["value"] == "CaptchaChallenge":
|
2024-03-19 17:48:32 +00:00
|
|
|
raise RateLimitError(f"{result['value']}: Use other cookies or/and ip address")
|
2024-03-12 17:45:22 +00:00
|
|
|
else:
|
|
|
|
raise RuntimeError(f"{result['value']}: {result['message']}")
|
|
|
|
if debug.logging:
|
|
|
|
print(f"Bing: Retry: {result['value']}: {result['message']}")
|
2024-04-21 05:22:59 +00:00
|
|
|
headers = await create_headers()
|
2024-03-12 17:45:22 +00:00
|
|
|
conversation = None
|
|
|
|
await asyncio.sleep(sleep_retry)
|
2024-04-21 05:22:59 +00:00
|
|
|
break
|
|
|
|
elif response.get('type') == 3:
|
|
|
|
do_read = False
|
|
|
|
break
|
|
|
|
if conversation is not None:
|
|
|
|
await delete_conversation(session, conversation, headers)
|