vsakkas / sydney.py Goto Github PK
View Code? Open in Web Editor NEWPython Client for Copilot (formerly named Bing Chat), also known as Sydney.
License: MIT License
Python Client for Copilot (formerly named Bing Chat), also known as Sydney.
License: MIT License
Hi,
Thank you so much for sharing this package. It's really helpful.
I know most probably it's not possible but I wanted ask it anyway. You know bing, when permission is granted, can acccess the current page that you are viewing on your browser and you can directly chat about that page.
As you know, currently we can't provide context to bing chat as it has 2000 characters limit. But when the permission is given, it can get the page content by itself and it's super useful.
For instance, I go to any github repo and start chatting about that repo. And with some proper prompt handling, it provides code reviews as well as providing the code for requested features itself. It's like free GPT4 with super big context window. Also it still searches the web when it thinks necessary :)
My question is can we mimic this behaviour in this package, for instance, user provides a url inside the python script (as if it's viewing it on the browswer) and bing chat gets the context by itself from the url?
I hope my question was clear.
Thanks for reading it :)
Edit: I thought this feature was only available for the edge developer version, but I checked it now and i see that it's possible to grant permissions in the normal edge browser too.
All work perfect on v0.15.x till hours ago, suddenly the client creation failed and never went back.
I tried following but not work at all: 1) upgrade to 0.18.0; 2) get some new _U cookies or the _U cookie of copilot.microsoft.com; 3) reboot PC, restart VS Code...
About my usage:
Hey there! Firstly I just wanted to thank you for creating this package. It has helped me create a lot of cool things :)
I am getting the same issue, this hadn't happened before, but today I run the code and I got this:
I know that everything is right because I have been running the same code for a while now, so the _U cookie is correct I am sure of that.
Could you point me on what could be the issue? Maybe they already patched it?
Thanks!
Before update, just go to bing.com/chat and input 'hi' >> Enter to pass CAPTCHA.
After update, i can not pass CAPTCHA
Support for adding/setting system message/instructions?
Like EdgeGPT, SydneyGPT, etc.
This would be HUGE
[system](#additional_instructions)
ERROR: Failed building wheel for aiohttp for Python 3.12.0
Exception has occurred: CookieError
Illegal key '<'
File "C:\PyTest\bing.py", line 22, in main
async with SydneyClient() as sydney:
File "C:\PyTest\bing.py", line 55, in
asyncio.run(main())
http.cookies.CookieError: Illegal key '<'
When I run the Demo, I used os.environ["BING_COOKIES"] = to set cookies.
I tried to get the cookies from https://www.bing.com/search?q=Bing+AI&showconv=0&FORM=hpcodxbing or https://copilot.microsoft.com/.
It has a long header string that contains "GUID", "MUIDB", "ANON" and so on. Each one I have tried to set it but all failed.
Then I also used one answer suggest way like this:
def prepare_cookies(cookies:RequestsCookieJar):
"""Prepare cookies for sydney"""
base_str = json.dumps(dict(cookies.items()))
return base_str.replace('{','').replace('}','').replace(',',';').replace(': ','=').replace('"','')
def get_new_cookies() -> RequestsCookieJar:
"""Returns new cookies to use in Bing Chat"""
res = requests.get('https://www.bing.com/search?q=Bing+AI&showconv=1&FORM=hpcodx')
# res = requests.get('https://www.bing.com/turing/conversation/create?bundleVersion=1.1342.3-cplt.7')
return res.cookies
async def main() -> None:
async with SydneyClient(bing_cookies=prepare_cookies(get_new_cookies())) as sydney:
This error appears when I do not use cookies:
from sydney import SydneyClient
async with SydneyClient() as sydney:
prompt = "what is the circumference of the earth?"
print("Sydney: ", end="", flush=True)
async for response in sydney.ask_stream(prompt):
print(response, end="", flush=True)
print("\n")
Error:
---------------------------------------------------------------------------
ContentTypeError Traceback (most recent call last)
Untitled-1.ipynb Cell 1 line 4
[1](vscode-notebook-cell:Untitled-1.ipynb?jupyter-notebook#W0sdW50aXRsZWQ%3D?line=0) from sydney import SydneyClient
----> [4](vscode-notebook-cell:Untitled-1.ipynb?jupyter-notebook#W0sdW50aXRsZWQ%3D?line=3) async with SydneyClient() as sydney:
[5](vscode-notebook-cell:Untitled-1.ipynb?jupyter-notebook#W0sdW50aXRsZWQ%3D?line=4) prompt = "what is the circumference of the earth?"
[7](vscode-notebook-cell:Untitled-1.ipynb?jupyter-notebook#W0sdW50aXRsZWQ%3D?line=6) print("Sydney: ", end="", flush=True)
File /usr/local/lib/python3.10/dist-packages/sydney/sydney.py:87, in SydneyClient.__aenter__(self)
86 async def __aenter__(self) -> SydneyClient:
---> 87 await self.start_conversation()
88 return self
File /usr/local/lib/python3.10/dist-packages/sydney/sydney.py:423, in SydneyClient.start_conversation(self)
418 if response.status != 200:
419 raise CreateConversationException(
420 f"Failed to create conversation, received status: {response.status}"
421 )
--> 423 response_dict = await response.json()
424 if response_dict["result"]["value"] != "Success":
425 raise CreateConversationException(
426 f"Failed to authenticate, received message: {response_dict['result']['message']}"
427 )
File /usr/local/lib/python3.10/dist-packages/aiohttp/client_reqrep.py:1104, in ClientResponse.json(self, encoding, loads, content_type)
1102 ctype = self.headers.get(hdrs.CONTENT_TYPE, "").lower()
1103 if not _is_expected_content_type(ctype, content_type):
-> 1104 raise ContentTypeError(
1105 self.request_info,
1106 self.history,
1107 message=(
1108 "Attempt to decode JSON with " "unexpected mimetype: %s" % ctype
1109 ),
1110 headers=self.headers,
1111 )
1113 stripped = self._body.strip() # type: ignore[union-attr]
1114 if not stripped:
ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: ', url=URL('https://www.bing.com/turing/conversation/create?bundleVersion=1.1199.4')
You: 你好
Sydney: Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\windows_events.py", line 444, in select
self._poll(timeout)
RuntimeError: <_overlapped.Overlapped object at 0x000002430C626430> still has pending operation at deallocation, the process may crash
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\windows_events.py", line 444, in select
self._poll(timeout)
RuntimeError: <_overlapped.Overlapped object at 0x000002430C626430> still has pending operation at deallocation, the process may crash
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\windows_events.py", line 444, in select
self._poll(timeout)
RuntimeError: <_overlapped.Overlapped object at 0x000002430C626430> still has pending operation at deallocation, the process may crash
async def main() -> None:
async with SydneyClient() as sydney:
response = await sydney.ask("When was Bing Chat released?", citations=True)
print(response)
if __name__ == "__main__":
asyncio.run(main())
raises the exception sydney.exceptions.NoResponseException: No response was returned
Please look at the attached screenshot for details
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/sydney/sydney.py", line 233, in _ask raise CaptchaChallengeException("Solve CAPTCHA to continue") sydney.exceptions.CaptchaChallengeException: Solve CAPTCHA to continue
Unfortunately, I'm encountering this error with the update 0.15.0. @vsakkas
Hello, I would like to use this librairy without being connected to my Microstoft account. It is possible with this URL for example : https://www.bing.com/search?q=Bing+AI&showconv=1&FORM=hpcodx&wlsso=0
But when I try to use the librairy and I add the cookie of this session (it's a cookie without the _U), it triggers a captcha that I can't solve with the non login session (the captcha doesn't appear in the session).
this is my code that I created to have a personal bot on telegram. the bot responds perfectly to questions that do not require searching on the web, as soon as you ask a question for which you will have to look for the answer on the internet I get this error... why? how can I solve it Sydney: Searching the web for:
Cosa c'è sulla luna?` it hangs like this without giving me the answer in the telegram bot and it doesn't give me any errors in the terminal
this is my code
import os import asyncio import telebot from sydney import SydneyClient
Token del bot Telegram, ottenuto da BotFather su Telegram telegram_token = 'bot_token'
Impostazione del cookie _U per l'utilizzo con Sydney.py bing_cookies = 'cookies _u' os.environ["BING_U_COOKIE"] = bing_cookies
` Inizializzazione del bot Telegram
bot = telebot.TeleBot(telegram_token)
Funzione per gestire il comando /start @bot.message_handler(commands=['start']) def send_welcome(message): bot.reply_to(message, "Ciao! Scrivi qualcosa per iniziare la conversazione con Sydney.")
Funzione per gestire i messaggi testuali
`@bot.message_handler(func=lambda message: True)
def handle_message(message):
async def ask_sydney(question):
async with SydneyClient() as sydney:
response = await sydney.ask(question)
return response
question = message.text`
`interrogazione di Sydney per ottenere la risposta
response = asyncio.run(ask_sydney(question))
# Invio della risposta al mittente su Telegram
bot.reply_to(message, f"Sydney: {response}")
bot.polling()`
Conversation delete, save and use without creating a conversation (without creating an apparent conversation in ui)
For myself:
Please brother 🙏
Captacha error
async def main() -> None:
async with SydneyClient() as sydney:
response = sydney.ask("When was Bing Chat released?", citations=True)
print(response)
if __name__ == "__main__":
asyncio.run(main())
gives :
C:\Python310\lib\asyncio\events.py:80: RuntimeWarning: coroutine 'SydneyClient.ask' was never awaited
self._context.run(self._callback, *self._args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
please add an API Support.
Add option to disable web access or using system prompts.
The web access is considered as plugin now.
I'm already searching for methods :)
I use default lib from you get this error:
sydney.exceptions.ImageUploadException: Failed to upload image, received empty image info from Bing Chat
Check it out blobID should be like: {"blobId":"*****","processedBlobId":""} but your response is {"blobId":"","processedBlobId":""}, this cause error.
Then I modify your to make upload local photo to https://www.bing.com/images/kblob, after that I get right value for blobID, processedBlobId. Then that JSON response from /image/kblob it fit with your code (response_dict = await response.json() in sydney.py).
Then I log received messages from wss, this error show up, please check again image upload:
['{"type":2,"invocationId":"0","item":{"firstNewMessageIndex":null,"defaultChatName":null,"conversationId":"51D|BingProdUnAuthenticatedUsers|****************************","requestId":"*****************************","telemetry":{"startTime":"2023-10-24T16:53:12.8064874Z"},"result":{"value":"InternalError","message":"ServiceClient failure for Gptv","error":"ServiceClient failure for Gptv\n ---> Failed to call \"Gptv\" at \"SelectedByPapyrusLoadBalancer\". HttpCode= - ResponseCode=Unknown - LoadBalancerResponseCode=SchedulingRejected - AMLModelErrorStatusCode=-1 - ReasonPhrase= - AMLModelErrorReason=.","exception":"Microsoft.TuringBot.Common.ServiceClientException: ServiceClient failure for Gptv\r\n ---> System.Net.Http.HttpRequestException: Failed to call \"Gptv\" at \"SelectedByPapyrusLoadBalancer\". HttpCode= - ResponseCode=Unknown - LoadBalancerResponseCode=SchedulingRejected - AMLModelErrorStatusCode=-1 - ReasonPhrase= - AMLModelErrorReason=.\r\n --- End of inner exception stack trace ---\r\n at BotClientLibrary.ServiceClients.ServiceClient.SendPapyrusRequest(String url, HttpRequestMessage request, TelemetryScope scope, MetricsCollection metrics, CancellationToken cancellationToken, String serviceName, ServiceClientOptions options) in C:\\a\\_work\\1\\s\\services\\TuringBot\\src\\BotClientLibrary\\ServiceClients\\ServiceClient.cs:line 764\r\n at BotClientLibrary.ServiceClients.ServiceClient.Run(Conversation conversation, Message message, CancellationToken cancellationToken, BatchRequest batchRequest, ServiceClientOptions options) in C:\\a\\_work\\1\\s\\services\\TuringBot\\src\\BotClientLibrary\\ServiceClients\\ServiceClient.cs:line 429\r\n at BotClientLibrary.Extensions.DeepLeoOrchestrator.UpdateConversationWithContentDescriptions(ExtensionRequest request, ExtensionResponse result, Conversation conversation, DeepLeoEngineState engineState, Message message, TuringBotConfiguration config, CancellationToken cancellationToken) in C:\\a\\_work\\1\\s\\services\\TuringBot\\src\\BotClientLibrary\\Extensions\\DeepLeoOrchestrator.cs:line 390\r\n at BotClientLibrary.Extensions.DeepLeoOrchestrator.Run(ExtensionRequest request, CancellationToken cancellationToken) in C:\\a\\_work\\1\\s\\services\\TuringBot\\src\\BotClientLibrary\\Extensions\\DeepLeoOrchestrator.cs:line 301\r\n at BotClientLibrary.Extensions.ExtensionRunner.RunExtension(ExtensionRequest request, Conversation conversation, ExtensionConfig extension, ExtensionRequestOptions customOptions, ParsedToolInvocation action, String modelName, CancellationToken cancellationToken) in C:\\a\\_work\\1\\s\\services\\TuringBot\\src\\BotClientLibrary\\Extensions\\ExtensionRunner.cs:line 694\r\n at BotClientLibrary.Extensions.ExtensionRunner.RunExtensions(Conversation conversation, CancellationToken cancellationToken, ComponentPriority minPriority, ComponentPriority maxPriority, ExtensionRequestOptions customOptions, ExtensionRequest request, ParsedToolInvocation action, String modelName, Classification modelClassification) in C:\\a\\_work\\1\\s\\services\\TuringBot\\src\\BotClientLibrary\\Extensions\\ExtensionRunner.cs:line 291\r\n at BotClientLibrary.BotConnection.GetContentResponsesAsync(Conversation conversation, CancellationToken cancellationToken) in C:\\a\\_work\\1\\s\\services\\TuringBot\\src\\BotClientLibrary\\BotConnection.cs:line 703\r\n at BotClientLibrary.BotConnection.InternalRun(Conversation conversation, CancellationToken cancellationToken) in C:\\a\\_work\\1\\s\\services\\TuringBot\\src\\BotClientLibrary\\BotConnection.cs:line 795\r\n at BotClientLibrary.BotConnection.ExecuteBotTurn(Conversation conversation, CancellationToken cancellationToken) in C:\\a\\_work\\1\\s\\services\\TuringBot\\src\\BotClientLibrary\\BotConnection.cs:line 418\r\n at BotClientLibrary.BotConnection.ExecuteBotTurn(Conversation conversation, CancellationToken cancellationToken) in C:\\a\\_work\\1\\s\\services\\TuringBot\\src\\BotClientLibrary\\BotConnection.cs:line 418\r\n at BotClientLibrary.BotConnection.Run(CancellationToken cancellationToken) in C:\\a\\_work\\1\\s\\services\\TuringBot\\src\\BotClientLibrary\\BotConnection.cs:line 141\r\n at Microsoft.Falcon.TuringBot.ChatApiImplementation.Run(BaseRequest request, BaseResponse response, CancellationToken cancellationToken) in C:\\a\\_work\\1\\s\\services\\TuringBot\\src\\Service\\Implementation\\ApiImplementation\\ChatApiImplementation.cs:line 164\r\n at Microsoft.Falcon.TuringBot.RequestProcessor.Run(BaseRequest request, BaseResponse response, IRequestContextInitializer contextInitializer, IRequestValidator requestValidator, IApiImplementation apiImplementation, IAsyncApiEndStep apiEndStep, String apiName, CancellationToken cancellationToken, Func`1 cancellationTokenProvider) in C:\\a\\_work\\1\\s\\services\\TuringBot\\src\\Service\\Implementation\\RequestProcessor.cs:line 260","serviceVersion":"20231023.32"}}}', '{"type":3,"invocationId":"0"}', '']
Hello, since this morning, when I try to use the library, I get captcha on the loop.
What I do :
As it is known, it is possible to use bing without logging in, including chrome, other browsers. It would be nice if this feature was added
I have recently been experiencing issues with the library, but I really like its simplicity and wouldn't want to switch to another one. While looking for solutions, I just came across an interesting topic that might be our solution to recent problems. I haven't implemented it yet, but I'm leaving it here for your analysis.
You can find more details in this link: danny-avila/LibreChat#370 (comment)
I've been trying to test out your project, but having issues finding the correct cookie in any browser. I've tried FF/Chrome/Edge and all three seem to have identical cookies. I've attached an image of the cookies that are present, but I don't see any edgeservices URL or any cookie with a "_U" in the key or value.
- Select the Application tab and click on the Cookies option to view all cookies associated with https://edgeservices.bing.com.
- Look for the _U cookie and click on it to expand its details.
- Copy the value of the _U cookie (it should look like a long string of letters and numbers).
I have this error since today : [Errno 11002] getaddrinfo failed
I use the script with cookies.
I installed sydney and have used it for several days. However, recently I always met an error:
"sydney.exceptions.ThrottledRequestException: Request is throttled". I wonder what I should do to fix this. Thanks!
https://www.bing.com/turing/conversation/create returns 404
when i use Sydney.py to easily create a CLI client for Bing Chat:
example.py
import asyncio
from sydney import SydneyClient
async def main() -> None:
async with SydneyClient() as sydney:
while True:
prompt = input("You: ")
if prompt == "!reset":
await sydney.reset_conversation()
continue
elif prompt == "!exit":
break
print("Sydney: ", end="", flush=True)
async for response in sydney.ask_stream(prompt):
print(response, end="", flush=True)
print("\n")
if __name__ == "__main__":
asyncio.run(main())
But it reported this error:
Traceback (most recent call last):
File "~/Project/sydney.py/example.py", line 24, in <module>
asyncio.run(main())
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
return future.result()
File "~/Project/sydney.py/example.py", line 7, in main
async with SydneyClient() as sydney:
File "~/Project/sydney.py/sydney/sydney.py", line 57, in __aenter__
await self.start_conversation()
File "~/Project/sydney.py/sydney/sydney.py", line 259, in start_conversation
raise Exception(
Exception: Failed to create conversation, received status: 404
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x10a233bb0>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x10aef11c0>, 0.491523)]']
connector: <aiohttp.connector.TCPConnector object at 0x10ae5ea00>
Is this a problem with Python 3.9?
Getting this error when using Sydney-Client with Python3.10 and Python3.11 on Ubuntu 22.04.03 and Debian 12
I know the _U cookie is correct so I'm unsure why im getting this error.
Please help.
Traceback (most recent call last):
File "/home/xxxx/testing.py", line 24, in
asyncio.run(main())
File "/usr/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/usr/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
return future.result()
File "/home/xxxx/testing.py", line 7, in main
async with SydneyClient(bing_u_cookie="x", style="precise") as sydney:
File "/usr/local/lib/python3.10/dist-packages/sydney/sydney.py", line 93, in aenter
await self.start_conversation()
File "/usr/local/lib/python3.10/dist-packages/sydney/sydney.py", line 427, in start_conversation
raise CreateConversationException(
sydney.exceptions.CreateConversationException: Failed to create conversation, received status: 404
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f494528a320>
When I use the librairie, the quality of the content is not the same as when I use Bing Chat. I have performed a test I have used the Balanced mode. In this mode the max number of character is 2000. I have given a prompt with arround 3500 characters and I have received an answer as if all the character have been read by Bing. So I assume that it was not in Balanced mode, otherwise, it shouldn't have read all my prompt.
Thank you.
Hello,
I've followed the instructions and even entered a new cookie each time (by logging in and out in the browser), but I still get
raise CaptchaChallengeException("Solve CAPTCHA to continue")
Any way around this?
Sometimes, when I use the function ask_stream, the first character or the first word of the response is missing.
async for response in syd.ask_stream(prompt):
res.append(response)
Not an issue, just a note that this library requires me to install Microsoft Visual C++ 14.0 or greater. to install that, you need to go https://visualstudio.microsoft.com/visual-cpp-build-tools/ and download the program, then install Workload named Desktop development C++, install the core and it optional files.
Im on windows 11, and Python 3.12.1
I am facing problem while trying to prompt image to the bing thorught attachment but facing the following error
`import asyncio
import os
from sydney import SydneyClient
os.environ["BING_U_COOKIE"] = '''1EGoJt1yjZ4phWsfhRb-jOz_kn02a2aNSJ-ZTepKf9RD5FiP0NBvSRPkrUqOF8qxyG9qs2Zq6U6THoi74O3LzaxWYlXC6o3x3LlygK0JBTwAoLZQ9OFMFa_zCh1E8WAs9XybXsJtmNqjGlnr7qu7DVOsdXfJQv6sH_stxoT44n1pe_XM2hD2nvi2mTHIh4T009XUusjzCk3ESouAZ9lpErBT0mSeB_WwjnS_yMCxJhuo'''
async def main() -> None:
async with SydneyClient() as sydney:
while True:
prompt = input("You: ")
if prompt == "!reset":
await sydney.reset_conversation()
continue
elif prompt == "!exit":
break
# Provide the URL to your image here
image_url = "https://th.bing.com/th/id/OIP.TILseDM6LQr7VTeARsInPQHaFj?pid=ImgDet&rs=1"
print("Bing ai: ", end="", flush=True)
response = await sydney.ask(prompt, attachment=image_url)
print(response, end="", flush=True)
print("\n")
if __name__ == "__main__":
asyncio.run(main())
`
For which i am getting the following error
Traceback (most recent call last):
File "C:\wamp64\www\project_1\api_demo6.py", line 27, in <module>
asyncio.run(main())
File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\wamp64\www\project_1\api_demo6.py", line 22, in main
response = await sydney.ask(prompt, attachment=image_url)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\site-packages\sydney\sydney.py", line 459, in ask
async for response, suggested_responses in self._ask(
File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\site-packages\sydney\sydney.py", line 316, in _ask
attachment_info = await self._upload_attachment(attachment)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\site-packages\sydney\sydney.py", line 275, in _upload_attachment
raise ImageUploadException(
sydney.exceptions.ImageUploadException: Failed to upload image, received empty image info from Bing Chat
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x0000017F24685D90>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x0000017F245E2A50>, 10168.265)]']
connector: <aiohttp.connector.TCPConnector object at 0x0000017F24685E90>
After several prompt, Bing Chat send me this error : text.
If I try to ask it something else, it keeps sending me this error.
Perhaps Bing Chat operates differently in different regions or there has been a update to how this is handled, but for me the conversationSignature
is assigned in the conversation response headers as X-Sydney-Conversationsignature
and X-Sydney-Encryptedconversationsignature
, not in the response body. Also there is no throttling
key in the chathub response.
X-Sydney-Conversationsignature
is used in exactly the same way as conversationSignature is currently handled.
X-Sydney-Encryptedconversationsignature
is encoded for use as a GET parameter and included in all requests to BING_CHATHUB_URL
, so the URL used should be BING_CHATHUB_URL + f"?sec_access_token={urllib.parse.quote(X-Sydney-Encryptedconversationsignature)}"
Without all these changes, Sydney.py does not run for me.
Hello,
I have this error since few hours : Error : Failed to create conversation, received status: 404.
After few retry, it is working. But the error appear frequently.
Hello, I have been using your library to retrieve responses from Bing's chat. And your library was successful on Windows 10 without any errors. However, when using the same script I ran on Windows, it gave me the following error. Any ideas on what may be going on?
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/websockets/legacy/client.py", line 662, in __await_impl__
await protocol.handshake(
File "/usr/local/lib/python3.10/dist-packages/websockets/legacy/client.py", line 329, in handshake
raise InvalidStatusCode(status_code, response_headers)
websockets.exceptions.InvalidStatusCode: server rejected WebSocket connection: HTTP 200
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/websockets/legacy/client.py", line 655, in __await_impl_timeout__
return await self.__await_impl__()
File "/usr/local/lib/python3.10/dist-packages/websockets/legacy/client.py", line 676, in __await_impl__
await protocol.wait_closed()
asyncio.exceptions.CancelledError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/root/AI_workspace/summarizer.py", line 294, in <module>
asyncio.run(summarize())
File "/usr/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/usr/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
return future.result()
File "/root/AI_workspace/summarizer.py", line 291, in summarize
await bot.create_bot(prompts=prompts, template=template, conversation_mode=conversation_mode)
File "/root/AI_workspace/summarizer.py", line 208, in create_bot
return await self.run(instance=bot_result,
File "/root/AI_workspace/summarizer.py", line 223, in run
response = await sydney.compose(f'{template}\n\nPROMPT: {prompt}' if template else prompt, raw=True)
File "/usr/local/lib/python3.10/dist-packages/sydney/sydney.py", line 509, in compose
async for response in self._compose(
File "/usr/local/lib/python3.10/dist-packages/sydney/sydney.py", line 280, in _compose
self.wss_client = await websockets.connect(
File "/usr/local/lib/python3.10/dist-packages/websockets/legacy/client.py", line 654, in __await_impl_timeout__
async with asyncio_timeout(self.open_timeout):
File "/usr/local/lib/python3.10/dist-packages/websockets/legacy/async_timeout.py", line 169, in __aexit__
self._do_exit(exc_type)
File "/usr/local/lib/python3.10/dist-packages/websockets/legacy/async_timeout.py", line 252, in _do_exit
raise asyncio.TimeoutError
asyncio.exceptions.TimeoutError
Apologizes for the rather non-helpful error, I saw someone else had issues with this same error but I just can't seem to figure out what it is.
Traceback (most recent call last):
File "/root/workspace/ChatGPT_API/src/bingGPT.py", line 52, in ask
request = await sydney.ask(ask_request.prompt, attachment=ask_request.attachment, raw=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/workspace/ChatGPT_API/.venv/lib/python3.11/site-packages/sydney/sydney.py", line 515, in ask
async for response, suggested_responses in self._ask(
File "/root/workspace/ChatGPT_API/.venv/lib/python3.11/site-packages/sydney/sydney.py", line 348, in _ask
raise ConnectionTimeoutException(
sydney.exceptions.ConnectionTimeoutException: Failed to connect to Copilot, connection timed out
If I remove the BING_COOKIES
, I get this error instead
Traceback (most recent call last):
File "/root/workspace/ChatGPT_API/.venv/lib/python3.11/site-packages/uvicorn/protocols/http/httptools_impl.py", line 426, in run_asgi
result = await app( # type: ignore[func-returns-value]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/workspace/ChatGPT_API/.venv/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 84, in __call__
return await self.app(scope, receive, send)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/workspace/ChatGPT_API/.venv/lib/python3.11/site-packages/fastapi/applications.py", line 1106, in __call__
await super().__call__(scope, receive, send)
File "/root/workspace/ChatGPT_API/.venv/lib/python3.11/site-packages/starlette/applications.py", line 122, in __call__
await self.middleware_stack(scope, receive, send)
File "/root/workspace/ChatGPT_API/.venv/lib/python3.11/site-packages/starlette/middleware/errors.py", line 184, in __call__
raise exc
File "/root/workspace/ChatGPT_API/.venv/lib/python3.11/site-packages/starlette/middleware/errors.py", line 162, in __call__
await self.app(scope, receive, _send)
File "/root/workspace/ChatGPT_API/.venv/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 79, in __call__
raise exc
File "/root/workspace/ChatGPT_API/.venv/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 68, in __call__
await self.app(scope, receive, sender)
File "/root/workspace/ChatGPT_API/.venv/lib/python3.11/site-packages/fastapi/middleware/asyncexitstack.py", line 20, in __call__
raise e
File "/root/workspace/ChatGPT_API/.venv/lib/python3.11/site-packages/fastapi/middleware/asyncexitstack.py", line 17, in __call__
await self.app(scope, receive, send)
File "/root/workspace/ChatGPT_API/.venv/lib/python3.11/site-packages/starlette/routing.py", line 718, in __call__
await route.handle(scope, receive, send)
File "/root/workspace/ChatGPT_API/.venv/lib/python3.11/site-packages/starlette/routing.py", line 276, in handle
await self.app(scope, receive, send)
File "/root/workspace/ChatGPT_API/.venv/lib/python3.11/site-packages/starlette/routing.py", line 66, in app
response = await func(request)
^^^^^^^^^^^^^^^^^^^
File "/root/workspace/ChatGPT_API/.venv/lib/python3.11/site-packages/fastapi/routing.py", line 274, in app
raw_response = await run_endpoint_function(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/workspace/ChatGPT_API/.venv/lib/python3.11/site-packages/fastapi/routing.py", line 191, in run_endpoint_function
return await dependant.call(**values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/workspace/ChatGPT_API/src/bingGPT.py", line 37, in ask
await sydney.reset_conversation(style="creative")
File "/root/workspace/ChatGPT_API/.venv/lib/python3.11/site-packages/sydney/sydney.py", line 748, in reset_conversation
await self.start_conversation()
File "/root/workspace/ChatGPT_API/.venv/lib/python3.11/site-packages/sydney/sydney.py", line 462, in start_conversation
response_dict = await response.json()
^^^^^^^^^^^^^^^^^^^^^
File "/root/workspace/ChatGPT_API/.venv/lib/python3.11/site-packages/aiohttp/client_reqrep.py", line 1165, in json
raise ContentTypeError(
aiohttp.client_exceptions.ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: ', url=URL('https://www.bing.com/turing/conversation/create?bundleVersion=1.1342.3-cplt.7')
File "c:\Users\robin\Music\Playlists\AI Jarvis Using Python Tut\sydney.py", line 286, in _upload_attachment
raise ImageUploadException(
exceptions.ImageUploadException: Failed to upload image, Copilot rejected uploading it
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x0000019E5C202A90>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x0000019E5C27E040>, 17450.718)]']
connector: <aiohttp.connector.TCPConnector object at 0x0000019E5C276490>
import asyncio
from sydney import SydneyClient
from Body.Speak import Speak
import nest_asyncio
nest_asyncio.apply()
async def main() -> None:
async with SydneyClient() as sydney:
response = await sydney.ask("What does this picture show?", attachment="img.jpg")
print(response)
if name == "main":
asyncio.run(main())
Hello, since few hours, I have a lot of errors : index out of range. Sometimes it comes on the first prompt and sometimes after few prompts on the same chat.
I am wondering if it's not triggered by a bad internet connection because when I use the UI of Bing Chat, I can see that the chat is trying to reconnect.
I need to use proxies for use in my area
Hello, I am using Bing Chat creative mode to generate marketing content. I have some trouble to force the AI to shorter the response.
I could use precise mode to do that but I prefer the content generated by the creative mode. Does anyone have found a good prompt to force the AI to writer a certain number of words ?
Thank you !
is it possible to get the value of the block code only? for an exampl, its the json data generated from my prompt
altho i can do it manually, my prompt is
async def get_newsletter(url):
async with SydneyClient(style="balanced") as sydney:
return await sydney.ask("i want your answer to be started ONLY with ""here is the answer : and then ended the final sentence with NOTHING"f". go to this url ONLY {url} and write me a unique newsletter that differs from other sources about it. make sure it retains its accuracy to information. then followed by some formatting, and only formatted in JSON with keys of the title, the newsletter, and the citation.", context=url, raw=True)
and then
response = asyncio.run(get_newsletter(url))
data = data.replace("Here is the answer:\n\n```json\n", "").replace("```", "").replace("\n", "")
output = ast.literal_eval(data)
unfortunately this workaround is not consistent, sometimes its not working because Bing answer the question in different way
Found this code here on github and after trying to get my own code working I decided to test this. It still showed the same behavior as my own code. Using sydney.ask twice in a row results in Sydney.exceptions.NoResponseException: No response was returned.
I live in the US, and i've tried using new cookies or no cookies at all. However if I replace the second .ask with .compose it still works. The same behavior occurs with ask stream.
async def main() -> None:
async with SydneyClient() as sydney:
response = await sydney.ask("What does this picture show?", attachment='')
print(response) # Will describe a photo of a golden retriever.
response = await sydney.ask(
"Can you tell me something interesting about it?"
)
print(response)
response = await sydney.compose(
prompt="Why they are a great pet",
format="ideas",
)
print(response)
Here is my code which has the same problem:
if characterName == "lucy":
async with SydneyClient() as sydney:
while True:
print(lucyPrompt)
if lucyPrompt == " !exit":
return
response = await sydney.ask(lucyPrompt)
response_chunks += response
cleanresponse = response_chunks
cleanresponse = cleanresponse.replace("Sydney", 'Lucy').strip()
cleanresponse = cleanresponse.replace("Bing", 'Lucy').strip()
conversations = await sydney.get_conversations()
print(conversations)
if len(cleanresponse) > 1500:
with open('response.txt', 'w') as f:
f.write(cleanresponse)
if cleanresponse.endswith('.txt'):
# If the response is a filename, send it as an attachment
await message.channel.send(file=discord.File(cleanresponse, 'response.txt'))
else:
# Otherwise, send it as a message
await message.channel.send(characterName + ":\n" + cleanresponse) # Send Discord message containing response
response_chunks = ''
# Process the msgQueue for new prompts
async with new_message_condition:
print("starting waiting")
await new_message_condition.wait()
print("waited for msg")
lucyPrompt = await msg_queue.get()
I tried to figure it out but it didn’t work out, I ask for help
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.