Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

How to integrate the Bard API into your Python applications

Save for later
View related Packt books & videos

article-image

You can leverage the power of Google Bard from within applications using the Bard-API Python package. This package provides a user-friendly programmatic interface to interact with Google Bard. You can use this package to seamlessly add generative AI capability to your Python applications. Text summarization, question-answering, and language translation are simplified.  Because Bard is Internet-aware, the API can answer queries that other AI solutions cannot answer out of the box.

It is important to note that this package describes itself as an “unofficial Python package that returns (the) response of Google Bard through (a) cookie value.” Specifically, it requires you to obtain a cookie from your browser assigned to your account. You then provide this to the library, and it acts as an “api key.” You should treat it with the same level of security and confidentiality as you would with any other API key tied to one of your accounts. Note that the Bard API is a cutting-edge technology in a rapidly changing area and is not production ready at the time of writing. 

Using this cookie value, the Bard-API package emulates calling Bard as if you were working with the web interface in a browser. By comparison, the Bard API does not have as much flexibility as the ChatGPT API. For example, there is no equivalent temperature parameter that controls the creativity level of the output. The Bard API signature is prompt-centric, so any instructions you want to give to the API need to be included as part of your prompt.

On the plus side, the interface is simple and easy to use. The main function is simply defined as shown below. The dictionary returned includes a content element, as well as other helpful information about the output.

def get_answer(self, input_text: str) -> dict:

Setup your environment for the Bard API

First, install the Bard-API package using the following command.

 pip install bardapi

You then need to obtain your account’s __Secure-1PSID cookie value. From the GitHub project that reverse-engineered the Bard API, you can get the cookie value as follows.

Go to https://bard.google.com/

  • F12 for console
  • Copy the values
    • Session: Go to Application → Cookies → __Secure-1PSID. Copy the value of that cookie.

As with any API key, avoid putting it directly into your code. Create a .env file and add a line for the value. Note that the key name _BARD_API_KEY is the exact name required by the Python library.

 _BARD_API_KEY=your_cookie_value.

To use this within your code, install the python-dotenv library.

 pip install python-dotenv

The following code in our bard.py file uses the Bard-API Python library to invoke the API. It reads the cookie value from the environment file in order to successfully authenticate.

from bardapi import Bard
from dotenv import load_dotenv
load_dotenv()
 
def call_bard(query):
   bard = Bard()
   answer = bard.get_answer(query)
   return (answer['content'])
Invoke the Bard API from your Python code

The function above can be used from within your Python code. Create a new file in Python to perform a simple test and verify that your API client is working correctly. The details of the API output can also be inspected. Note, however, that the call_bard code only returns the content element. In most use cases, this is likely all you need to be concerned with.

 from bard import call_bard
 
response = call_bard("What movie would you recommend?")
print(response)
 

Running this code returned the following output. Note that only the initial portion of the response is shown below for brevity. Our BARD API client code is working.

I need more information like what kind of movies do you like, what are your interests, etc. 

Here are a few recommendations to get you started:

 

* **The Godfather (1972)** is a classic gangster film that tells the story of the Corleone family. It is considered one of the greatest films of all time.

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime

[Image of The Godfather (1972) movie poster]

* **The Shawshank Redemption (1994)** is a drama about a man who is wrongly convicted of murder and sent to prison. It is a heartwarming story about hope and redemption.

[Image of The Shawshank Redemption (1994) movie poster]

* **The Dark Knight (2008)** is a superhero film that tells the story of Batman's battle against the Joker. It is a dark and gritty film that is considered one of the best superhero films ever made.

[Image of The Dark Knight (2008) movie poster]

For some use cases, you may be interested to see what other response options Bard generated. In the dictionary returned from the Bard API, there is also a choices element, which is a list of other candidate responses Bard generated. On the Bard web page, you can choose to view these alternative responses. In your application, you may or may not want to leverage these other options based on your use case and requirements.

Interestingly, Bard also returns an equivalent query it uses to generate a response. In our movie example above, the output dictionary contains the following element. 

textQuery': ['what is the most critically acclaimed movie?', 1]

If you look through the other choices it generated, others take a different approach. Another response choice starts by recommending comedies instead of critically acclaimed movies.

 {'id': 'rc_e531de0d5173e11b',

 'content': ["I need more information on what kind of movie you are looking for. Here are a few options to get you started:\n\n* If you are in the mood for a comedy, I recommend *21 Jump Street* (2012). It's a hilarious and action-packed film about two young cops who go undercover as high school students to bust a drug ring.\n[Image of 21 Jump Street (2012) movie poster]... 

Summary

In summary, integrating the Bard API into Python applications is a practical and straightforward process. By leveraging the API's rich collection of literary quotes, developers can enhance their applications with a touch of elegance and creativity. Through simple API calls and data manipulation, Python programmers can seamlessly integrate Bard's vast repository of quotes into their projects, enriching the user experience and adding a sophisticated literary flair. By following the practical steps outlined in this article, developers can easily unlock the power of the Bard API and bring the magic of literature into their Python applications.

Author Bio

Darren Broemmer is an author and software engineer with extensive experience in Big Tech and Fortune 500. He writes on topics at the intersection of technology, science, and innovation.

 LinkedIn