Skip to main content

Reverse engineered Edge Chat API

Project description

EdgeGPT

Edge GPT

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

English - 简体中文 - 繁體中文 - Español - 日本語

PyPI version Python version Total downloads

Setup

Install package

python3 -m pip install EdgeGPT --upgrade

Requirements

  • python 3.8+
  • A Microsoft Account with early access to https://bing.com/chat (Required)
  • Required in a supported country with New Bing (Chinese mainland VPN required)
  • Selenium (for automatic cookie setup)

Authentication (Required)

  1. Install the latest version of Microsoft Edge
  2. 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.
  3. Open bing.com/chat
  4. If you see a chat feature, you are good to continue...
  5. Install the cookie editor extension for Chrome or Firefox
  6. Go to bing.com
  7. Open the extension
  8. Click "Export" on the bottom right, then "Export as JSON" (This saves your cookies to clipboard)
  9. Paste your cookies into a file cookies.json

Instead of following steps 5-9 you can also use the following experimental helper function which has been tested on Windows 11 and requires Selenium and the latest version of Microsoft Edge:

pip install selenium
from EdgeGPT import Cookie
Cookie.fetch_default()

This will automatically create a file called bing_cookies__default.json in your current working directory.

The double underscore in the name ensures it always gets used first if you have other cookie files e.g. bing_cookies_pete.json (see below regarding multiple cookie files).

The bing_ prefix in the name should avoid confusion with any other cookie files you might be using and is also used as a default by the Cookie helper class (see later).

Chatbot

Running from the Command Line

 $ python3 -m EdgeGPT -h

        EdgeGPT - A demo of reverse engineering the Bing GPT chatbot
        Repo: github.com/acheong08/EdgeGPT
        By: Antonio Cheong

        !help for help

        Type !exit to exit
        Enter twice to send message or set --enter-once to send one line message

usage: EdgeGPT.py [-h] [--enter-once] [--no-stream] [--rich] [--proxy PROXY] [--wss-link WSS_LINK] [--style {creative,balanced,precise}]
                  [--cookie-file COOKIE_FILE]

options:
  -h, --help            show this help message and exit
  --enter-once
  --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}
  --cookie-file COOKIE_FILE
                        needed if environment variable COOKIE_FILE is not set

Running in Python

1) The Chatbot class and asyncio for more granular control

There are three main ways to pass in cookies:

  • Environment variable: export COOKIE_FILE=/path/to/cookies.json.

  • Specify the path to cookies.json in the argument cookie_path like this:

    bot = await Chatbot.create(cookie_path='./cookies.json')
    
  • Pass in the cookies directly by the argument cookies, like this:

    with open('./cookies.json', 'r') as f:
        cookies = json.load(f)
    bot = await Chatbot.create(cookies=cookies)
    

Use Async for the best experience, for example:

import asyncio
from EdgeGPT import Chatbot, ConversationStyle

async def main():
    bot = await Chatbot.create()
    print(await bot.ask(prompt="Hello world", conversation_style=ConversationStyle.creative))
    await bot.close()

if __name__ == "__main__":
    asyncio.run(main())

2) The Query and Cookie helper classes

Create a simple Bing Chat AI query (using the 'precise' conversation style by default) and see just the main text output rather than the whole API response:

from EdgeGPT import Query, Cookie

q = Query("What are you? Give your answer as Python code")
print(q)

Or change the conversation style or cookie file to be used:

q = Query(
  "What are you? Give your answer as Python code",
  style="creative",  # or 'balanced'
  cookies="./bing_cookies_alternative.json"
)

Quickly extract the text output, code snippets, list of sources/references, or suggested follow-on questions using the following attributes:

q.output
q.code
q.suggestions
q.sources       # for the full json output
q.sources_dict  # for a dictionary of titles and urls

Get the orginal prompt and the conversation style you specified:

q.prompt
q.style
repr(q)

Access previous Queries made since importing Query:

Query.index  # A list of Query objects; updated dynamically
Query.request_count  # A tally of requests made using each cookie file

And finally, the Cookie class supports multiple cookie files, so if you create additional cookie files with the naming convention bing_cookies_*.json, your queries will automatically try using the next file (alphabetically) if you've exceeded your daily quota of requests (currently set at 200).

Here are the main attributes which you can access:

Cookie.current_file_index
Cookie.dirpath
Cookie.search_pattern  # default is `bing_cookies_*.json`
Cookie.files()  # list as files that match .search_pattern
Cookie.current_filepath
Cookie.current_data
Cookie.import_next()
Cookie.image_token
Cookie.ignore_files

Running with Docker

This assumes you have a file cookies.json in your current working directory

docker run --rm -it -v $(pwd)/cookies.json:/cookies.json:ro -e COOKIE_FILE='/cookies.json' ghcr.io/acheong08/edgegpt

You can add any extra flags as following

docker run --rm -it -v $(pwd)/cookies.json:/cookies.json:ro -e COOKIE_FILE='/cookies.json' ghcr.io/acheong08/edgegpt --rich --style creative

Image generator

Running from the Command Line

$ python3 -m ImageGen -h
usage: ImageGen.py [-h] [-U U] [--cookie-file COOKIE_FILE] --prompt PROMPT [--output-dir OUTPUT_DIR] [--quiet] [--asyncio]

optional arguments:
  -h, --help            show this help message and exit
  -U U                  Auth cookie from browser
  --cookie-file COOKIE_FILE
                        File containing auth cookie
  --prompt PROMPT       Prompt to generate images for
  --output-dir OUTPUT_DIR
                        Output directory
  --quiet               Disable pipeline messages
  --asyncio             Run ImageGen using asyncio

Running in Python

1) The ImageQuery helper class

Generate images based on a simple prompt and download to the current working directory:

from EdgeGPT import ImageQuery

q=ImageQuery("Meerkats at a garden party in Devon")

Change the download directory for all future images in this session:

Query.image_dirpath = Path("./to_another_folder")

2) The ImageGen class and asyncio for more granular control

from ImageGen import ImageGen
import argparse
import json

async def async_image_gen(args) -> None:
    async with ImageGenAsync(args.U, args.quiet) as image_generator:
        images = await image_generator.get_images(args.prompt)
        await image_generator.save_images(images, output_dir=args.output_dir)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-U", help="Auth cookie from browser", type=str)
    parser.add_argument("--cookie-file", help="File containing auth cookie", type=str)
    parser.add_argument(
        "--prompt",
        help="Prompt to generate images for",
        type=str,
        required=True,
    )
    parser.add_argument(
        "--output-dir",
        help="Output directory",
        type=str,
        default="./output",
    )
    parser.add_argument(
        "--quiet", help="Disable pipeline messages", action="store_true"
    )
    parser.add_argument(
        "--asyncio", help="Run ImageGen using asyncio", action="store_true"
    )
    args = parser.parse_args()
    # Load auth cookie
    with open(args.cookie_file, encoding="utf-8") as file:
        cookie_json = json.load(file)
        for cookie in cookie_json:
            if cookie.get("name") == "_U":
                args.U = cookie.get("value")
                break

    if args.U is None:
        raise Exception("Could not find auth cookie")

    if not args.asyncio:
        # Create image generator
        image_generator = ImageGen(args.U, args.quiet)
        image_generator.save_images(
            image_generator.get_images(args.prompt),
            output_dir=args.output_dir,
        )
    else:
        asyncio.run(async_image_gen(args))

Star History

Star History Chart

Contributors

This project exists thanks to all the people who contribute.

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

EdgeGPT-0.4.4.tar.gz (15.8 kB view hashes)

Uploaded Source

Built Distribution

EdgeGPT-0.4.4-py3-none-any.whl (16.0 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page