PaLM API: Embeddings Quickstart with Node.js

Installing the API Client

In a new directory, initialize a Node.js project using npm and install the google-auth library:

npm init -y
npm install google-auth-library

Next, you'll need to install the PaLM API client library:

npm install @google-ai/generativelanguage

Generating Messages

Create a new file index.js and add the following code, supplying your API key through the API_KEY environment variable:

const { TextServiceClient } =
  require("@google-ai/generativelanguage").v1beta3;

const { GoogleAuth } = require("google-auth-library");

const MODEL_NAME = "models/embedding-gecko-001";
const API_KEY = process.env.API_KEY;

const client = new TextServiceClient({
  authClient: new GoogleAuth().fromAPIKey(API_KEY),
});

const text = "Repeat after me: one, two,";

client
  .embedText({
    model: MODEL_NAME,
    text: text,
  })
  .then((result) => {
    console.log(JSON.stringify(result));
  });

Then run the script:

node index.js