Connect Google’s AI With Python Using PaLM2 API

Neel Bhatt
2 min readSep 3, 2023

--

Join Google PaLM API Waitlist

Before we embark on our journey to connect Google Bard with Python, it’s essential to ensure that you have access to the PaLM API. To get started, you need to join the Google PaLM API waitlist. Follow the simple steps below:

  1. Click on this link: Join Google PaLM API Wait List.
  2. Sign in with your Google account or create one if you haven’t already.
  3. Fill out the necessary information to request access to the PaLM API.
  4. Wait patiently for Google to grant you access to this cutting-edge API.

Once you have been granted access, you’ll be on your way to unlocking the power of Google Bard and Python through the PaLM API.

Setting Up PaLM API Python Library

Now that you’ve successfully joined the PaLM API waitlist and received access, it’s time to connect Google Bard with Python, you’ll need to download and install the google-generativeai Python library.

Follow these steps:

pip install -q google-generativeai

To get started, you’ll need to create an API key.

import google.generativeai as palm 
palm.configure(api_key='YOUR_API_KEY')

Replace 'YOUR_API_KEY' with the API key you received when you were granted access to the PaLM API.

Listing Available Models

To find the available models for text generation, use the following code:

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

The palm.list_models() function will provide you with a list of models that support text generation. You can select the one that suits your specific requirements. In this example, we've chosen the models/text-bison-001 model.

Generating Text

Now, let’s put the PaLM API to work by generating text based on a given prompt:

prompt = """

You are an expert at solving word problems.

Solve the following problem:

I have three houses, each with three cats.
each cat owns 4 mittens, and a hat. Each mitten was
knit from 7m of yarn, each hat from 4m.
How much yarn was needed to make all the items?

Think about it step by step, and show your work.

"""

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

print(completion.result)

The Output

There are 3 houses * 3 cats per house, totaling 9 cats. Each cat owns 4 mittens and a hat. The mittens are knit from 7 meters of yarn, while the hats require 4 meters each.

--

--