PaLM API: Text quickstart with Go

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

Obtain an API Key

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

Set up

Create a new directory for the sample, and initialze a Go module inside it:

go mod init palm-sample

Sample code

Paste the following code into palm-sample.go:

package main

import (
  "context"
  "fmt"
  "os"

  gl "cloud.google.com/go/ai/generativelanguage/apiv1beta2"
  pb "cloud.google.com/go/ai/generativelanguage/apiv1beta2/generativelanguagepb"
  "google.golang.org/api/option"
)

func main() {
  ctx := context.Background()
  client, err := gl.NewTextRESTClient(ctx, option.WithAPIKey(os.Getenv("PALM_KEY")))
  if err != nil {
    panic(err)
  }

  defer client.Close()
  req := &pb.GenerateTextRequest{
    Model: "models/text-bison-001",
    Prompt: &pb.TextPrompt{
      Text: "What is the world's largest island that's not a continent?",
    },
  }

  resp, err := client.GenerateText(ctx, req)
  if err != nil {
    panic(err)
  }

  fmt.Println(resp.Candidates[0].Output)
}

Install the generativelanguage packages

To install the required packages, run:

go mod tidy

Inside your directory. The command will print out a log of the packages installed. You can also observe the changes in your go.mod file after this is done.

Invoke the sample

The sample code is set up to take your API key from the PALM_KEY environment variable. Run it as follows:

PALM_KEY=<your key here> go run .

You should see the model's output answer shortly:

Greenland