acheong08 / EdgeGPT

Reverse engineered API of Microsoft's Bing Chat AI
The Unlicense
8.08k stars 910 forks source link

[Bug]: 403, message='Invalid response status', url=URL('wss://sydney.bing.com/sydney/ChatHub') #505

Closed Zapzatron closed 1 year ago

Zapzatron commented 1 year ago

Is there an existing issue for this?

What happened?

Traceback (most recent call last): File "F:\Games\Programming_Projects\Python\telegram_bots\Zapzatron_Bot\tests\bing_AI.py", line 105, in bot_response = asyncio.run(bing_chat(prompt=text, cookies_json_path="cookies.json")) File "F:\Games\Programming_Projects\Python\telegram_bots\Zapzatron_Bot\venv\lib\site-packages\nest_asyncio.py", line 35, in run return loop.run_until_complete(task) File "F:\Games\Programming_Projects\Python\telegram_bots\Zapzatron_Bot\venv\lib\site-packages\nest_asyncio.py", line 90, in run_until_complete return f.result() File "F:\Games\Programming_Projects\Python\telegram_bots\Python3109\lib\asyncio\futures.py", line 201, in result raise self._exception.with_traceback(self._exception_tb) File "F:\Games\Programming_Projects\Python\telegram_bots\Python3109\lib\asyncio\tasks.py", line 232, in __step result = coro.send(None) File "F:\Games\Programming_Projects\Python\telegram_bots\Zapzatron_Bot\tests\bing_AI.py", line 86, in bing_chat response_dict = await gbot.ask(prompt=prompt, conversation_style=ConversationStyle.precise) File "F:\Games\Programming_Projects\Python\telegram_bots\Zapzatron_Bot\venv\lib\site-packages\EdgeGPT\EdgeGPT.py", line 98, in ask async for final, response in self.chat_hub.ask_stream( File "F:\Games\Programming_Projects\Python\telegram_bots\Zapzatron_Bot\venv\lib\site-packages\EdgeGPT\chathub.py", line 84, in ask_stream self.wss = await self.wss_session.ws_connect( File "F:\Games\Programming_Projects\Python\telegram_bots\Zapzatron_Bot\venv\lib\site-packages\aiohttp\client.py", line 795, in _ws_connect raise WSServerHandshakeError( aiohttp.client_exceptions.WSServerHandshakeError: 403, message='Invalid response status', url=URL('wss://sydney.bing.com/sydney/ChatHub') Unclosed client session client_session: <aiohttp.client.ClientSession object at 0x0000025BE07CBD30> Unclosed connector connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x0000025BE08FCE20>, 5966.359)]'] connector: <aiohttp.connector.TCPConnector object at 0x0000025BE07CBA00>

Steps to reproduce the problem

from EdgeGPT.EdgeGPT import Chatbot, ConversationStyle import asyncio

async def bing_chat(prompt): cookies = json.loads(open("cookies.json", encoding="utf-8").read()) gbot = await Chatbot().create(cookies=cookies) response_dict = await gbot.ask(prompt=prompt, conversation_style=ConversationStyle.precise) await gbot.close() print(response_dict) return response_dict['item']['messages'][1]['text']

text = "Cell number 15 on the 2nd floor! Help me get out!!!"

print(f"None: {text}") bot_response = asyncio.run(bing_chat(prompt=text)) print(f"AI: {bot_response}")

What should have happened?

...

Version where the problem happens

0.10.3

What Python version are you running this with?

3.10.9

What is your operating system ?

Windows

Command Line Arguments

No

Console logs

F:\Games\Programming_Projects\Python\telegram_bots\Zapzatron_Bot\venv\Scripts\python.exe F:\Games\Programming_Projects\Python\telegram_bots\Zapzatron_Bot\tests\bing_AI.py 
Version of Python: 3.10.9
Version of EdgeGPT: 0.10.3
User:  Cell number 15 on the 2nd floor! Help me get out!!!
Cookies: True
Proxy: None
Traceback (most recent call last):
  File "F:\Games\Programming_Projects\Python\telegram_bots\Zapzatron_Bot\tests\bing_AI.py", line 105, in <module>
    bot_response = asyncio.run(bing_chat(prompt=text, cookies_json_path="cookies.json"))
  File "F:\Games\Programming_Projects\Python\telegram_bots\Zapzatron_Bot\venv\lib\site-packages\nest_asyncio.py", line 35, in run
    return loop.run_until_complete(task)
  File "F:\Games\Programming_Projects\Python\telegram_bots\Zapzatron_Bot\venv\lib\site-packages\nest_asyncio.py", line 90, in run_until_complete
    return f.result()
  File "F:\Games\Programming_Projects\Python\telegram_bots\Python3109\lib\asyncio\futures.py", line 201, in result
    raise self._exception.with_traceback(self._exception_tb)
  File "F:\Games\Programming_Projects\Python\telegram_bots\Python3109\lib\asyncio\tasks.py", line 232, in __step
    result = coro.send(None)
  File "F:\Games\Programming_Projects\Python\telegram_bots\Zapzatron_Bot\tests\bing_AI.py", line 86, in bing_chat
    response_dict = await gbot.ask(prompt=prompt, conversation_style=ConversationStyle.precise)
  File "F:\Games\Programming_Projects\Python\telegram_bots\Zapzatron_Bot\venv\lib\site-packages\EdgeGPT\EdgeGPT.py", line 98, in ask
    async for final, response in self.chat_hub.ask_stream(
  File "F:\Games\Programming_Projects\Python\telegram_bots\Zapzatron_Bot\venv\lib\site-packages\EdgeGPT\chathub.py", line 84, in ask_stream
    self.wss = await self.wss_session.ws_connect(
  File "F:\Games\Programming_Projects\Python\telegram_bots\Zapzatron_Bot\venv\lib\site-packages\aiohttp\client.py", line 795, in _ws_connect
    raise WSServerHandshakeError(
aiohttp.client_exceptions.WSServerHandshakeError: 403, message='Invalid response status', url=URL('wss://sydney.bing.com/sydney/ChatHub')
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x0000025BE07CBD30>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x0000025BE08FCE20>, 5966.359)]']
connector: <aiohttp.connector.TCPConnector object at 0x0000025BE07CBA00>

Process finished with exit code 1

Additional information

No response

phamxtien commented 1 year ago

I get error: objects = msg.data.split(DELIMITER) AttributeError: 'int' object has no attribute 'split'

Run code as below:

import asyncio from EdgeGPT.EdgeGPT import Chatbot, ConversationStyle async def main(): ... cookies = json.loads(open("bing.json", encoding="utf-8").read()) ... bot = await Chatbot.create(cookies=cookies) # Passing cookies is "optional", as explained above ... print(await bot.ask(prompt="What is iso 9001?", conversation_style=ConversationStyle.creative)) ... await bot.close() ... asyncio.run(main())

Traceback (most recent call last): File "/usr/lib/python3.10/code.py", line 90, in runcode exec(code, self.locals) File "", line 1, in 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 646, in run_until_complete return future.result() File "", line 4, in main File "......../EdgeGPT/EdgeGPT.py", line 98, in ask async for final, response in self.chat_hub.ask_stream( File "......./EdgeGPT/chathub.py", line 108, in ask_stream objects = msg.data.split(DELIMITER) AttributeError: 'int' object has no attribute 'split'

The---onE commented 1 year ago

I got "AttributeError: 'int' object has no attribute 'split'", too. I print the every message, and the last would be:

WSMessage(type=<WSMsgType.TEXT: 1>, data='{"type":1,"target":"update","arguments
":[{"messages":[{"text":"好的,这是我用python实现的猜数字游戏的代码:\\n\\n```py
thon\\n# 导入random模块\\nimport random\\n\\n# 生成一个1到100之间的随机整数\\nan
swer = random.randint(1, 100)\\n\\n# 设置猜测次数为10\\nguesses = 10\\n\\n# 打印
欢迎信息\\nprint(\\"欢迎来玩猜数字游戏!\\")\\nprint(\\"我已经想好了一个1到100之
间的整数。\\")\\nprint(\\"你有10次机会来猜这个数字。\\")\\n\\n# 开始游戏循环\\nw
hile guesses > 0:\\n    # 获取用户输入并转换为整数\\n    guess = int(input(\\"请
输入你的猜测:\\"))\\n\\n    # 判断用户输入是否合法\\n    if guess < 1 or guess
> 100:\\n        print(\\"请输入一个1到100之间的整数!\\")\\n        continue\\n
\\n   ","author":"bot","createdAt":"2023-06-07T02:01:21.452875+00:00","timestamp
":"2023-06-07T02:01:21.452875+00:00","messageId":"a8f0962a-d83d-4810-8c02-79282f
a039c2","offense":"Unknown","adaptiveCards":[{"type":"AdaptiveCard","version":"1
.0","body":[{"type":"TextBlock","text":"好的,这是我用python实现的猜数字游戏的代
码:\\n\\n```python\\n# 导入random模块\\nimport random\\n\\n# 生成一个1到100之间
的随机整数\\nanswer = random.randint(1, 100)\\n\\n# 设置猜测次数为10\\nguesses =
 10\\n\\n# 打印欢迎信息\\nprint(\\"欢迎来玩猜数字游戏!\\")\\nprint(\\"我已经想
好了一个1到100之间的整数。\\")\\nprint(\\"你有10次机会来猜这个数字。\\")\\n\\n#
开始游戏循环\\nwhile guesses > 0:\\n    # 获取用户输入并转换为整数\\n    guess =
 int(input(\\"请输入你的猜测:\\"))\\n\\n    # 判断用户输入是否合法\\n    if gue
ss < 1 or guess > 100:\\n        print(\\"请输入一个1到100之间的整数!\\")\\n
     continue\\n\\n   ","wrap":true}]}],"sourceAttributions":[],"feedback":{"tag
":null,"updatedOn":null,"type":"None"},"contentOrigin":"DeepLeo","privacy":null}
],"requestId":"716a5e07-442a-4917-bb24-5575885da73a"}]}\x1e', extra='')

WSMessage(type=<WSMsgType.TEXT: 1>, data='{"type":7,"allowReconnect":true}\x1e',
 extra='')

WSMessage(type=<WSMsgType.CLOSE: 8>, data=1000, extra='')
jarhot1992 commented 1 year ago

I hava the same bugs..... Traceback (most recent call last): File "/root/bing/workspace/bingchat/bing_chat_ask.py", line 31, in asyncio.run(main()) File "/root/miniconda3/envs/python3.10/lib/python3.10/asyncio/runners.py", line 44, in run return loop.run_until_complete(main) File "/root/miniconda3/envs/python3.10/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete return future.result() File "/root/bing/workspace/bingchat/bing_chat_ask.py", line 27, in main print(await bot.ask(prompt="", conversation_style=ConversationStyle.creative)) File "/root/miniconda3/envs/python3.10/lib/python3.10/site-packages/EdgeGPT/EdgeGPT.py", line 98, in ask async for final, response in self.chat_hub.ask_stream( File "/root/miniconda3/envs/python3.10/lib/python3.10/site-packages/EdgeGPT/chathub.py", line 108, in ask_stream objects = msg.data.split(DELIMITER) AttributeError: 'int' object has no attribute 'split'

plageon commented 1 year ago

i have the same problem, looking forward to a sulution Traceback (most recent call last): File "/home/openai/api_caller/edgegpt/views.py", line 31, in index res = (await chat_bot.ask(prompt=json_body["message"], conversation_style=ConversationStyle.creative)) File "/home/openai/anaconda3/lib/python3.10/site-packages/EdgeGPT/EdgeGPT.py", line 98, in ask async for final, response in self.chat_hub.ask_stream( File "/home/openai/anaconda3/lib/python3.10/site-packages/EdgeGPT/chathub.py", line 108, in ask_stream objects = msg.data.split(DELIMITER) AttributeError: 'int' object has no attribute 'split' Unclosed client session client_session: <aiohttp.client.ClientSession object at 0x7f2c8739bf70>

plageon commented 1 year ago

I think i've found the soltion. I followed the example code from src/EdgeGPT.py.

if args.no_stream:
            response = (
                await bot.ask(
                    prompt=question,
                    conversation_style=args.style,
                    wss_link=args.wss_link,
                    search_result=args.search_result,
                    locale=args.locale,
                )
            )["item"]["messages"][1]["adaptiveCards"][0]["body"][0]["text"]
            print(response)
            p_hist(response)
phamxtien commented 1 year ago

I think i've found the soltion. I followed the example code from src/EdgeGPT.py.

if args.no_stream:
            response = (
                await bot.ask(
                    prompt=question,
                    conversation_style=args.style,
                    wss_link=args.wss_link,
                    search_result=args.search_result,
                    locale=args.locale,
                )
            )["item"]["messages"][1]["adaptiveCards"][0]["body"][0]["text"]
            print(response)
            p_hist(response)

Still get error : objects = msg.data.split(DELIMITER) AttributeError: 'int' object has no attribute 'split'

jarhot1992 commented 1 year ago

### Here is the solution


diff --git a/chathub.py b/chathub.py
index 8a2152c..9677b72 100644
--- a/chathub.py
+++ b/chathub.py
@@ -105,6 +105,13 @@ class ChatHub:
         resp_txt_no_link = ""
         while True:
             msg = await self.wss.receive(timeout=900)
\+            data = msg.data
\+            #print(data)
\+            if data is None:
\+                yield True, response
\+                await self.wss_session.close()
\+                await self.wss.close()
\+
             objects = msg.data.split(DELIMITER)
             for obj in objects:
                 if obj is None or not obj:
@@ -186,6 +193,8 @@ class ChatHub:
                     await self.wss_session.close()
                     await self.wss.close()
                     return
\+                elif response.get("type") == 6:
\+                    await self.wss.send_str(append_identifier({"type": 6}))

     async def _initial_handshake(self) -> None:
         await self.wss.send_str(append_identifier({"protocol": "json", "version": 1}))
```diff
manatlan commented 1 year ago

same bug, on v.0.10.5 ;-(

WSServerHandshakeError( aiohttp.client_exceptions.WSServerHandshakeError: 403, message='Invalid response status', url=URL('wss://sydney.bing.com/sydney/ChatHub') 

there should be some basics pytests in the repo ... to verify that the basics works OOTB, before releasing on pypi do you want some ?

phamxtien commented 1 year ago

### Here is the solution

diff --git a/chathub.py b/chathub.py index 8a2152c..9677b72 100644 --- a/chathub.py +++ b/chathub.py @@ -105,6 +105,13 @@ class ChatHub: resp_txt_no_link = "" while True: msg = await self.wss.receive(timeout=900) + data = msg.data + #print(data) + if data is None: + yield True, response + await self.wss_session.close() + await self.wss.close() + objects = msg.data.split(DELIMITER) for obj in objects: if obj is None or not obj: @@ -186,6 +193,8 @@ class ChatHub: await self.wss_session.close() await self.wss.close() return + elif response.get("type") == 6: + await self.wss.send_str(append_identifier({"type": 6}))

 async def _initial_handshake(self) -> None:
     await self.wss.send_str(append_identifier({"protocol": "json", "version": 1}))

I fix by add 2 row : elif response.get("type") == 7: await self.wss.send_str(append_identifier({"type": 7}))

manatlan commented 1 year ago

Here is a PR : https://github.com/acheong08/EdgeGPT/pull/515 to be able to add some basics pytests in the project,

acheong08 commented 1 year ago

@manatlan You seem to have some knowledge of tests (I don't). Mind opening a PR for more comprehensive tests (for different styles etc). Currently got a basic non-streaming test in place

manatlan commented 1 year ago

@acheong08 no problem ! I can add somes (but only on things/api I understand (which seems to be "basic non-streaming"))

MichaelZhouwang commented 1 year ago

I also get this 403 issue. Is there any way to fix it?

manatlan commented 1 year ago

@MichaelZhouwang ... No fix yet. There seems to be a regression since edgegpt use aiohttp for TCP, on some context ;-( For me, I've got this 403 when using edgegpt in a starlette web context ;-( It works on the same machine in a bash context. No trouble with 0.8.2 version