v1.2.0 · stable · MIT

Talk to Gemini
from Go.

A small client for the official Gemini API. One API key, one call, typed errors, and nothing outside the standard library.

$ go get github.com/Allan-Nava/go-gemini
main.go
// Reads GEMINI_API_KEY from the environment
client, err := gogemini.New()
if err != nil {
    return err
}

resp, err := client.GenerateContent(ctx,
    "Explain goroutines in one sentence")
if err != nil {
    return err
}
fmt.Println(resp.Text())

Status

Where the SDK stands

v1.2.0 is out: the model can call your Go functions, and a chat runs the round trip for you. The API is stable since v1.0.0; 1.x releases only add to it.

Calls

Everything the API does for text

  • Single calls, streams and multi-turn chats
  • Images and files, JSON output with a schema
  • Function calling, thinking, token counting
Built in

The plumbing is handled

  • Retries with backoff on 429 and 5xx
  • A time limit per attempt that never cuts a stream
  • The key stays on the API host, over HTTPS only
Stable

v1.x

  • The exported API is frozen since v1.0.0
  • CI rejects incompatible changes
  • Standard library only, no dependencies

Quickstart

From zero to an answer

Get a key from Google AI Studio and keep it in the environment, not in your code.

  1. Installgo get the module. Go 1.26 or newer.
  2. Set the keyexport GEMINI_API_KEY=…, or pass WithAPIKey.
  3. Create the clientgogemini.New(opts...) checks the key; each attempt gets up to 5 minutes.
  4. CallGenerateContent(ctx, prompt), then resp.Text().
main.go
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/Allan-Nava/go-gemini/gogemini"
)

func main() {
    client, err := gogemini.New(gogemini.WithModel("gemini-3.8-flash"))
    if err != nil {
        log.Fatal(err)
    }
    resp, err := client.GenerateContent(context.Background(), "Say hello")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(resp.Text())
}

API

Package gogemini

The main entry points; the README lists every exported identifier. Runnable examples are on pkg.go.dev; request semantics are in the Gemini API reference.

SymbolKindWhat it does
New(opts...)funcBuilds a client. Returns ErrMissingAPIKey when neither WithAPIKey nor GEMINI_API_KEY gives a key.
WithAPIKey · WithModeloptionKey and model. The default is gemini-3.8-flash and may change in a minor release; Client.Model() tells which one is used.
WithHTTPClient · WithTimeoutoptionBring your own *http.Client, and set the per-attempt limit with WithTimeout (5 min by default; for a stream it covers the start only).
WithBaseURLoptionAnother host: a proxy, or an httptest server in your tests. HTTPS only; plain HTTP for loopback.
GenerateContent(ctx, prompt)methodSends one user prompt to :generateContent and returns the *Response.
Generate(ctx, req)methodSame call with a full GenerateContentRequest, for callers that build the contents themselves.
Content · Part · Candidate · UsageMetadatatypeA turn and its pieces (text, Blob, FileData, calls, results), one generated answer, and its token counts.
Ptr · DefaultBaseURL · APIKeyEnvhelperA pointer for optional config values such as a temperature of 0; the API host; the key's environment variable.
Response.Text()methodText of the first candidate; empty when the prompt was blocked (see PromptFeedback).
GenerateContentStream · GenerateStreammethodStream the answer as an iter.Seq2[*Response, error]; breaking out of the loop closes the connection.
NewChat · Chat.Send · Chat.HistorymethodA multi-turn conversation; a turn is kept only when the model answers.
WithSystemInstruction · WithGenerationConfigoptionPer-client defaults for the system instruction and generation parameters; a request's own values win.
TextPart · InlineDataPart · FileDataPart · UserContentfuncBuild turns with images, PDFs or file references; Chat.SendParts sends them in a conversation.
JSONResponse(schema)funcJSON output that conforms to a JSON Schema, via GenerationConfig.ResponseFormat.
WithSafetySettings · SafetySettingoptionBlocking thresholds per harm category; each candidate carries its SafetyRatings.
ThinkingConfig · Response.ThoughtstypeReasoning level or budget; Text() leaves the reasoning out, and chats send thought signatures back.
Chat.AddFunction · FunctionHandlermethodLet the model call your Go functions; Send runs them and returns the final answer, up to SetMaxFunctionRounds rounds (ErrFunctionCallLimit beyond).
FunctionDeclaration · FunctionCall · FunctionResponsetypeA function's name, description and JSON Schema; a call with its arguments; the result sent back.
Tool · ToolConfig · Response.FunctionCallstypeFunction calling by hand, outside a chat: declare tools, read the calls, send FunctionResponseParts.
Chat.SendStream · CountTokensmethodStream a chat reply into the history; count a prompt's tokens before sending it.
WithRetry · RetryPolicyoptionRetry 408, 429, 5xx and network errors with backoff and jitter; 4 attempts by default, honouring Google's RetryInfo.
*APIErrorerrorNon-2xx reply: HTTP code, Google status such as RESOURCE_EXHAUSTED, message, Reason, RetryDelay and Retryable(). Match it with errors.As.
ErrMissingAPIKey · ErrInvalidBaseURL · ErrInvalidTimeout · ErrEmptyModel · ErrInvalidRetryPolicyerrorReturned by New for a missing key or an invalid option.
ErrEmptyRequest · ErrRedirectOtherHosterrorAn empty prompt is rejected before sending; a redirect to another host is refused, so the key stays put.

Auth

One key, in a header

The client sends your key in the x-goog-api-key header, never in the URL, so it stays out of access logs and error messages. WithAPIKey wins over GEMINI_API_KEY.

The key only travels over HTTPS and only to the base URL's host: net/http would copy it to any redirect target, so redirects to another host are refused with ErrRedirectOtherHost.

The Bard-era design copied the __Secure-1PSID session cookie out of the browser. That cookie opens the whole Google account and the web endpoint was never meant for automated use, so it is not supported.

Never commit a key. Keep it in the environment or a secret manager, and restrict it in Google AI Studio.

Sequence: the SDK reads the key, posts the prompt with the key in a header to the Gemini API, which returns the generated content. go-gemini Gemini API key · env/option POST :generateContent x-goog-api-key candidates[].content non-2xx → *APIError 3xx to another host → refused

Releases

Release history

Every release is in the changelog; planned work is tracked as GitHub milestones, generated from docs/milestone.md.

  1. v0.2.0 · first working clientReleased 2026-09-29.
  2. v0.3.0 · hardeningReleased 2026-09-29.
  3. v0.4.0 · SDK experienceReleased 2026-09-29: streaming, chat, generation parameters, retries.
  4. v1.0.0 · stable APIReleased 2026-09-29: API frozen, compatibility enforced in CI.
  5. v1.1.0 · multimodalReleased 2026-09-30: images, JSON output, safety, thinking, chat streaming.
  6. v1.2.0 · tool callingReleased 2026-09-30: the model calls your Go functions.
errors.go
// Handle quota errors differently from the rest
resp, err := client.GenerateContent(ctx, prompt)
var apiErr *gogemini.APIError
switch {
case errors.As(err, &apiErr) && apiErr.StatusCode == 429:
    // back off and retry later
case err != nil:
    return err
}