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
// 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.
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
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
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.
- Install
go getthe module. Go 1.26 or newer. - Set the key
export GEMINI_API_KEY=…, or passWithAPIKey. - Create the client
gogemini.New(opts...)checks the key; each attempt gets up to 5 minutes. - Call
GenerateContent(ctx, prompt), thenresp.Text().
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.
| Symbol | Kind | What it does |
|---|---|---|
| New(opts...) | func | Builds a client. Returns ErrMissingAPIKey when neither WithAPIKey nor GEMINI_API_KEY gives a key. |
| WithAPIKey · WithModel | option | Key and model. The default is gemini-3.8-flash and may change in a minor release; Client.Model() tells which one is used. |
| WithHTTPClient · WithTimeout | option | Bring your own *http.Client, and set the per-attempt limit with WithTimeout (5 min by default; for a stream it covers the start only). |
| WithBaseURL | option | Another host: a proxy, or an httptest server in your tests. HTTPS only; plain HTTP for loopback. |
| GenerateContent(ctx, prompt) | method | Sends one user prompt to :generateContent and returns the *Response. |
| Generate(ctx, req) | method | Same call with a full GenerateContentRequest, for callers that build the contents themselves. |
| Content · Part · Candidate · UsageMetadata | type | A turn and its pieces (text, Blob, FileData, calls, results), one generated answer, and its token counts. |
| Ptr · DefaultBaseURL · APIKeyEnv | helper | A pointer for optional config values such as a temperature of 0; the API host; the key's environment variable. |
| Response.Text() | method | Text of the first candidate; empty when the prompt was blocked (see PromptFeedback). |
| GenerateContentStream · GenerateStream | method | Stream the answer as an iter.Seq2[*Response, error]; breaking out of the loop closes the connection. |
| NewChat · Chat.Send · Chat.History | method | A multi-turn conversation; a turn is kept only when the model answers. |
| WithSystemInstruction · WithGenerationConfig | option | Per-client defaults for the system instruction and generation parameters; a request's own values win. |
| TextPart · InlineDataPart · FileDataPart · UserContent | func | Build turns with images, PDFs or file references; Chat.SendParts sends them in a conversation. |
| JSONResponse(schema) | func | JSON output that conforms to a JSON Schema, via GenerationConfig.ResponseFormat. |
| WithSafetySettings · SafetySetting | option | Blocking thresholds per harm category; each candidate carries its SafetyRatings. |
| ThinkingConfig · Response.Thoughts | type | Reasoning level or budget; Text() leaves the reasoning out, and chats send thought signatures back. |
| Chat.AddFunction · FunctionHandler | method | Let the model call your Go functions; Send runs them and returns the final answer, up to SetMaxFunctionRounds rounds (ErrFunctionCallLimit beyond). |
| FunctionDeclaration · FunctionCall · FunctionResponse | type | A function's name, description and JSON Schema; a call with its arguments; the result sent back. |
| Tool · ToolConfig · Response.FunctionCalls | type | Function calling by hand, outside a chat: declare tools, read the calls, send FunctionResponseParts. |
| Chat.SendStream · CountTokens | method | Stream a chat reply into the history; count a prompt's tokens before sending it. |
| WithRetry · RetryPolicy | option | Retry 408, 429, 5xx and network errors with backoff and jitter; 4 attempts by default, honouring Google's RetryInfo. |
| *APIError | error | Non-2xx reply: HTTP code, Google status such as RESOURCE_EXHAUSTED, message, Reason, RetryDelay and Retryable(). Match it with errors.As. |
| ErrMissingAPIKey · ErrInvalidBaseURL · ErrInvalidTimeout · ErrEmptyModel · ErrInvalidRetryPolicy | error | Returned by New for a missing key or an invalid option. |
| ErrEmptyRequest · ErrRedirectOtherHost | error | An 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.
Releases
Release history
Every release is in the changelog; planned work is tracked as GitHub milestones, generated from docs/milestone.md.
- v0.2.0 · first working clientReleased 2026-09-29.
- v0.3.0 · hardeningReleased 2026-09-29.
- v0.4.0 · SDK experienceReleased 2026-09-29: streaming, chat, generation parameters, retries.
- v1.0.0 · stable APIReleased 2026-09-29: API frozen, compatibility enforced in CI.
- v1.1.0 · multimodalReleased 2026-09-30: images, JSON output, safety, thinking, chat streaming.
- v1.2.0 · tool callingReleased 2026-09-30: the model calls your Go functions.
// 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
}