Skip to content

The unofficial python package that returns response of Google Bard through cookie value.

License

Notifications You must be signed in to change notification settings

duanyu1988/Bard-API

 
 

Repository files navigation

Development Status :: 5 - Production/Stable

Google Bard API

PyPI package Code style: black PyPI

The python package that returns response of Google Bard through value of cookie.

Please exercise caution and use this package responsibly.

I referred to this github repository(github.com/acheong08/Bard) where inference process of Bard was reverse engineered. Using __Secure-1PSID, you can ask questions and get answers from Google Bard. This package is designed for application to the Python package ExceptNotifier and Co-Coder. Please note that the bardapi is not a free service, but rather a tool provided to assist developers with testing certain functionalities due to the delayed development and release of Google Bard's API. It has been designed with a lightweight structure that can easily adapt to the emergence of an official API. Therefore, I strongly discourage using it for any other purposes.


Do not expose the __Secure-1PSID

Note that while I referred to __Secure-1PSID value as an API KEY for convenience, it is not an officially provided API KEY. Cookie value subject to frequent changes. Verify the value again if an error occurs. Most errors occur when an invalid cookie value is entered.


Bard API is unofficial project

Currently, there is no official API from Google. However, if an official API is released, I will make sure to announce it prominently at the top of the repository's readme.

Official API of Bard is still not released. https://www.googlecloudcommunity.com/gc/AI-ML/Google-Bard-API/m-p/538517


Open LLM

Alternatively, you can use Open LLM models according to the terms of the license. https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard


Amazing Bard Prompts Is All You Need!

  • Helpful prompts for Google Bard

Install

If you will not provide the language parameter (use english, korean, japanese only as input text):

pip install bardapi

If you wish to use the Bard API, including various features:

pip install git+https://github.com/dsdanielpark/Bard-API.git

Authentication

  1. Visit https://bard.google.com/
  2. F12 for console
  3. Session: Application → Cookies → Copy the value of __Secure-1PSID cookie.

Usage

Open In Colab

Simple Usage

from bardapi import Bard

token = 'xxxxxxxxxx'
bard = Bard(token=token)
bard.get_answer("나와 내 동년배들이 좋아하는 뉴진스에 대해서 알려줘")['content']

Or you can use this

from bardapi import Bard
import os
os.environ['_BARD_API_KEY']="xxxxxxxx"

Bard().get_answer("나와 내 동년배들이 좋아하는 뉴진스에 대해서 알려줘")['content']

To get reponse dictionary

import bardapi
import os

# set your __Secure-1PSID value to key
token = 'xxxxxxxxxx'

# set your input text
input_text = "나와 내 동년배들이 좋아하는 뉴진스에 대해서 알려줘"

# Send an API request and get a response.
response = bardapi.core.Bard(token).get_answer(input_text)

Addressing errors caused by delayed responses in environments like Google Colab and containers. If an error occurs despite following the proper procedure, utilize the timeout argument.

from bardapi import Bard
import os
os.environ['_BARD_API_KEY']="xxxxxxxx"

bard = Bard(timeout=30) # Set timeout in seconds
bard.get_answer("나와 내 동년배들이 좋아하는 뉴진스에 대해서 알려줘")['content']

Further

Behind a proxy

If you are working behind a proxy, use the following.

from bardapi import Bard
import os

# Change 'http://proxy.example.com:8080' to your http proxy
# timeout in seconds
proxies = {
    'http': 'http://proxy.example.com:8080',
    'https': 'https://proxy.example.com:8080'
}

bard = Bard(token='xxxxxxxxxx', proxies=proxies, timeout=30)
bard.get_answer("나와 내 동년배들이 좋아하는 뉴진스에 대해서 알려줘")['content']

Reusable session object

You can continue the conversation using a reusable session.

from bardapi import Bard
import os
import requests
os.environ['_BARD_API_KEY'] = 'xxxxxxxxxxx'
# token='xxxxxxxxxxx'

session = requests.Session()
session.headers = {
            "Host": "bard.google.com",
            "X-Same-Domain": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36",
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
            "Origin": "https://bard.google.com",
            "Referer": "https://bard.google.com/",
        }
session.cookies.set("__Secure-1PSID", os.getenv("_BARD_API_KEY")) 
# session.cookies.set("__Secure-1PSID", token) 

bard = Bard(token=token, session=session, timeout=30)
bard.get_answer("나와 내 동년배들이 좋아하는 뉴진스에 대해서 알려줘")['content']

# Continued conversation without set new session
bard.get_answer("What is my last prompt??")['content']

GitHub installation required for the following features.

To remove the dependencies of the bardapi package, you need to install the GitHub developer version.

pip install git+https://github.com/dsdanielpark/Bard-API.git

Multi-language Bard API

GitHub Dev version only.

from bardapi import Bard

bard = Bard(token='xxxxxxxx', language='chinese (simplified)')
res = bard.get_answer("你好。")
print(res['content'])

or

from bardapi import Bard
import os
os.environ["_BARD_API_LANG"] = 'chinese (simplified)'
os.environ["_BARD_API_KEY"] = 'xxxxxxxx'

res = Bard().get_answer("你好。")
print(res['content'])

Get image links

GitHub Dev version only.

from bardapi import Bard
bard = Bard(token='xxxxxxxxxxx')
res = bard.get_answer("Find me an image of the main entrance of Stanford University.")
res['links'] # Get image links (list)
res['images'] # Get images (set)


ChatBard

from bardapi import ChatBard
    
chat = ChatBard()
chat.start()

or

from bardapi import ChatBard
import os
os.environ["_BARD_API_KEY"] = 'xxxxxx'   # Requird
os.environ["_BARD_API_LANG"] = Arabic    # Optional, Default to English
os.environ["_BARD_API_TIMEOUT"] = 30     # Optional, Session Timeout
 
chat = ChatBard()
chat.start()

or

from bardapi import Bard, SESSION_HEADERS
import os
import requests

token='xxxxxxxxxxx'
session = requests.Session()
session.headers = SESSION_HEADERS
session.cookies.set("__Secure-1PSID", token) 
proxies = {
    'http': 'http://proxy.example.com:8080',
    'https': 'https://proxy.example.com:8080'
}
    
ChatBard(token=token, session=session, proxies=proxies, timeout=40, language="chinese (simplified)").start()

Executing Python code received as a response from Bard

GitHub Dev version only.

from bardapi import Bard
    
bard = Bard(token="xxxxxxxx", run_code=True)
bard.get_answer("code a pie chart in python for this data={'blue':25, 'red':30, 'green':30, 'purple':15}")


Translation to Another Programming Language

Please check the translation results in this folder.

  • Copy the code of Core.py.
  • Ask ChatGPT to translate like "Translate to Swift."
  • Ask ChatGPT to optimize the code or provide any desired instructions until you're satisfied.

Scripts

In the scripts folder, I have released a script to help you compare OpenAI-ChatGPT, Microsoft-EdgeGPT and Google-Bard. I hope they will help more developers.

Shifting Service Policies: Bard and Google's Dynamics

Bard's service status and Google's API interfaces are in constant flux. The number of replies is currently limited, but certain users, such as those utilizing VPNs or proxy servers, have reported slightly higher message caps. Adaptability is crucial in navigating these dynamic service policies. Please note that the cookie values used in this package are not official API values.

License

MIT
I hold no legal responsibility; for more information, please refer to the bottom of the readme file. I just want you to give me and them a star.

The MIT License (MIT)

Copyright (c) 2023 Minwoo Park

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Bugs and Issues

Sincerely grateful for any reports on new features or bugs. Your valuable feedback on the code is highly appreciated.

Contacts

Reference

[1] https://github.com/acheong08/Bard
[2] https://github.com/discordtehe/Bard


Important Notice

The user assumes all legal responsibilities associated with using the BardAPI package. This Python package merely facilitates easy access to Google Bard for developers. Users are solely responsible for managing data and using the package appropriately. For further information, please consult the Google Bard Official Document.

Caution!

This Python package is not an official Google package or API service. It is not affiliated with Google and uses Google account cookies, which means that excessive or commercial usage may result in restrictions on your Google account. The package was created to support developers in testing functionalities due to delays in the official Google package. However, it should not be misused or abused. Please be cautious and refer to the Readme for more information.

Copyright (c) 2023 MinWoo Park, South Korea

About

The unofficial python package that returns response of Google Bard through cookie value.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Python 29.5%
  • Jupyter Notebook 12.6%
  • Swift 8.5%
  • C# 7.8%
  • Java 7.3%
  • Go 7.3%
  • Other 27.0%