PaLM API: Embeddings quickstart with Java

This quickstart gets you started using the embeddings service of the PaLM API. You will use the embeddings service to generate text embeddings that you can use in various natural language applications.

Obtain an API Key

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

What are embeddings?

Embeddings are a technique used to represent text (like words, sentences, or entire paragraphs) as a list of floating point numbers in an array. The key idea is that text with similar meanings will have similar embeddings. You can use the relationship between them for many important tasks.

Install the API client

These instructions will install the PaLM Java SDK 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-v1-java.tar.gz file.
  2. Extract the files and install them in mavenLocal:

    # Extract the files
    tar -xzvf google-cloud-ai-generativelanguage-v1-java.tar.gz
    cd google-cloud-ai-generativelanguage-v1-java
    # Install to mavenLocal
    ./gradlew publishToMavenLocal
  3. Open your Gradle configuration file and make sure mavenLocal() is listed under repositories:

    repositories {
        // ...
        // Add the Maven Local repository
  4. 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", "API_KEY");

TransportChannelProvider provider = InstantiatingGrpcChannelProvider.newBuilder()

TextServiceSettings settings = TextServiceSettings.newBuilder()

TextServiceClient client = TextServiceClient.create(settings);

Generate embeddings

In this section, you will see how to generate embeddings for a piece of text using the embedText method.

To use the embedText method, pass in the name of the model as well as some text to embed. You will get a list of floating point values.

EmbedTextRequest request = EmbedTextRequest.newBuilder()
    .setModel("models/embedding-gecko-001") // Required, which model to use to generate the result
    .setText("What do squirrels eat?") // Required

EmbedTextResponse response = client.embedText(request);

List<Float> embedding = response.getEmbedding().getValueList();