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 ¶
- Constants
- type Blob
- type Candidate
- type Client
- func (c *Client) CountTokens(ctx context.Context, model string, req *GenerateRequest) (int, error)
- func (c *Client) Embed(ctx context.Context, model string, texts ...string) ([][]float64, error)
- func (c *Client) EmbedContent(ctx context.Context, model string, req *EmbedRequest) (*Embedding, error)
- func (c *Client) Generate(ctx context.Context, req *ai.Request) (*ai.Response, error)
- func (c *Client) GenerateContent(ctx context.Context, model string, req *GenerateRequest) (*GenerateResponse, error)
- func (c *Client) GetModel(ctx context.Context, model string) (*Model, error)
- func (c *Client) Models(ctx context.Context) ([]Model, error)
- func (c *Client) Stream(ctx context.Context, req *ai.Request) iter.Seq2[ai.Chunk, error]
- func (c *Client) StreamGenerateContent(ctx context.Context, model string, req *GenerateRequest) iter.Seq2[*GenerateResponse, error]
- type Content
- type EmbedRequest
- type Embedding
- type FileData
- type FunctionCall
- type FunctionCallingConfig
- type FunctionDeclaration
- type FunctionResponse
- type GenerateRequest
- type GenerateResponse
- type GenerationConfig
- type Model
- type Option
- type Part
- type ToolConfig
- type ToolDecls
- type UsageMetadata
Examples ¶
Constants ¶
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
GetModel retrieves one model by name, with or without the "models/" prefix.
func (*Client) Stream ¶
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 ¶
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 ¶
WithBaseURL overrides the API base URL (proxies, gateways, mock servers, Gemini-compatible endpoints).
func WithHTTPClient ¶
WithHTTPClient sets the HTTP client used for requests.
func WithHeader ¶
WithHeader adds a header sent with every request.
func WithMaxRetries ¶
WithMaxRetries sets how many times a request is retried on 429 and 5xx.
func WithTimeout ¶
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.