python实现本地化bingBot
# --* encoding=utf8 *--
'''
命令模式基本完成
'''
import asyncio
import json
import re
from prompt_toolkit import PromptSession
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.history import InMemoryHistory
from EdgeGPT import Chatbot, ConversationStyle
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
bingcookiefile = './bingcookies.json'
with open(bingcookiefile, 'r') as f:
cookies = json.load(f)
bot = Chatbot(cookies=cookies)
async def main(query):
bot = Chatbot(cookies=cookies)
response_dict = await bot.ask(prompt=query, conversation_style=ConversationStyle.creative)
# json_str = json.dumps(response_dict)
# json_str = json.loads(json_str)
#
# print("JSON: \n" + str(json_str))
suggestedResponses = [] # 提示再次发送的语句
messageText = query
response = ''
spokenText = ''
try:
tempresponsedict = response_dict['item']['messages']
if len(tempresponsedict) == 1:
if 'text' in response_dict['item']['messages'][1]:
response = re.sub(r'\[\^\d\^\]', '',
response_dict['item']['messages'][1]['text'])
else:
response = "Something wrong. Please reset chat"
# 解释返回的bing建议
if 'suggestedResponses' in response_dict['item']['messages'][1]:
suggestedResponses0 = re.sub(
r'\[\^\d\^\]', '', response_dict['item']['messages'][1]['suggestedResponses'][0]['text'])
response = response + "\n ---------------------------------------------"
response = response + "\n 1.[%s]" % (suggestedResponses0)
suggestedResponses1 = re.sub(
r'\[\^\d\^\]', '', response_dict['item']['messages'][1]['suggestedResponses'][1]['text'])
response = response + "2.[%s]\n" % (suggestedResponses1)
suggestedResponses2 = re.sub(
r'\[\^\d\^\]', '', response_dict['item']['messages'][1]['suggestedResponses'][2]['text'])
response = response + "3.[%s]\n" % (suggestedResponses2)
else:
suggestedResponses = ''
if 'spokenText' in response_dict['item']['messages'][1]:
spokenText = response_dict['item']['messages'][1]['spokenText']
response = response + "\n ---------------------------------------------"
response = response + "\n参考:[%s]" % (spokenText)
else:
for tmpdata in tempresponsedict:
if 'text' in tmpdata:
response = response + re.sub(r'\[\^\d\^\]', '', tmpdata['text'])
if 'suggestedResponses' in tmpdata:
suggestedResponses0 = re.sub(r'\[\^\d\^\]', '', tmpdata['suggestedResponses'][0]['text'])
suggestedResponses1 = re.sub(r'\[\^\d\^\]', '', tmpdata['suggestedResponses'][1]['text'])
suggestedResponses2 = re.sub(r'\[\^\d\^\]', '', tmpdata['suggestedResponses'][2]['text'])
else:
suggestedResponses = ''
if 'spokenText' in tmpdata:
spokenText = tmpdata['spokenText']
response = response + "\n ---------------------------------------------"
response = response + "\n1.[%s]" % (suggestedResponses0)
response = response + "\n2.[%s]" % (suggestedResponses1)
response = response + "\n3.[%s]" % (suggestedResponses2)
response = response + "\n ---------------------------------------------"
response = response + "\n\n参考:\t[%s]\n" % (spokenText)
if 'maxNumUserMessagesInConversation' in response_dict['item'][
'throttling'] and 'numUserMessagesInConversation' in \
response_dict['item']['throttling']:
maxNumUserMessagesInConversation = response_dict['item'][
'throttling']['maxNumUserMessagesInConversation']
numUserMessagesInConversation = response_dict['item']['throttling']['numUserMessagesInConversation']
response = response + "\n---------------------------------------------\n"
response = response + "Messages In Conversation : %d / %d" % (
numUserMessagesInConversation, maxNumUserMessagesInConversation)
if int(numUserMessagesInConversation) >= maxNumUserMessagesInConversation:
await bot.reset() #
response = response + "\n Automatic reset succeeded?"
if (len(response_dict['item']['messages'][1]['sourceAttributions']) >= 3):
providerDisplayName0 = re.sub(
r'\[\^\d\^\]', '', response_dict['item']['messages'][1]['sourceAttributions'][0]['providerDisplayName'])
seeMoreUrl0 = re.sub(
r'\[\^\d\^\]', '', response_dict['item']['messages'][1]['sourceAttributions'][0]['seeMoreUrl'])
providerDisplayName1 = re.sub(
r'\[\^\d\^\]', '', response_dict['item']['messages'][1]['sourceAttributions'][1]['providerDisplayName'])
seeMoreUrl1 = re.sub(
r'\[\^\d\^\]', '', response_dict['item']['messages'][1]['sourceAttributions'][1]['seeMoreUrl'])
providerDisplayName2 = re.sub(
r'\[\^\d\^\]', '', response_dict['item']['messages'][1]['sourceAttributions'][2]['providerDisplayName'])
seeMoreUrl2 = re.sub(
r'\[\^\d\^\]', '', response_dict['item']['messages'][1]['sourceAttributions'][2]['seeMoreUrl'])
response = response + "\n\n--------------------\nReference:\n"
response = response + \
"1.[%s](%s)\n" % (providerDisplayName0, seeMoreUrl0)
response = response + \
"2.[%s](%s)\n" % (providerDisplayName1, seeMoreUrl1)
response = response + \
"3.[%s](%s)\n" % (providerDisplayName2, seeMoreUrl2)
except BaseException as B:
print(B)
print("问题->:" + messageText + "\n" + "回答->:" + response)
print('\n')
return response
async def get_input_async(
session: PromptSession = None,
completer: WordCompleter = None,
) -> str:
"""
Multiline input function.
"""
return await session.prompt_async(
completer=completer,
multiline=True,
auto_suggest=AutoSuggestFromHistory(),
)
def create_session() -> PromptSession:
return PromptSession(history=InMemoryHistory())
if __name__ == '__main__':
session = create_session()
while True:
question = input('请提问:\t')
# query='给我用python写一段代码,实现与webUI交互式聊天,要求有比较漂亮界面设计'
if question == "!exit":
break
elif question == "!help":
print(
"""
!help - Show this help message
!exit - Exit the program
!reset - Reset the conversation
""",
)
continue
elif question == "!reset":
bot.reset()
continue
asyncio.run(main(question))
运行前安装好依赖包,然后将bing的cookies 粘贴到bingcookies.json里
使用说明:
安装包
python3 -m pip install EdgeGPT --upgrade
要求
- python 3.8+
- 可以提前访问https://bing.com/chat的 Microsoft 帐户(必需)
- 在受支持的国家需要 New Bing(需要 VPN)
检查访问权限(必填)
- 安装最新版本的 Microsoft Edge
- 或者,您可以使用任何浏览器并将用户代理设置为看起来像您正在使用 Edge(例如,
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 Edg/111.0.1661.51
)。您可以使用Chrome和Firefox的“User-Agent Switcher and Manager”等扩展轻松地做到这一点。 - 打开bing.com/chat
- 如果您看到聊天功能,那您就可以开始了
一条评论
aifamilyadmin
李厚霖在