Google Generative AI Go SDK (Legacy)

repository·main·Indexed 21 days ago

https://github.com/google/generative-ai-go

A legacy Go SDK for the Gemini API. This repository is deprecated and superseded by the unified Google Generative AI SDK for Go. It provides functionality to initialize clients via genai.NewClient, configure GenerativeModel instances, generate content using GenerateContent and GenerateContentStream, count tokens, and retrieve model information. Support for this SDK ends on November 30, 2025.

Tokens
1.4K
Snippets
6
Records
7
Agent score
25%

What's inside generative-ai-go

  1. Migrate to the Google Generative AI SDK for Go

    main

    This repository (google/generative-ai-go) is deprecated and considered legacy. For all new development, latest features, and performance improvements, you should migrate to the official Google Generative AI SDK for Go.

    Migration Guidance:

    • The new SDK is a unified solution for all Google GenAI models (Gemini, Veo, Imagen, etc.).
    • Updated Gemini API documentation and Go quickstart guides are available at ai.google.dev.

    Legacy Repository Support Status:

    • Maintenance: Restricted to critical bug fixes only. No new features will be added.
    • End-of-Life: All support, including bug fixes, will permanently end on November 30, 2025.
  2. Initialize a new Google generative AI client

    main

    Use genai.NewClient to create a new client instance. You must provide an authentication option, such as an API Key. Clients are safe for concurrent use and should be reused throughout your application rather than being created per request. You can configure the client using options from the google.golang.org/api/option package.

    To use an API Key, retrieve it from an environment variable (e.g., GEMINI_API_KEY) and pass it via option.WithAPIKey.

    import (
    	"context"
    	"os"
    
    	"github.com/google/generative-ai-go/genai"
    	"google.golang.org/api/option"
    )
    
    func main() {
    	ctx := context.Background()
    	client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("GEMINI_API_KEY")))
    	if err != nil {
    		// handle error
    	}
    	defer client.Close()
    }
  3. Create and configure a GenerativeModel

    main

    A GenerativeModel represents a specific model instance (e.g., "gemini-1.5-flash") that can generate content. You create one using client.GenerativeModel(name).

    Once created, you can configure the model by setting its exported fields before making calls:

    • GenerationConfig: Controls parameters like temperature and top-p.
    • SafetySettings: Configures content filtering.
    • Tools: Enables features like function calling.
    • SystemInstruction: Provides a high-priority system prompt to guide model behavior.
    • CachedContentName: Specifies the name of previously created cached content to use for this model.
    model := client.GenerativeModel("gemini-1.5-flash")
    model.SystemInstruction = &genai.Content{
        Parts: []genai.Part{genai.Text("You are a helpful assistant.")},
    }
  4. Generate content from a model

    main

    Use GenerativeModel.GenerateContent to send a single request and receive a single response. This method accepts a variadic number of Part objects (such as Text).

    For streaming responses, use GenerateContentStream, which returns a GenerateContentResponseIterator. You can iterate through the stream using .Next() and retrieve the full combined response using .MergedResponse() once the iterator reaches iterator.Done.

    // Single response
    resp, err := model.GenerateContent(ctx, genai.Text("Write a poem about Go."))
    
    // Streaming response
    iter := model.GenerateContentStream(ctx, genai.Text("Write a long story."))
    for { 
        resp, err := iter.Next()
        if err == iterator.Done {
            break
        }
        if err != nil {
            // handle error
        }
        // process resp
    }
    fullResp := iter.MergedResponse()
  5. Count tokens in content

    main

    Use GenerativeModel.CountTokens to calculate the number of tokens in a given set of Part objects. This is useful for managing context window limits and estimating costs.

    countResp, err := model.CountTokens(ctx, genai.Text("How many tokens is this?"))
    if err != nil {
        // handle error
    }
    fmt.Println(countResp.TotalTokens)
  6. Handle blocked responses with BlockedError

    main

    If a model's response or the input prompt is blocked due to safety or other reasons, the SDK returns a BlockedError. This error type provides details on why the content was blocked:

    • Candidate: If non-nil, the model's response was blocked. Check the FinishReason field.
    • PromptFeedback: If non-nil, the input prompt itself was blocked. Check the BlockReason field.
    type BlockedError struct {
    	Candidate      *Candidate
    	PromptFeedback *PromptFeedback
    }