PaLM API: Text quickstart with Java

This quickstart provides the code to get you up and running with the PaLM API Java SDK.

Obtain an API Key

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

Install the API client

These instructions will install the PaLM Java API in your local Maven repository so that you can add it as a dependency to your Gradle project.

  1. Download the google-cloud-ai-generativelanguage-v1beta3-java.tar.gz file.
  2. Extract the files and install them in mavenLocal:

    # Extract the files
    tar -xzvf google-cloud-ai-generativelanguage-v1beta3-java.tar.gz
    cd google-cloud-ai-generativelanguage-v1beta3-java
    # Install to mavenLocal
    ./gradlew publishToMavenLocal

Adding the SDK to your project

  1. Open your Gradle configuration file and make sure mavenLocal() is listed under repositories:

    repositories {
        // ...
        // Add the Maven Local repository
  2. Also in your Gradle configuration file add the necessary libraries to the dependencies block:

    dependencies {
        // ...
        // Add these dependencies to use Generative AI

Initialize the text service client

In your Java program, initialize a TextServiceClient by passing your API Key as a header to the TransportChannelProvider to be used by TextServiceSettings:


HashMap<String, String> headers = new HashMap<>();
headers.put("x-goog-api-key", System.getenv("PALM_API_KEY"));

TransportChannelProvider provider = InstantiatingGrpcChannelProvider.newBuilder()

TextServiceSettings settings = TextServiceSettings.newBuilder()

TextServiceClient client = TextServiceClient.create(settings);

Create a text prompt

You need to provide a TextPrompt to the API:

TextPrompt prompt = TextPrompt.newBuilder()
    .setText("Repeat after me: one, two")

Generate text

Create a GenerateTextRequest

Create a GenerateTextRequest by passing a model name and prompt to the GenerateTextRequest.Builder:

GenerateTextRequest request = GenerateTextRequest.newBuilder()
    .setModel("models/text-bison-001") // Required, which model to use to generate the result
    .setPrompt(prompt) // Required
    .setTemperature(0.5f) // Optional, controls the randomness of the output
    .setCandidateCount(1) // Optional, the number of generated texts to return

Send the request

GenerateTextResponse response = client.generateText(request);

TextCompletion returnedText = response.getCandidatesList().get(0);

One, two.