Project Icon

ReEdgeGPT

Python库实现必应AI聊天功能交互

ReEdgeGPT是一个开源Python库,实现了与必应AI聊天功能的交互。该库支持自动化对话、图像生成和插件集成,提供简单易用的API和异步操作。开发者可利用ReEdgeGPT构建聊天机器人和AI应用。项目已在GitHub开源,并提供详细文档。

ReEdgeGPT

Downloads

The reverse engineering the chat feature of the new version of Bing

Documentation Status

ReEdgeGPT Doc Click Here!

If you have any problem watch bottom Q&A first.

  • Notice! Copilot now easier to raise CaptchaChallenge: User needs to solve CAPTCHA to continue.
    • Pls manual send message to Copilot and retry.
    • Microsoft change cookie expiration time from one week to only 3 days.

Another README

繁體中文

Setup

Install package

python3 -m pip install re_edge_gpt --upgrade

Requirements

  • python 3.9+
  • A Microsoft Account with access to https://bing.com/chat (Optional, depending on your region)
  • Required in a supported country or region with New Bing (Chinese mainland VPN required)

Authentication

!!! POSSIBLY NOT REQUIRED ANYMORE !!!

In some regions, Microsoft has made the chat feature available to everyone, so you might be able to skip this step. You can check this with a browser (with user-agent set to reflect Edge), by trying to start a chat without logging in.

It was also found that it might depend on your IP address. For example, if you try to access the chat features from an IP that is known to belong to a datacenter range (vServers, root servers, VPN, common proxies, ...), you might be required to log in while being able to access the features just fine from your home IP address.

If you receive the following error, you can try providing a cookie and see if it works then:

Exception: Authentication failed. You have not been accepted into the beta.

Collect cookies

  • a) (Easy) Install the latest version of Microsoft Edge
  • b) (Advanced) Alternatively, you can use any browser and set the user-agent to look like you're using Edge (e.g., 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). You can do this easily with an extension like "User-Agent Switcher and Manager" for Chrome and Firefox.
  1. Get a browser that looks like Microsoft Edge.
  2. Open bing.com/chat
  3. If you see a chat feature, you are good to continue...
  4. Install the cookie editor extension for Chrome or Firefox
  5. Go to bing.com/chat
  6. Open the extension
  7. Click "Export" on the bottom right, then "Export as JSON" (This saves your cookies to clipboard)
  8. Paste your cookies into a file bing_cookies.json.
    • NOTE: The cookies file name MUST follow the regex pattern bing_cookies.json, so that they could be recognized by internal cookie processing mechanisms

Use cookies in code:

import json
from re_edge_gpt import Chatbot


async def create_bot():
    cookies = json.loads(open("./path/to/bing_cookies.json", encoding="utf-8").read())
    bot = await Chatbot.create(cookies=cookies)
    return bot

How to use Chatbot

Run from Command Line

 $ python3 -m re_edge_gpt -h

        ReEdgeGPT - A demo of reverse engineering the Bing GPT chatbot

        !help for help

        Type !exit to exit

usage: __main__.py [-h] [--enter-once] [--search-result] [--no-stream] [--rich] [--proxy PROXY] [--wss-link WSS_LINK]
                  [--style {creative,balanced,precise}] [--prompt PROMPT] [--cookie-file COOKIE_FILE]
                  [--history-file HISTORY_FILE] [--locale LOCALE]

options:
  -h, --help            show this help message and exit
  --enter-once
  --search-result
  --no-stream
  --rich
  --proxy PROXY         Proxy URL (e.g. socks5://127.0.0.1:1080)
  --wss-link WSS_LINK   WSS URL(e.g. wss://sydney.bing.com/sydney/ChatHub)
  --style {creative,balanced,precise}
  --prompt PROMPT       prompt to start with
  --cookie-file COOKIE_FILE
                        path to cookie file
  --history-file HISTORY_FILE
                        path to history file
  --locale LOCALE       your locale (e.g. en-US, zh-CN, en-IE, en-GB)

(China/US/UK/Norway has enhanced support for locale)

Run in Python

1. The Chatbot class and asyncio for more granular control

Use Async for the best experience, for example:

import asyncio
import json
from pathlib import Path

from re_edge_gpt import Chatbot
from re_edge_gpt import ConversationStyle


# If you are using jupyter pls install this package
# from nest_asyncio import apply


async def test_ask() -> None:
    bot = None
    try:
        cookies = json.loads(open(
            str(Path(str(Path.cwd()) + "/bing_cookies.json")), encoding="utf-8").read())
        bot = await Chatbot.create(cookies=cookies)
        response = await bot.ask(
            prompt="How to boil the egg",
            conversation_style=ConversationStyle.balanced,
            simplify_response=True
        )
        # If you are using non ascii char you need set ensure_ascii=False
        print(json.dumps(response, indent=2, ensure_ascii=False))
        # Raw response
        # print(response)
        assert response
    except Exception as error:
        raise error
    finally:
        if bot is not None:
            await bot.close()


if __name__ == "__main__":
    # If you are using jupyter pls use nest_asyncio apply()
    # apply()
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        loop = asyncio.get_event_loop()
    loop.run_until_complete(test_ask())


Use copilot as default mode

Collect cookies

  • a) (Easy) Install the latest version of Microsoft Edge
  • b) (Advanced) Alternatively, you can use any browser and set the user-agent to look like you're using Edge (e.g., 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). You can do this easily with an extension like "User-Agent Switcher and Manager" for Chrome and Firefox.
  1. Get a browser that looks like Microsoft Edge.
  2. Open copilot.microsoft.com
  3. If you see a chat feature, you are good to continue...
  4. Install the cookie editor extension for Chrome or Firefox
  5. Go to copilot.microsoft.com)
  6. Open the extension
  7. Click "Export" on the bottom right, then "Export as JSON" (This saves your cookies to clipboard)
  8. Paste your cookies into a file copilot_cookies.json.
    • NOTE: The cookies file name MUST follow the regex pattern copilot_cookies.json, so that they could be recognized by internal cookie processing mechanisms

Use cookies in code:

import asyncio
import json
from pathlib import Path

from re_edge_gpt import Chatbot
from re_edge_gpt import ConversationStyle


# If you are using jupyter pls install this package
# from nest_asyncio import apply


async def test_ask() -> None:
   bot = None
   try:
      mode = "Copilot"
      if mode == "Bing":
         cookies: list[dict] = json.loads(open(
            str(Path(str(Path.cwd()) + "/bing_cookies.json")), encoding="utf-8").read())
      else:
         cookies: list[dict] = json.loads(open(
            str(Path(str(Path.cwd()) + "/copilot_cookies.json")), encoding="utf-8").read())
      # Notice when mode != "Bing" (Bing is default) will set mode is copilot
      bot = await Chatbot.create(cookies=cookies, mode=mode)
      response = await bot.ask(
         prompt="Is your name Copilot",
         conversation_style=ConversationStyle.balanced,
         simplify_response=True
      )
      # If you are using non ascii char you need set ensure_ascii=False
      print(json.dumps(response, indent=2, ensure_ascii=False))
      # Raw response
      # print(response)
      assert response
   except Exception as error:
      raise error
   finally:
      if bot is not None:
         await bot.close()


if __name__ == "__main__":
   # If you are using jupyter pls use nest_asyncio apply()
   # apply()
   try:
      loop = asyncio.get_running_loop()
   except RuntimeError:
      loop = asyncio.get_event_loop()
   loop.run_until_complete(test_ask())

When u ask copilot what is your name

are_u_bing.png

How to generate image

Getting authentication

Chromium based browsers (Edge, Opera, Vivaldi, Brave)

  • Go to https://bing.com/
  • F12 to open console
  • In the JavaScript console, type cookieStore.get("_U").then(result => console.log(result.value)) and press enter
  • Copy the output. This is used in --U or auth_cookie.

Firefox

  • Go to https://bing.com/.
  • F12 to open developer tools
  • navigate to the storage tab
  • expand the cookies tab
  • click on the https://bing.com cookie
  • copy the value from the _U
import os
import shutil
from pathlib import Path

from re_edge_gpt import ImageGen, ImageGenAsync

# create a temporary output directory for testing purposes
test_output_dir = "test_output"
# download a test image
test_image_url = "https://picsum.photos/200"
auth_cooker = open("bing_cookies.txt", "r+").read()
sync_gen = ImageGen(auth_cookie=auth_cooker)
async_gen = ImageGenAsync(auth_cookie=auth_cooker)


def test_save_images_sync():
    sync_gen.save_images([test_image_url], test_output_dir)
    sync_gen.save_images([test_image_url], test_output_dir, file_name="test_image")
    # check if the image was downloaded and saved correctly
    assert os.path.exists(os.path.join(test_output_dir, "test_image_0.jpeg"))
    assert os.path.exists(os.path.join(test_output_dir, "0.jpeg"))


# Generate image list sync
def test_generate_image_sync():
    image_list = sync_gen.get_images("tree")
    print(image_list)

if __name__ == "__main__":
    # Make dir to save image
    Path("test_output").mkdir(exist_ok=True)
    # Save image
    test_save_images_sync()
    # Generate image sync
    test_generate_image_sync()
    # Remove dir
    shutil.rmtree(test_output_dir)

Plugins support

https://github.com/Integration-Automation/ReEdgeGPT/issues/119

Example:

import asyncio
import json
from pathlib import Path
from random import choice
from string import ascii_uppercase

from re_edge_gpt import Chatbot
from re_edge_gpt import ConversationStyle


# If you are using jupyter pls install this package
# from nest_asyncio import apply


async def test_ask() -> None:
    bot = None
    try:
        cookies: list[dict] = json.loads(open(
            str(Path(str(Path.cwd()) + "/bing_cookies.json")), encoding="utf-8").read())
        bot = await Chatbot.create(cookies=cookies, mode="Bing", plugin_ids=["c310c353-b9f0-4d76-ab0d-1dd5e979cf68"])
        prompt = """Rome (Italian and Latin: Roma, Italian: [ˈroːma] ⓘ) is the capital city of Italy. It is also the capital of the Lazio region, the centre of the Metropolitan City of Rome Capital, and a special comune (municipality) named Comune di Roma Capitale. With 2,860,009 residents in 1,285 km2 (496.1 sq mi),[2] Rome is the country's most populated comune and the third most populous city in the European Union by population within city limits. The Metropolitan City of Rome, with a population of 4,355,725 residents, is the most populous metropolitan city in Italy.[3] Its metropolitan area is the third-most populous within Italy.[5] Rome is located in the central-western portion of the Italian Peninsula, within Lazio (Latium), along the shores of the Tiber. Vatican City (the smallest country in the world)[6] is an independent country inside the city boundaries of Rome, the only existing example of a country within a city. Rome is often referred to as the City of Seven Hills due to its geographic location, and also as the "Eternal City". Rome is generally considered to be the cradle of Western civilization and Western Christian culture, and the centre of the Catholic Church.[7][8][9]

Rome's history spans 28 centuries. While Roman mythology dates the founding of Rome at around 753 BC, the site has been inhabited for much longer, making it a major human settlement for almost three millennia and one of the oldest continuously occupied cities in Europe.[10] The city's early population originated from a mix of Latins, Etruscans, and Sabines. Eventually, the city successively became the capital of the Roman Kingdom, the Roman Republic and the Roman Empire, and is regarded by many as the first-ever Imperial city and metropolis.[11] It was first called The Eternal City (Latin: Urbs Aeterna; Italian: La Città Eterna) by the Roman poet Tibullus in the 1st century BC, and the expression was also taken up by Ovid, Virgil, and Livy.[12][13] Rome is also called "Caput Mundi" (Capital of the World).

After the fall of the Empire in the west, which marked the beginning of the Middle Ages, Rome slowly fell under the political control of the Papacy, and in the 8th century, it became the capital of the Papal States, which lasted until 1870. Beginning with the Renaissance, almost all popes since Nicholas V (1447–1455) pursued a coherent architectural and urban programme over four hundred years, aimed at making the city the artistic and cultural centre of the world.[14] In this way, Rome first became one of the major centres of the Renaissance[15] and then became the birthplace of both the Baroque style and Neoclassicism. Famous artists, painters, sculptors, and architects made Rome the centre of their activity, creating masterpieces throughout the city. In 1871, Rome became the capital of the Kingdom of Italy, which, in 1946, became the Italian Republic.

In 2019, Rome was the 14th most visited city in the world, with 8.6 million tourists, the third most visited city in the European Union, and the most popular tourist destination in Italy.[16] Its historic centre is listed by UNESCO as a World Heritage Site.[17] The host city for the 1960 Summer Olympics, Rome is also the seat of several specialised agencies of the United Nations, such as the Food and Agriculture Organization (FAO), the World Food Programme (WFP) and the International Fund for Agricultural Development (IFAD). The city also hosts the Secretariat of the Parliamentary Assembly of the Union for the Mediterranean[18] (UfM) as well as the headquarters of many multinational companies, such as Eni, Enel, TIM, Leonardo, and banks such as BNL. Numerous companies are based within Rome's EUR business district, such as the luxury fashion house Fendi located in the Palazzo della Civiltà Italiana. The presence of renowned international brands in the city has made Rome an important centre of fashion and design, and the Cinecittà Studios have been the set of many Academy Award–winning movies.[19]

Name and symbol
Etymology
According to the Ancient Romans' founding myth,[20] the name Roma came from the city's founder and first king, Romulus.[1]

However, it is possible that the name Romulus was actually derived from Rome itself.[21] As early as the 4th century, there have been alternative theories proposed on the origin of the name Roma. Several hypotheses have been advanced focusing on its linguistic roots which however remain uncertain:[22]

From Rumon or Rumen, archaic name of the Tiber,
项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

吐司

探索Tensor.Art平台的独特AI模型,免费访问各种图像生成与AI训练工具,从Stable Diffusion等基础模型开始,轻松实现创新图像生成。体验前沿的AI技术,推动个人和企业的创新发展。

Project Cover

SubCat字幕猫

SubCat字幕猫APP是一款创新的视频播放器,它将改变您观看视频的方式!SubCat结合了先进的人工智能技术,为您提供即时视频字幕翻译,无论是本地视频还是网络流媒体,让您轻松享受各种语言的内容。

Project Cover

美间AI

美间AI创意设计平台,利用前沿AI技术,为设计师和营销人员提供一站式设计解决方案。从智能海报到3D效果图,再到文案生成,美间让创意设计更简单、更高效。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号