Get started with the Gemini API in Go applications

This tutorial demonstrates how to access the Gemini API for your Go application using the Google AI Go SDK.

In this tutorial, you'll learn how to do the following:

In addition, this tutorial contains sections about advanced use cases (like embeddings and counting tokens) as well as options for controlling content generation.

Prerequisites

This tutorial assumes that you're familiar with building applications with Go.

To complete this tutorial, make sure that your development environment meets the following requirements:

  • Go 1.20+

Set up your project

Before calling the Gemini API, you need to set up your project, which includes setting up your API key, installing the SDK package, and initializing the model.

Set up your API key

To use the Gemini API, you'll need an API key. If you don't already have one, create a key in Google AI Studio.

Get an API key

Secure your API key

It's strongly recommended that you do not check an API key into your version control system. Instead, you should use a secrets store for your API key.

All the snippets in this tutorial assume that you're accessing your API key as an environment variable.

Install the SDK package

To use the Gemini API in your own application, you need to get the Go SDK package in your module directory:

go get github.com/google/generative-ai-go

Initialize the Generative Model

Before you can make any API calls, you need to import and initialize the Generative Model.

import "github.com/google/generative-ai-go/genai"
import "google.golang.org/api/option"

ctx := context.Background()
// Access your API key as an environment variable (see "Set up your API key" above)
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
  log.Fatal(err)
}
defer client.Close()

model := client.GenerativeModel("MODEL_NAME")

When specifying a model, note the following:

  • Use a model that's specific to your use case (for example, gemini-pro-vision is for multimodal input). Within this guide, the instructions for each implementation list the recommended model for each use case.

Implement common use cases

Now that your project is set up, you can explore using the Gemini API to implement different use cases:

In the advanced use cases section, you can find information about the Gemini API and embeddings.

Generate text from text-only input

When the prompt input includes only text, use the gemini-pro model with the GenerateContent method to generate text output:

ctx := context.Background()
// Access your API key as an environment variable (see "Set up your API key" above)
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
  log.Fatal(err)
}
defer client.Close()

// For text-only input, use the gemini-pro model
model := client.GenerativeModel("gemini-pro")
resp, err := model.GenerateContent(ctx, genai.Text("Write a story about a magic backpack."))
if err != nil {
  log.Fatal(err)
}

Generate text from text-and-image input (multimodal)

Gemini provides a multimodal model (gemini-pro-vision), so you can input both text and images. Make sure to review the image requirements for prompts.

When the prompt input includes both text and images, use the gemini-pro-vision model with the GenerateContent method to generate text output:

ctx := context.Background()
// Access your API key as an environment variable (see "Set up your API key" above)
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
  log.Fatal(err)
}
defer client.Close()

// For text-and-image input (multimodal), use the gemini-pro-vision model
model := client.GenerativeModel("gemini-pro-vision")

imgData1, err := os.ReadFile(pathToImage1)
if err != nil {
  log.Fatal(err)
}

imgData2, err := os.ReadFile(pathToImage1)
if err != nil {
  log.Fatal(err)
}

prompt := []genai.Part{
  genai.ImageData("jpeg", imgData1),
  genai.ImageData("jpeg", imgData2),
  genai.Text("What's different between these two pictures?"),
}
resp, err := model.GenerateContent(ctx, prompt...)

if err != nil {
  log.Fatal(err)
}

Build multi-turn conversations (chat)

Using Gemini, you can build freeform conversations across multiple turns. The SDK simplifies the process by managing the state of the conversation, so unlike with GenerateContent, you don't have to store the conversation history yourself.

To build a multi-turn conversation (like chat), use the gemini-pro model, and initialize the chat by calling StartChat(). Then use SendMessage() to send a new user message, which will also append the message and the response to the chat history.

There are two possible options for role associated with the content in a conversation:

  • user: the role which provides the prompts. This value is the default for SendMessage calls.

  • model: the role which provides the responses. This role can be used when calling StartChat() with existing history.

ctx := context.Background()
// Access your API key as an environment variable (see "Set up your API key" above)
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
  log.Fatal(err)
}
defer client.Close()

// For text-only input, use the gemini-pro model
model := client.GenerativeModel("gemini-pro")
// Initialize the chat
cs := model.StartChat()
cs.History = []*genai.Content{
  &genai.Content{
    Parts: []genai.Part{
      genai.Text("Hello, I have 2 dogs in my house."),
    },
    Role: "user",
  },
  &genai.Content{
    Parts: []genai.Part{
      genai.Text("Great to meet you. What would you like to know?"),
    },
    Role: "model",
  },
}

resp, err := cs.SendMessage(ctx, genai.Text("How many paws are in my house?"))
if err != nil {
  log.Fatal(err)
}

Use streaming for faster interactions

By default, the model returns a response after completing the entire generation process. You can achieve faster interactions by not waiting for the entire result, and instead use streaming to handle partial results.

The following example shows how to implement streaming with the GenerateContentStream method to generate text from a text-and-image input prompt.

ctx := context.Background()
// Access your API key as an environment variable (see "Set up your API key" above)
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
  log.Fatal(err)
}
defer client.Close()

// For text-and-image input (multimodal), use the gemini-pro-vision model
model := client.GenerativeModel("gemini-pro-vision")

imageBytes, err := os.ReadFile(pathToImage)

img := genai.ImageData("jpeg", imageBytes)
prompt := genai.Text("Tell me a story about this animal")
iter := model.GenerateContentStream(ctx, img, prompt)

for {
  resp, err := iter.Next()
  if err == iterator.Done {
    break
  }
  if err != nil {
    log.Fatal(err)
  }

  // ... print resp
}

You can use a similar approach for text-only input and chat use cases.

prompt := genai.Text("Tell me a story about a lumberjack and his giant ox")
iter := model.GenerateContentStream(ctx, prompt)
prompt := genai.Text("And how do you feel about that?")
iter := cs.SendMessageStream(ctx, prompt)

Implement advanced use cases

The common use cases described in the previous section of this tutorial help you become comfortable with using the Gemini API. This section describes some use cases that might be considered more advanced.

Use embeddings

Embedding is a technique used to represent information as a list of floating point numbers in an array. With Gemini, you can represent text (words, sentences, and blocks of text) in a vectorized form, making it easier to compare and contrast embeddings. For example, two texts that share a similar subject matter or sentiment should have similar embeddings, which can be identified through mathematical comparison techniques such as cosine similarity.

Use the embedding-001 model with the EmbedContent method (or the BatchEmbedContent method) to generate embeddings. The following example generates an embedding for a single string:

ctx := context.Background()
// Access your API key as an environment variable (see "Set up your API key" above)
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
  log.Fatal(err)
}
defer client.Close()
em := client.EmbeddingModel("embedding-001")
res, err := em.EmbedContent(ctx, genai.Text("The quick brown fox jumps over the lazy dog."))

if err != nil {
  panic(err)
}
fmt.Println(res.Embedding.Values)

Count tokens

When using long prompts, it might be useful to count tokens before sending any content to the model. The following examples show how to use CountTokens() for various use cases:

// For text-only input
text := "Parrots can be green and live a long time."
resp, err := model.CountTokens(ctx, genai.Text(text))
if err != nil {
  log.Fatal(err)
}
fmt.Println(resp.TotalTokens)
// For text-and-image input (multimodal)
text := "Parrots can be green and live a long time."
imageBytes, err := os.ReadFile(pathToImage)
if err != nil {
  log.Fatal(err)
}

resp, err := model.CountTokens(
    ctx,
    genai.Text(text),
    genai.ImageData("png", imageBytes))
  if err != nil {
    log.Fatal(err)
}
fmt.Println(resp.TotalTokens)

Options to control content generation

You can control content generation by configuring model parameters and by using safety settings.

Configure model parameters

Every prompt you send to the model includes parameter values that control how the model generates a response. The model can generate different results for different parameter values. Learn more about Model parameters. The configuration is maintained for the lifetime of your model instance.

// ...

model := client.GenerativeModel("MODEL_NAME")

// Configure model parameters by invoking Set* methods on the model.
model.SetTemperature(0.9)
model.SetTopK(1)

// ...

Use safety settings

You can use safety settings to adjust the likelihood of getting responses that may be considered harmful. By default, safety settings block content with medium and/or high probability of being unsafe content across all dimensions. Learn more about Safety settings.

Here's how to set one safety setting:

// ...

model := client.GenerativeModel("MODEL_NAME")

model.SafetySettings = []*genai.SafetySetting{
  {
    Category:  genai.HarmCategoryHarassment,
    Threshold: genai.HarmBlockOnlyHigh,
  },
}

// ...

You can also set more than one safety setting:

// ...

model := client.GenerativeModel("MODEL_NAME")

model.SafetySettings = []*genai.SafetySetting{
  {
    Category:  genai.HarmCategoryHarassment,
    Threshold: genai.HarmBlockOnlyHigh,
  },
  {
    Category:  genai.HarmCategoryHateSpeech,
    Threshold: genai.HarmBlockMediumAndAbove,
  },
}

// ...

What's next

  • Prompt design is the process of creating prompts that elicit the desired response from language models. Writing well structured prompts is an essential part of ensuring accurate, high quality responses from a language model. Learn about best practices for prompt writing.

  • Gemini offers several model variations to meet the needs of different use cases, such as input types and complexity, implementations for chat or other dialog language tasks, and size constraints. Learn about the available Gemini models.

  • Gemini offers options for requesting rate limit increases. The rate limit for Gemini Pro models is 60 requests per minute (RPM).