Skip to main content

Google Gemini

The llms/googleai package calls Google Gemini through the Google AI Studio endpoint. To use Gemini through Google Cloud instead, see Vertex AI.

Setup

Create an API key at Google AI Studio and set it in GOOGLE_API_KEY, or pass it explicitly. Note that googleai.New takes a context.Context:

llm, err := googleai.New(ctx,
googleai.WithAPIKey(os.Getenv("GOOGLE_API_KEY")),
googleai.WithDefaultModel("gemini-2.5-flash"),
)

On thinking-capable models, control reasoning per call with llms.WithReasoning (Gemini 3.x maps effort to a thinking level; 2.5 uses a token budget), and request schema-constrained JSON with llms.WithStructuredOutput.

For a full walkthrough, see the Gemini quickstart.

Example

// Set the GOOGLE_API_KEY env var to your API key taken from ai.google.dev
package main

import (
"context"
"fmt"
"log"
"os"

"github.com/vxcontrol/langchaingo/llms"
"github.com/vxcontrol/langchaingo/llms/googleai"
)

func main() {
ctx := context.Background()
apiKey := os.Getenv("GOOGLE_API_KEY")
llm, err := googleai.New(ctx, googleai.WithAPIKey(apiKey))
if err != nil {
log.Fatal(err)
}

prompt := "Who was the second person to walk on the moon?"
answer, err := llms.GenerateFromSinglePrompt(ctx, llm, prompt)
if err != nil {
log.Fatal(err)
}

fmt.Println(answer)
}