Git Product home page Git Product logo

dsdanielpark / bard-api Goto Github PK

View Code? Open in Web Editor NEW
5.4K 48.0 535.0 17.31 MB

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

Home Page: https://pypi.org/project/bardapi/

License: MIT License

Python 74.72% Jupyter Notebook 1.43% TypeScript 0.26% Go 0.41% Java 0.42% JavaScript 20.74% PHP 0.29% Kotlin 0.34% Rust 0.39% Swift 0.48% C# 0.51%
google-bard google-bard-python chatbot nlp google llm api bard ai-api googlebard

bard-api's Introduction

Development Status :: 7 - Inactive


[NOTICE]

Please, go to Gemini Icon Gemini API

A unofficial Python wrapper, python-gemini-api, operates through reverse-engineering, utilizing cookie values to interact with Google Gemini for users struggling with frequent authentication problems or unable to authenticate via Google Authentication.

Collaborated competently with Antonio Cheong.

Installation

pip install python-gemini-api
pip install git+https://github.com/dsdanielpark/Gemini-API.git

For the updated version, use as follows:

pip install -q -U python-gemini-api






Reflection on the Bard API Project #289

Gemini Icon Google - Bard API

PyPI package Code style: black 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. This python package is UNOFFICIAL.

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. 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. If you have access to reliable official PaLM-2 API or Google Generative AI API, replace the provided response with the corresponding official code. Check out #262.



What is Google Bard?

Bard is a conversational generative artificial intelligence chatbot developed by Google, based initially on the LaMDA family of LLMs(Large Language Models) and later the PaLM LLM. Please check official documents for updates on Bard, including available regions and languages.

Install

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

Due to certain dependency packages that are not compatible with 64bit windows(OS), we are releasing a lightweight alpha release of bard that only returns responses for simple requests. This release is a continuation of the pypi 0.1.18 version, which was maintained with lightweight and simple functionality. See alpha-release github branch for more details.

$ pip install bardapi==0.1.23a

Authentication

Warning Do not expose the __Secure-1PSID. For testing purposes only; avoid direct application use. Cookie values change periodically (every 15-20 minutes). Frequent session changes may briefly block access; headless mode is challenging. Rate limiting applies and changes often. If the cookie changes, log out of your Google account, close the browser, and enter the new cookie value. Or manually reset the cookie for a new value. See FAQ and issue pages for details.

  1. Visit https://gemini.google.com/
  2. F12 for console
  3. Session: Application → Cookies → Copy the value of __Secure-1PSID cookie. Or try to use SIDCC as token.

Note that while I referred to __Secure-1PSID or SIDCC 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.


If you need to set multiple cookie values:

  • Multi-cookie Bard - After confirming that multiple cookie values are required to receive responses reliably in certain countries, I will deploy it for testing purposes. Please debug and create a pull request.

Usage

Open In Colab

Simple Usage

from bardapi import Bard

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

Or you can use this

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

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

To get reponse dictionary

import bardapi

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

# 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']="xxxxxxx"

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

# 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='xxxxxxx', proxies=proxies, timeout=30)
bard.get_answer("나와 내 동년배들이 좋아하는 뉴진스에 대해서 알려줘")['content']

Use rotating proxies

If you want to avoid blocked requests and bans, then use Smart Proxy by Crawlbase. It forwards your connection requests to a randomly rotating IP address in a pool of proxies before reaching the target website. The combination of AI and ML make it more effective to avoid CAPTCHAs and blocks.

from bardapi import Bard
import requests

# Get your proxy url at crawlbase https://crawlbase.com/docs/smart-proxy/get/
proxy_url = "http://xxxxxxxxxxxxxx:@smartproxy.crawlbase.com:8012" 
proxies = {"http": proxy_url, "https": proxy_url}

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

Reusable session object

You can continue the conversation using a reusable session. However, this feature is limited, and it is difficult for a package-level feature to perfectly maintain conversation_id and context. You can try to maintain the consistency of conversations same way as other LLM services, such as passing some sort of summary of past conversations to the DB.

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

session = requests.Session()
session.headers = {
            "Host": "gemini.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://gemini.google.com",
            "Referer": "https://gemini.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']
Async Bard Code (Click to expand)
from httpx import AsyncClient
from bardapi import BardAsync
import os

# Uncomment and set your API key as needed
# os.environ['_BARD_API_KEY'] = 'xxxxxxx'
token = 'xxxxxxx'  # Replace with your actual token

SESSION_HEADERS = {
    "Host": "gemini.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://gemini.google.com",
    "Referer": "https://gemini.google.com/",
}
timeout = 30  # Example timeout
proxies = {}  # Replace with your proxies if needed

client = AsyncClient(
    http2=True,
    headers=SESSION_HEADERS,
    cookies={"__Secure-1PSID": token},
    timeout=timeout,
    proxies=proxies,
)

bard_async = BardAsync(token=token, client=client)

# Asynchronous function to get the answer
async def get_bard_answer(question):
    await bard_async.async_setup()  # Ensure async setup is done
    return await bard_async.get_answer(question)

response = await get_bard_answer("나와 내 동년배들이 좋아하는 뉴진스에 대해서 알려줘")
print(response['content'])

Auto Cookie Bard

Using browser_cookie3 we extract the __Secure-1PSID cookie from all browsers, and then we can use the API without passing the token. However, there are still incomplete dependency packages and various variables, so please seek assistance in the following GitHub Issues or adjust your browser's version.

  • Visit https://gemini.google.com/ in your browser and execute the following command while in the chat-enabled state. Refer to browser_cookie3 for details on how it works. If any issues arise, please restart the browser or log in to your Google account again. Recommended to keep the browser open.
from bardapi import Bard

bard = Bard(token_from_browser=True)
response = bard.get_answer("Do you like cookies?")
print(response['content'])

Bard ask_about_image method

It may not work as it is only available for certain accounts, regions, and other restrictions. As an experimental feature, it is possible to ask questions with an image. However, this functionality is only available for accounts with image upload capability in Bard's web UI.

from bardapi import Bard

bard = Bard(token='xxxxxxx')
image = open('image.jpg', 'rb').read() # (jpeg, png, webp) are supported.
bard_answer = bard.ask_about_image('What is in the image?', image)
print(bard_answer['content'])

Business users and high traffic volume may be subject to account restrictions according to Google's policies. Please use the Official Google Cloud API for any other purpose. The user is solely responsible for all code, and it is imperative to consult Google's official services and policies. Furthermore, the code in this repository is provided under the MIT license, and it disclaims any liability, including explicit or implied legal responsibilities.

from bardapi import Bard

bard = Bard(token='xxxxxxx')
audio = bard.speech('Hello, I am Bard! How can I help you today?')
with open("speech.ogg", "wb") as f:
  f.write(bytes(audio['audio']))

Starting from version 0.1.18, the GitHub version of BardAPI will be synchronized with the PyPI version and released simultaneously. However, the version undergoing QA can still be used from the GitHub repository.

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

Amazing Bard Prompts Is All You Need!

  • Helpful prompts for Google Bard

If you want to comfortably use the open-source LLM models in your native language, which are released under the Apache License (allowing free commercial use) in various languages, you can try using the hf-transllm package. hf-transllm also supports multilingual inference for various LLMs stored in hugging face repository.

Example code of hf-transllm

In case the Google package is no longer available due to policy restrictions, here's a simple example code for using open-source language models (LLMs) in both English and multiple languages.

Usage

For the decoder models provided by Hugging Face, you can easily use them by either following a simple approach or overriding the inference method. You can explore various open-source language models at this link. Through the ranking information from Open LLM Leader Board Report repository, you can find information about good models.

For LLM that use languages other than English

from transllm import LLMtranslator

open_llama3b_kor = LLMtranslator('openlm-research/open_llama_3b', target_lang='ko', translator='google') # Korean

trnaslated_answer = open_llama3b_kor.generate("나와 내 동년배들이 좋아하는 뉴진스에 대해서 알려줘")
print(trnaslated_answer)

For LLM that use English

Refer https://github.com/openlm-research/open_llama or using like this:

from transllm import LLMtranslator

open_llama3b = LLMtranslator('openlm-research/open_llama_3b) 

answer = open_llama3b.generate("Tell me about the Korean girl group Newjeans.")
print(answer)

What is Google Gemini?

Gemini or formerly knowns as Bard is an advanced, multimodal AI model by Google DeepMind, capable of understanding and integrating various information types like text, code, audio, images, and video.

Google AI Studio

Google AI Studio creates a new Google Cloud project for each new API key. You also can create an API key in an existing Google Cloud project. All projects are subject to the Google Cloud Platform Terms of Service.

Access to Gemini Pro in Bard API package

The Bard API, sourcing responses from Google BardGemini's official website, allows you to receive the same responses as the website. So, if Gemini answers are available on the web, you can also accessed Gemini through the Bard API. However, it's important to note that responses might also come from other models, not exclusively Gemini Pro or Ultra.

  • There is no official Bard API or early access/waiting list for Gemini, although the PaLM2 API is available.
    • Google's PaLM2 API differs from Bard, with some aspects of Bard being superior.
    • It's speculated that after expert review, Bard Advanced lineup will likely provide an official API in 2024.
  • Gemini and previous generative AI model responses are provided randomly on Bard Web.
  • The Bard API, with its imperfect extension features(e.g, ask_about_image), occasionally demonstrates Gemini's capabilities. This behavior may vary by region, language, or Google account.
  • More information in the FAQ.

For more on Gemini:


Google PaLM

Try demo at https://makersuite.google.com/app/prompts/new_text.

who are you?
>> I am powered by PaLM 2, which stands for Pathways Language Model 2, a large language model from Google AI.

Google Generative AI

Quick Start

$ pip install -q google-generativeai
import pprint
import google.generativeai as palm

palm.configure(api_key='YOUR_API_KEY')

models = [m for m in palm.list_models() if 'generateText' in m.supported_generation_methods]
model = models[0].name
print(model)

prompt = "Who are you?"

completion = palm.generate_text(
    model=model,
    prompt=prompt,
    temperature=0,
    # The maximum length of the response
    max_output_tokens=800,
)
print(completion.result)


Sponsor

Use data scraping to train your AI models.

  • Easy to use API to crawl and scrape millions of websites
  • Use crawlbase for efficient data extraction for your LLMs
  • Average success rate: 98%
  • Uptime guarantee: 99.9%
  • Simple docs to get started in minutes
  • Asynchronous Crawling API if you need massive amounts of data
  • GDPR and CCPA compliant

Used by 70k+ developers.

Please check the FAQ and open issues for similar questions before creating a new issue. Repeated questions will be kept as open issues. Too many requests can trigger a temporary account block (HTTP 429). Maintain proper intervals, using functions like sleep to avoid rate limits. Policies may vary by country and language, so all users could face temporary or permanent errors via the API.

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.

Contributors

We would like to express our sincere gratitude to all the contributors.


License

MIT
We hold no legal responsibility; for more information, please refer to the bottom of the readme file. We just want you to give me and them a star. This project is a personal initiative and is not affiliated with or endorsed by Google. It is recommended to use Google's official API.

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.

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.

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

Warning 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.

Warning 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

bard-api's People

Contributors

amit9021 avatar ayansengupta17 avatar cboyxd avatar dsdanielpark avatar jjkoh95 avatar kota113 avatar meemeelab avatar mirusu400 avatar nishantchauhan949 avatar qewertyy avatar sachnun avatar salimloudev avatar senseibence avatar sudoalireza avatar szv99 avatar thecodekitchen avatar thewh1teagle avatar veonua avatar yihong0618 avatar zeelsheladiya avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bard-api's Issues

Want to hold a conversation

I would like to retain the session data after the session is disconnected and use that data to retain the conversation when I re-instantiate the session.
It seems possible if I can retain the conversation_id and reuse it.

AttributeError: 'NoneType' object has no attribute 'group'

Traceback (most recent call last):
File "f:\Python_files\main.py", line 8, in
print(Bard().get_answer(input_text)['content'])
File "F:\facereg\NEW\lib\site-packages\bardapi\core.py", line 43, in init
self.SNlM0e = self._get_snim0e()
File "F:\facereg\NEW\lib\site-packages\bardapi\core.py", line 59, in _get_snim0e
raise Exception(
Exception: SNlM0e value not found in response. Check __Secure-1PSID value.

But i used correct id

How to continue an conversation?

Can you show me what I need to save so that Bard can remember the previous conversation without starting a new one after each question?
I'm trying to write it on PHP

I used Chrome Dev Tools to monitor and found SNlM0e and conversation_id unchanged, I tried saving it again but the result is not as expected

Large volume of requests may result in a ban

I was throwing a request to Bard to summarize a paper, and it started throwing Response Error halfway through. This happens regardless of the Token and will not accept requests from python.
Requests from web browsers are successfully accepted, so there may be some way to fix this.
Do you have any ideas?

Response Error: b')]}\'\n\n38\n[["wrb.fr",null,null,null,null,[8]]]\n55\n[["di",90],["af.httprm",89,"-5846312931853295462",1]]\n25\n[["e",4,null,null,130]]\n'.

question: how to use a request proxy (not an http proxy)

first of all, congratulations for the excellent project, I did some tests integrating it in a chatbot and it worked incredibly well.

My doubt is: how do I use a request proxy?
reason: I'm from a country where bard is not officially available and I don't have access to a secure and fast proxy.
I tried to use vpn but for independent scripts it ends up being one more problem to deal with.

my solution was to create a CORS proxy for requests on fly.io that receives a request and retransmits it.
but I wanted to know where I can add this in the core of your project?
the proxy works by adding the real url in front of the proxy url and it only works for requests.
example:
https://proxy-request.com/https://bard.google.com/

where could I modify in core.py to make this request like this?

Suggesting to add support behind proxy

Hi,
Thanks for creating this library! It is awsome, easy to use and very useful!
I'm using it behind a proxy, so I added support for proxies locally and would love to contribute it to the library if you agree.
If so - please let me know if you want me to branch, propose a solution and create a pull request.
Thanks!
Nir.

SNlM0e value not found in response

I have tried to interpret core python code to C# with the help of Chatgpt as I'm just a newbie in this field , It generated the full code to be applicable for integration with Unity. but I have got the error "SNlM0e value not found in response".
I don't know what is the issue, it might be related to my location ?
and here is the code

using UnityEngine;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Net.Http;
using System;
using UnityEngine.Networking;
using System.Linq;

public class Bard
{
    private Dictionary<string, string> proxies;
    private int timeout;
    private Dictionary<string, string> headers;
    private int _reqid;
    private string conversation_id;
    private string response_id;
    private string choice_id;
    private HttpClient httpClient;
    private string SNlM0e;

    public Bard(int timeout = 6, Dictionary<string, string> proxies = null)
    {
        this.proxies = proxies;
        this.timeout = timeout;
        this.headers = new Dictionary<string, string>
        {
            { "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/" }
        };
        this._reqid = int.Parse(string.Join("", UnityEngine.Random.Range(0, 10), UnityEngine.Random.Range(0, 10), UnityEngine.Random.Range(0, 10), UnityEngine.Random.Range(0, 10)));
        this.conversation_id = "";
        this.response_id = "";
        this.choice_id = "";
        this.httpClient = new HttpClient();
        this.httpClient.DefaultRequestHeaders.Clear();
        this.httpClient.DefaultRequestHeaders.Host = "bard.google.com";
        this.httpClient.DefaultRequestHeaders.Add("X-Same-Domain", "1");
        this.httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36");
        this.httpClient.DefaultRequestHeaders.Accept.ParseAdd("application/x-www-form-urlencoded;charset=UTF-8");
        this.httpClient.DefaultRequestHeaders.Referrer = new Uri("https://bard.google.com/");

       // this.httpClient.DefaultRequestHeaders.Add("Cookie", "__Secure-1PSID=" + Environment.GetEnvironmentVariable("_BARD_API_KEY"));

        this.httpClient.DefaultRequestHeaders.Add("Cookie", "__Secure-1PSID=Wgi8wUobo4-2WaJ29Y45F_fGhfjh4GjtcOMkBamz5_dJ4gogfwcocBxvS2PRxuEiJsS4ww.");

        this.SNlM0e = this._get_snim0e();
    }

    private string _get_snim0e()
    {
        var requestUri = "https://bard.google.com/";
        var response = httpClient.GetAsync(requestUri).Result;

        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"Response Status: {response.StatusCode}");
        }

        var responseContent = response.Content.ReadAsStringAsync().Result;
        Debug.Log("responseContent" + responseContent);
        var match = Regex.Match(responseContent, "SNlM0e\":\"(.*?)\"");
        if (!match.Success)
        {
            throw new Exception("SNlM0e value not found in response.");
        }

        return match.Groups[1].Value;
    }

    public Dictionary<string, object> GetAnswer(string inputText)
    {
        var url = "https://bard.google.com/_/BardChatUi/data/assistant.lamda.BardFrontendService/StreamGenerate";
        var paramsDict = new Dictionary<string, string>
    {
        { "bl", "boq_assistant-bard-web-server_20230419.00_p1" },
        { "_reqid", this._reqid.ToString() },
        { "rt", "c" }
    };

        var inputTextStruct = new List<object[]>
    {
        new object[] { inputText },
        null,
        new object[] { this.conversation_id, this.response_id, this.choice_id }
    };

        var dataDict = new Dictionary<string, string>
    {
        { "f.req", JsonUtility.ToJson(new object[] { null, JsonUtility.ToJson(inputTextStruct) }) },
        { "at", this.SNlM0e }
    };

        var formData = new WWWForm();
        foreach (var kvp in dataDict)
        {
            formData.AddField(kvp.Key, kvp.Value);
        }

        var request = UnityWebRequest.Post(url, formData);
        request.SetRequestHeader("Host", "bard.google.com");
        request.SetRequestHeader("X-Same-Domain", "1");
        request.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36");
        request.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        request.SetRequestHeader("Origin", "https://bard.google.com");
        request.SetRequestHeader("Referer", "https://bard.google.com/");

        var response = request.SendWebRequest();

        while (!response.isDone) { }

        if (request.result != UnityWebRequest.Result.Success)
        {
            return new Dictionary<string, object> { { "content", $"Response Error: {request.error}." } };
        }

        var responseContent = request.downloadHandler.text;
        var responseLines = responseContent.Split('\n');
        var respDict = JsonUtility.FromJson<DictionaryResponse>(responseLines[3]);
        var respJson = JsonUtility.ToJson(new DictionaryResponse { Content = respDict.Content });
        var parsedAnswer = JsonUtility.FromJson<DictionaryAnswer>(respJson);
        var bardAnswer = new Dictionary<string, object>
    {
        { "content", parsedAnswer.Content[0][0] },
        { "conversation_id", parsedAnswer.Content[1][0] },
        { "response_id", parsedAnswer.Content[1][1] },
        { "factualityQueries", parsedAnswer.Content[3] },
        { "textQuery", parsedAnswer.Content[2][0] != null ? parsedAnswer.Content[2][0] : "" },
        { "choices", parsedAnswer.Content[4].Select(item => new Dictionary<string, object> { { "id", item[0] }, { "content", item[1] } }).ToList() }
    };

        this.conversation_id = (string)bardAnswer["conversation_id"];
        this.response_id = (string)bardAnswer["response_id"];
        choice_id = ((List<Dictionary<string, object>>)bardAnswer["choices"])[0]["id"].ToString(); this._reqid += 100000;

        return bardAnswer;
    }

    [System.Serializable]
    public class DictionaryResponse
    {
        public object[][] Content;
    }

    [System.Serializable]
    public class DictionaryAnswer
    {
        public object[][][] Content;
    }

}

image not displayed

query: "give me an image of maa Saraswati"
when I pass this query to Bard via API, following is the response:
'Sure, here is an image of Maa Saraswati.\n[Image of Maa Saraswati]'

however, when I give this same query to Bard via the chat, it shows me a relevant image

please help resolve this

Cannot be used from japan (Bard PSID cookie update?)

I don't know this is specific to me or only rolled out to japan region, but from what I can see now, bard.google.com does not allow logging in just by sending __Secure-1PSID now.
This causes "SNlM0e value not found in response. Check __Secure-1PSID value." error with valid __Secure-1PSID token.

I tried different cookie combination, and found out now it needs 3 cookies:

  • __Secure1-PSID
  • APISID
  • SAPISID

I noticed this library was becoming unstable yesterday (It wasn't unstable before that) and today, it became completly unusable.

Would be appreciated if you can make cookie dict parameter instead of just one PSID str argument.

Thanks

list index out of range

well, maybe google decided to change things a bit...

File "/home/runner/Bard-AI-bot-template-bardapi/venv/lib/python3.10/site-packages/bardapi/core.py", line 86, in get_answer
resp_dict = json.loads(resp.content.splitlines()[3])[0][2]
IndexError: list index out of range

Not able to get response

I have followed the procedures in the Read.me file.

from bardapi import Bard
import os
os.environ['_BARD_API_KEY']='WwXXXXXjQIGRj3Cno871zb4FRW1smDrQH10e1H7GbD5LeU9m02OlZJj5-XX.'

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

First i have tried with example snippets, i got the below error.

Traceback (most recent call last):
File "PyCharmProjects/Bard-API/scripts/google_bard_api.py", line 13, in
response = Bard().get_answer("나와 내 동년배들이 좋아하는 뉴진스에 대해서 알려줘")['content']
File "PyCharmProjects/Bard-API/bardapi/core.py", line 130, in get_answer
translator_to_lang = GoogleTranslator(source="auto", target=self.language)
File "PyCharmProjects/Bard-API/venv/lib/python3.10/site-packages/deep_translator/google.py", line 39, in init
super().init(
File "PyCharmProjects/Bard-API/venv/lib/python3.10/site-packages/deep_translator/base.py", line 42, in init
raise InvalidSourceOrTargetLanguage(target)
deep_translator.exceptions.InvalidSourceOrTargetLanguage: None --> Invalid source or target language!

then i have changed the input text to english language, and again i got the same error.

Traceback (most recent call last):
File "PyCharmProjects/Bard-API/scripts/google_bard_api.py", line 14, in
response = Bard().get_answer("What is Bard API")['content']
File "PyCharmProjects/Bard-API/bardapi/core.py", line 130, in get_answer
translator_to_lang = GoogleTranslator(source="auto", target=self.language)
File "PyCharmProjects/Bard-API/venv/lib/python3.10/site-packages/deep_translator/google.py", line 39, in init
super().init(
File "PyCharmProjects/Bard-API/venv/lib/python3.10/site-packages/deep_translator/base.py", line 42, in init
raise InvalidSourceOrTargetLanguage(target)
deep_translator.exceptions.InvalidSourceOrTargetLanguage: None --> Invalid source or target language!

Could anybody get help me here?

Response error

Response Error: b')]}'\n\n38\n[["wrb.fr",null,null,null,null,[9]]]\n56\n[["di",253],["af.httprm",252,"7953890135670054436",0]]\n25\n[["e",4,null,null,131]]\n'.

image

problem when i call the api

what should i do ,it returns the content. Response Error: b')]}'\n\n38\n[["wrb.fr",null,null,null,null,[8]]]\n55\n[["di",70],["af.httprm",70,"-2165490944187691766",6]]\n25\n[["e",4,null,null,130]]\n'. []

Is it chargeable ?

I have done exact steps and get it done to run but, just want to know that Will google charge me if I use it ?

Provide Links For Images Generated by Google's Bard AI

Hello,

It seems BardAI now supports image generation as per below snapshot. However the Bard-API only returns the alt-image-text for the generated image.
Is there a way to include the links of the generated images?

cannot import

When trying to import the package, I got the following error

ImportError: urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with LibreSSL 2.8.3. See: urllib3/urllib3#2168

please advice which urllib3 to use

Problem when executing Bard.get_answer()

Earlier today, it was working fine but now whenever it executes it shows me this error:

site-packages/bardapi/core.py", line 114, in get_answer
resp_dict = json.loads(resp.content.splitlines()[3])[0][2]
IndexError: list index out of range

Chat continuity not working?

I wanted to try to continue the chat and tried the code as per the sample in the readme, but it returns a completely different prompt on the second question.

Is there any way to fix this?

Getting errors even on first request, even with large timeout

I tried running this, and I am getting the same kind of error. I didn't make a lot of requests, and this error persists whether I vary the following factors:

  • session: Tried with and without
  • timeout: Tried with and without

Here's what the errors are:

Session and timeout: Response Error: b')]}\'\n\n38\n[["wrb.fr",null,null,null,null,[9]]]\n57\n[["di",207],["af.httprm",206,"-5973836830292919317",0]]\n25\n[["e",4,null,null,132]]\n'.

Session: Response Error: b')]}\'\n\n38\n[["wrb.fr",null,null,null,null,[9]]]\n57\n[["di",158],["af.httprm",157,"-7097826725018575708",1]]\n25\n[["e",4,null,null,132]]\n'.

Timeout: Response Error: b')]}\'\n\n38\n[["wrb.fr",null,null,null,null,[9]]]\n57\n[["di",188],["af.httprm",187,"-7191527685766192777",2]]\n25\n[["e",4,null,null,132]]\n'.

No Sesh No Timeout: Response Error: b')]}\'\n\n38\n[["wrb.fr",null,null,null,null,[9]]]\n56\n[["di",170],["af.httprm",170,"3959452704966963607",1]]\n25\n[["e",4,null,null,131]]\n'.
!pip install bardapi


from bardapi import Bard
import os
import requests

# Get this from going to 
# Bard web UI --> 
# Developer tools --> 
# Applications --> 
# Storage tab --> 
# cookies --> 
# Secure-1PSID
token='MYCOOKIE.'
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", token)

# TRY DIFFERENT COMBOS OF SESSION AND TIMEOUT 

# Session and timeout 
bard = Bard(token=token, session=session, timeout=500)
ans = bard.get_answer("What's a creative use for a hat?")['content']
print("Session and timeout:", ans)

# Session
bard = Bard(token=token, session=session)
ans = bard.get_answer("What's a creative use for a hat?")['content']
print("Session:", ans)

# Timeout
bard = Bard(token=token, timeout=500)
ans = bard.get_answer("What's a creative use for a hat?")['content']
print("Timeout:", ans)

# No Session, No Timeout
bard = Bard(token=token)
ans = bard.get_answer("What's a creative use for a hat?")['content']
print("No Sesh No Timeout:", ans)

license??

What is the license to use this repository? Apache, MIT or GPL, Please upload

Is google bard has limit number of question?

It appears that there's a quota limitation when invoking the Bard API. I've written a loop for the calls, and I've noticed there seems to be a cap on the number of requests. Once a certain threshold is reached, it starts to return errors, preventing further queries.

New Feature request.

I want a function that can assist in getting quotes from the Bard.
I find it annoying to use get_answer() to get a quote when we can have a command for it.

SNlM0e has disappeared

It's still in the browser, but calling with GET and current cookie setup produces a response without it

Also, calling the stream API (which also has a new body format) with a manually extracted SNlM0e and __Secure-1PSID doesn't work. It's like there is something detecting that the call is not originating from the browser UI

Response error

I did as the docs said and just replaced my api key yet I m getting the error

from bardapi import Bard
import os

#Replace XXXX with the values you get from __Secure-1PSID 
os.environ['_BARD_API_KEY']="XXXX"
# set your input text
input_text = "what is google bard?"

print(Bard().get_answer(input_text)['content'])

Response Error: b')]}\'\n\n38\n[["wrb.fr",null,null,null,null,[9]]]\n56\n[["di",329],["af.httprm",329,"2550290118937250235",0]]\n25\n[["e",4,null,null,131]]\n'.

Response error

Everything seems to work fine until I run the code and get

Response Error: b')]}'\n\n38\n[["wrb.fr",null,null,null,null,[9]]]\n56\n[["di",113],["af.httprm",113,"-913832998693439861",7]]\n25\n[["e",4,null,null,131]]\n'.

Translated core to Node.js

I don't expect this to work forever, as Bard's UI interface and internal stream API will likely evolve, but here is some code I wrote in case anyone finds it useful.... use at your own peril!

    //This value expires after 12 days, so need to refresh from Bard's website manually
    const cookie = '__Secure-1PSID=[API_KEY_VALUE]';
    let prompt = "Hi!";
    fetch("https://bard.google.com/",
        {
            method: 'get',
            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",
                'Cookie': cookie
            },
        }).then(async bard_res => {
        var bard_text = await bard_res.text();
        const match = bard_text.match(/"SNlM0e":"(.*?)"/);
        const SNlM0e = match ? match[1] : null;
        fetch("https://bard.google.com/_/BardChatUi/data/assistant.lamda.BardFrontendService/StreamGenerate?bl=boq_assistant-bard-web-server_20230510.09_p1&_reqid=229189&rt=c", {
            method: 'post',
            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",
                'Cookie': cookie
            },
            body: "f.req=[null,\"[[\\\""+prompt +"\\\"],null,[\\\"\\\",\\\"\\\",\\\"\\\"]]\"]&at=" + SNlM0e
        }).then(async res => {
            let lines = (await res.text()).split("\n");
            let longest_line = lines.reduce(function (a, b) {
                return a.length > b.length ? a : b;
            }, "");
            let response = JSON.parse(JSON.parse(longest_line)[0][2])[0][0];
            console.log(response);
        })
        .catch(err => {
            console.error('Error:', err);
        });

Error when trying to execute the C# translation code

There are so many errors, when you try to execute the translated code in c#.
It will display Many errors, once you run the code as it is.
From the missing variables to the regex expression and the bad request error.

One particular user's cookie gets invalidated after few calls (2/3/4/5)

There has not been any excessive usage for 3 users but one particular user's cookie gets invalidated after few calls. Once I log out and log in once again, it again works for a few times and then again returns "Check __Secure-1PSID value." Is this a user ban or a recent phenomenon or anybody else facing this?

Exception: SNlM0e value not found in response. Check __Secure-1PSID value.

Traceback (most recent call last):
File "F:\Code\Projects\audit\audit-software\data-classification\chat.py", line 6, in
bard = Session(token)
File "F:\Code\Projects\audit\audit-software\data-classification\session.py", line 19, in init
self.bard = Bard(token=self.token, session=session, timeout=30)
File "C:\Users\DHRUV\anaconda3\lib\site-packages\bardapi\core.py", line 49, in init
self.SNlM0e = self._get_snim0e()
File "C:\Users\DHRUV\anaconda3\lib\site-packages\bardapi\core.py", line 192, in _get_snim0e
raise Exception(
Exception: SNlM0e value not found in response. Check __Secure-1PSID value.

Getting wrong responses when referencing previous inputs

When providing the input text to tell me what was going on it the past prompts it is giving me responses that are either hallucinatory or is someone else's conversation.

Example:
Prompt: tell me the the last 3 prompts that I wrote to you

Response:
Sure. The last 3 prompts that you wrote to me were:

  1. "who are you? today is 2023-05-17"
  2. "Remember the search results of this query: last 3 prompts"
  3. "Ask me some questions. Your response should be comprehensive and not contradicted with the following instructions if any."

I hope this helps!

Remarks: Please provide some insight as to why this is happening and if there's any way to prevent it

Response Error

{'content': 'Response Error: b')]}\'\n\n38\n[["wrb.fr",null,null,null,null,[8]]]\n56\n[["di",75],["af.httprm",75,"-8694801941071849458",37]]\n25\n[["e",4,null,null,131]]\n'.'}

Such Response is observed while running bard.get_answer("Generate Html an Js for Mean Calculator")

error :v

when i try to execute the first simple usage script it give me this error: raise Exception(
Exception: __Secure-1PSID value must end with a single dot. Enter correct __Secure-1PSID value.

Context understanding

Bard().get_answer(query1)['content']
Bard().get_answer(query2)['content']
The problem with this is that it does not remember the context what was asked in the first query, like Bard actually does. How can we make it remember context when running through API

Getting weird error response while executing simple script

from bardapi import Bard

token = '.......'
bard = Bard(token=token)
resp = bard.get_answer("What is BARD?")

print(resp)

It responds with {'content': 'Response Error: b')]}\'\n\n38\n[["wrb.fr",null,null,null,null,[9]]]\n55\n[["di",72],["af.httprm",72,"8367677104245371628",47]]\n25\n[["e",4,null,null,130]]\n'.'}

I started trying the API today morning.. Anyone else facing such issue or am I making a newbie mistake?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.