gemini

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 9, 2026 License: MIT Imports: 9 Imported by: 0

README

deps.dev License License Stay with Ukraine

gemini

gemini is a Go client for the Google Gemini API. It implements the github.com/goloop/ai interface, so it looks and works like every other goloop AI provider, and exposes Gemini's native endpoints with their full options on top.

Features

  • Content generation: Generate for a single response, Stream for token-by-token output through iter.Seq2.
  • Tool use (function calling), multimodal image input and system instructions.
  • Native GenerateContent and StreamGenerateContent with the full option set (generation config, response schema, tool config).
  • Embeddings, token counting and model listing.
  • Retries on 429 and 5xx with backoff; normalized, typed API errors.
  • Depends only on github.com/goloop/ai and the standard library.

Installation

go get github.com/goloop/gemini

Quick start

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/goloop/ai"
	"github.com/goloop/gemini"
)

func main() {
	c := gemini.New(os.Getenv("GEMINI_API_KEY"))

	resp, err := c.Generate(context.Background(), &ai.Request{
		Model:    gemini.ModelGemini25Flash,
		Messages: []ai.Message{ai.UserText("Say hello in one word.")},
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(resp.Text())
}

Streaming

for chunk, err := range c.Stream(ctx, req) {
	if err != nil {
		break
	}
	fmt.Print(chunk.Text)
	if chunk.Done && chunk.Usage != nil {
		fmt.Printf("\n[%d in / %d out]\n",
			chunk.Usage.InputTokens, chunk.Usage.OutputTokens)
	}
}

Tools, images and system prompts

Tools, images and system prompts use the same shared ai types as every other provider (see the reference). Gemini keys tool results by function name, so the driver uses the function name as the tool-call ID and resolves it back automatically.

For Gemini-only options such as a JSON response schema, build a native GenerateRequest:

resp, _ := c.GenerateContent(ctx, gemini.ModelGemini25Flash, &gemini.GenerateRequest{
	Contents: []gemini.Content{{Role: "user", Parts: []gemini.Part{{Text: "List two colors."}}}},
	GenerationConfig: &gemini.GenerationConfig{
		ResponseMIMEType: "application/json",
	},
})

Native endpoints

c.Embed(ctx, "text-embedding-004", "hello", "world")
c.CountTokens(ctx, gemini.ModelGemini25Flash, req)
c.Models(ctx)
c.GetModel(ctx, gemini.ModelGemini25Flash)

Documentation

Full reference: DOC.md (Ukrainian: DOC.UK.md).

Contributing

See CONTRIBUTING.md.

License

MIT - see LICENSE.

Documentation

Overview

Package gemini is a client for the Google Gemini API, built on the goloop/ai interface.

The Client implements ai.Client, so Generate and Stream work the same as with any other goloop AI provider. On top of that it exposes Gemini's native endpoints and their full options: generateContent, streamGenerateContent, embeddings, token counting and model listing.

c := gemini.New(os.Getenv("GEMINI_API_KEY"))
resp, err := c.Generate(ctx, &ai.Request{
    Model:    gemini.ModelGemini25Flash,
    Messages: []ai.Message{ai.UserText("Say hello in one word.")},
})

Gemini keys tool results by function name rather than by call ID, so this package uses the function name as the ai.ToolUse ID on the way out and resolves it back on the way in. It depends only on goloop/ai and the standard library.

Index

Examples

Constants

View Source
const (
	ModelGemini25Pro       = "gemini-2.5-pro"
	ModelGemini25Flash     = "gemini-2.5-flash"
	ModelGemini25FlashLite = "gemini-2.5-flash-lite"
	ModelGemini20Flash     = "gemini-2.0-flash"
	ModelTextEmbedding004  = "text-embedding-004"
)

Convenience model identifiers. Any model string is accepted; use Models to discover what the account can call.

View Source
const DefaultBaseURL = "https://generativelanguage.googleapis.com/v1beta"

DefaultBaseURL is the Gemini API base URL, including the version segment.

Variables

This section is empty.

Functions

This section is empty.

Types

type Blob

type Blob struct {
	MIMEType string `json:"mimeType"`
	Data     string `json:"data"`
}

Blob is inline binary data, such as an image, with its MIME type. Data is base64-encoded.

type Candidate

type Candidate struct {
	Content      Content `json:"content"`
	FinishReason string  `json:"finishReason,omitempty"`
	Index        int     `json:"index"`
}

Candidate is one generated response option.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a Gemini API client. It implements ai.Client and adds the provider's native endpoints.

func New

func New(apiKey string, opts ...Option) *Client

New returns a Client for the given API key. Shared options (WithBaseURL, WithHTTPClient, WithTimeout, WithMaxRetries, WithHeader) configure it.

Example
package main

import (
	"fmt"

	"github.com/goloop/gemini"
)

func main() {
	c := gemini.New("AIza...")
	_ = c // use c.Generate, c.Stream, c.GenerateContent, ...
	fmt.Println(gemini.ModelGemini25Flash)
}
Output:
gemini-2.5-flash

func (*Client) CountTokens

func (c *Client) CountTokens(
	ctx context.Context,
	model string,
	req *GenerateRequest,
) (int, error)

CountTokens reports how many tokens the given content would consume for a model, without generating a response.

func (*Client) Embed

func (c *Client) Embed(
	ctx context.Context,
	model string,
	texts ...string,
) ([][]float64, error)

Embed embeds one or more plain-text inputs and returns their vectors in order, using a single batchEmbedContents call.

func (*Client) EmbedContent

func (c *Client) EmbedContent(
	ctx context.Context,
	model string,
	req *EmbedRequest,
) (*Embedding, error)

EmbedContent embeds a single request with the given model.

func (*Client) Generate

func (c *Client) Generate(
	ctx context.Context,
	req *ai.Request,
) (*ai.Response, error)

Generate implements ai.Client. It maps the request onto generateContent and returns the first candidate as an ai.Response.

Example

ExampleClient_Generate builds a request. Sending it needs a real API key, so this example only shows the shape.

package main

import (
	"fmt"

	"github.com/goloop/ai"
	"github.com/goloop/gemini"
)

func main() {
	req := &ai.Request{
		Model: gemini.ModelGemini25Flash,
		Messages: []ai.Message{
			ai.UserText("Name the capital of France."),
		},
	}
	fmt.Println(req.Model, len(req.Messages))
}
Output:
gemini-2.5-flash 1

func (*Client) GenerateContent

func (c *Client) GenerateContent(
	ctx context.Context,
	model string,
	req *GenerateRequest,
) (*GenerateResponse, error)

GenerateContent sends a native generateContent request for the given model.

func (*Client) GetModel

func (c *Client) GetModel(ctx context.Context, model string) (*Model, error)

GetModel retrieves one model by name, with or without the "models/" prefix.

func (*Client) Models

func (c *Client) Models(ctx context.Context) ([]Model, error)

Models lists the models available to the account.

func (*Client) Stream

func (c *Client) Stream(
	ctx context.Context,
	req *ai.Request,
) iter.Seq2[ai.Chunk, error]

Stream implements ai.Client. It maps the request onto streamGenerateContent and yields text deltas, completed tool calls and a final chunk carrying usage.

func (*Client) StreamGenerateContent

func (c *Client) StreamGenerateContent(
	ctx context.Context,
	model string,
	req *GenerateRequest,
) iter.Seq2[*GenerateResponse, error]

StreamGenerateContent sends a native streaming request and yields each response chunk as it arrives.

type Content

type Content struct {
	Role  string `json:"role,omitempty"`
	Parts []Part `json:"parts"`
}

Content is one turn of a conversation: a role ("user" or "model") and its parts. System text is carried separately in GenerateRequest.SystemInstruction and leaves Role empty.

type EmbedRequest

type EmbedRequest struct {
	Content              Content `json:"content"`
	TaskType             string  `json:"taskType,omitempty"`
	Title                string  `json:"title,omitempty"`
	OutputDimensionality int     `json:"outputDimensionality,omitempty"`
}

EmbedRequest is the native embedContent request body.

type Embedding

type Embedding struct {
	Values []float64 `json:"values"`
}

Embedding is a single embedding vector.

type FileData

type FileData struct {
	MIMEType string `json:"mimeType,omitempty"`
	FileURI  string `json:"fileUri"`
}

FileData references data by URI, such as an uploaded file or a supported remote resource.

type FunctionCall

type FunctionCall struct {
	Name string          `json:"name"`
	Args json.RawMessage `json:"args,omitempty"`
}

FunctionCall is a request from the model to call a declared function. Args is the JSON arguments object.

type FunctionCallingConfig

type FunctionCallingConfig struct {
	Mode string `json:"mode,omitempty"`
}

FunctionCallingConfig sets the tool-calling mode: "AUTO", "ANY" or "NONE".

type FunctionDeclaration

type FunctionDeclaration struct {
	Name        string          `json:"name"`
	Description string          `json:"description,omitempty"`
	Parameters  json.RawMessage `json:"parameters,omitempty"`
}

FunctionDeclaration describes a callable function. Parameters is a JSON Schema object describing its arguments.

type FunctionResponse

type FunctionResponse struct {
	Name     string          `json:"name"`
	Response json.RawMessage `json:"response"`
}

FunctionResponse carries a function's result back to the model. Response is a JSON object.

type GenerateRequest

type GenerateRequest struct {
	Contents          []Content         `json:"contents"`
	SystemInstruction *Content          `json:"systemInstruction,omitempty"`
	Tools             []ToolDecls       `json:"tools,omitempty"`
	ToolConfig        *ToolConfig       `json:"toolConfig,omitempty"`
	GenerationConfig  *GenerationConfig `json:"generationConfig,omitempty"`
}

GenerateRequest is the native generateContent request body.

type GenerateResponse

type GenerateResponse struct {
	Candidates    []Candidate    `json:"candidates"`
	UsageMetadata *UsageMetadata `json:"usageMetadata,omitempty"`
	ModelVersion  string         `json:"modelVersion,omitempty"`
}

GenerateResponse is the native generateContent (and stream chunk) response.

func (*GenerateResponse) Text

func (r *GenerateResponse) Text() string

Text returns the concatenation of the text parts of the first candidate.

type GenerationConfig

type GenerationConfig struct {
	Temperature      *float64        `json:"temperature,omitempty"`
	TopP             *float64        `json:"topP,omitempty"`
	MaxOutputTokens  int             `json:"maxOutputTokens,omitempty"`
	StopSequences    []string        `json:"stopSequences,omitempty"`
	ResponseMIMEType string          `json:"responseMimeType,omitempty"`
	ResponseSchema   json.RawMessage `json:"responseSchema,omitempty"`
}

GenerationConfig tunes generation. Temperature and TopP are pointers so an explicit zero is distinct from unset.

type Model

type Model struct {
	Name                       string   `json:"name"`
	BaseModelID                string   `json:"baseModelId,omitempty"`
	Version                    string   `json:"version,omitempty"`
	DisplayName                string   `json:"displayName,omitempty"`
	Description                string   `json:"description,omitempty"`
	InputTokenLimit            int      `json:"inputTokenLimit,omitempty"`
	OutputTokenLimit           int      `json:"outputTokenLimit,omitempty"`
	SupportedGenerationMethods []string `json:"supportedGenerationMethods,omitempty"`
}

Model describes a Gemini model as reported by the API.

type Option

type Option func(*settings)

Option configures a Client in New.

func WithBaseURL

func WithBaseURL(u string) Option

WithBaseURL overrides the API base URL (proxies, gateways, mock servers, Gemini-compatible endpoints).

func WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient sets the HTTP client used for requests.

func WithHeader

func WithHeader(key, value string) Option

WithHeader adds a header sent with every request.

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets how many times a request is retried on 429 and 5xx.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the per-request timeout when no custom HTTP client is set.

type Part

type Part struct {
	Text             string            `json:"text,omitempty"`
	InlineData       *Blob             `json:"inlineData,omitempty"`
	FileData         *FileData         `json:"fileData,omitempty"`
	FunctionCall     *FunctionCall     `json:"functionCall,omitempty"`
	FunctionResponse *FunctionResponse `json:"functionResponse,omitempty"`
}

Part is a single piece of a Content. Exactly one field is set: Text for plain text, InlineData for embedded bytes, FileData for a referenced file, FunctionCall for a model tool call, or FunctionResponse for a tool result.

type ToolConfig

type ToolConfig struct {
	FunctionCallingConfig *FunctionCallingConfig `json:"functionCallingConfig,omitempty"`
}

ToolConfig controls tool calling for a request.

type ToolDecls

type ToolDecls struct {
	FunctionDeclarations []FunctionDeclaration `json:"functionDeclarations,omitempty"`
}

ToolDecls groups the function declarations offered to the model.

type UsageMetadata

type UsageMetadata struct {
	PromptTokenCount     int `json:"promptTokenCount"`
	CandidatesTokenCount int `json:"candidatesTokenCount"`
	TotalTokenCount      int `json:"totalTokenCount"`
}

UsageMetadata reports token counts for a request.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL