Connect with us

Google Generative AI

Google PaLM 2: Generating Text with Bard API

Learn how to use the Google PaLM API (or Bard API) to generate text programmatically in Python.



In this quick tutorial, we explore the capabilities of the Google PaLM API (also known as Google Bard API) to generate text content. Google’s PaLM 2 is a powerful generative AI model that can assist you in various tasks, from generating text content to providing code snippets in various programming languages, including Python. I will walk you through the process of using the PaLM API to generate text. Before you begin, ensure that you have set up your Conda environment and installed the necessary modules, as shown in our previous article.

To start with the PaLM API, create a Python file named Import the API as palm to access its functionalities. Be sure to have the necessary modules by importing the Google Generative AI package (as palm) and os. The palm module is crucial for PaLM API access, while the os module enables environment variable handling.

Before we proceed, it’s essential to configure the palm module with our API key, a secret string granting access to the PaLM API. For security, we recommend storing the API key in an environment variable on your machine, making it accessible to all our Python scripts while keeping it hidden from public view. If you are using a Conda environment, this is easier to manage.

The palm.configure() method requires two parameters: the API key and the project ID. The API key, as mentioned earlier, is the secret string enabling PaLM API access.

import google.generativeai as palm
import os

# Access your API key as an environment variable, for security

The code below uses the palm module we imported. Then, it calls the generate_text() method to generate a list of countries near Malaysia. The prompt parameter specifies the text that the PaLM API should use as a starting point for the generation. Consider it as instructions given to the API to understand precisely what text it should generate and return to us as output. In this case, the prompt is “List the countries near Malaysia.” The response variable will contain the result of the generation, which is a list of strings.

response = palm.generate_text(prompt="List the countries near Malaysia.")

The print() statement at the end of the code will print the clean result of the generation to the console via the result attribute used on the response object, which is why you see response.result. You can generate any text by changing the string corresponding to the prompt. As with the Bard AI interface, text generated via the PaLM API may be presented as short strings, paragraphs, lists, numerical data, and more.

That is all; you have just learnt how to use the Google PaLM API (or Bard API) to generate text programmatically in Python.


Exit mobile version