google

package
v0.0.0-...-0f13597 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 41 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package google adapts the Gemini API (AI Studio) and Vertex AI generateContent and embedding endpoints to package ai.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CodeExecution

func CodeExecution() ai.Tool

CodeExecution lets the model run Python; runs arrive as provider-executed ToolCall and ToolResult parts.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"

	"github.com/minodevss/ai-go"
	"github.com/minodevss/ai-go/google"
)

func exampleServer(responses map[string]string) *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = io.WriteString(w, responses[r.URL.Path])
	}))
}

func main() {
	srv := exampleServer(map[string]string{"/v1beta/models/gemini-3-flash:generateContent": `{"candidates":[{"content":{"role":"model","parts":[
		{"executableCode":{"language":"PYTHON","code":"print(17*23)"}},
		{"codeExecutionResult":{"outcome":"OUTCOME_OK","output":"391\n"}},
		{"text":"It is 391."}]},"finishReason":"STOP"}]}`})
	defer srv.Close()
	model := google.New(google.WithAPIKey("test-key"), google.WithBaseURL(srv.URL+"/v1beta")).Model("gemini-3-flash")

	res, err := ai.GenerateText(context.Background(), model, ai.TextRequest{
		Messages: []ai.Message{ai.User("What is 17*23?")},
		Tools:    []ai.Tool{google.CodeExecution()},
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, p := range res.Content {
		switch p := p.(type) {
		case ai.ToolCall:
			fmt.Println("ran:", p.Name, p.ProviderExecuted)
		case ai.Text:
			fmt.Println(p.Text)
		}
	}
}
Output:
ran: code_execution true
It is 391.

func FileID

func FileID(id string) ai.File

FileID references a file stored with the Files API instead of sending its bytes. Set MediaType on the result when it is known.

Example
package main

import (
	"fmt"

	"github.com/minodevss/ai-go/google"
)

func main() {
	f := google.FileID("abc-123")
	fmt.Println(f.URL)
}
Output:
https://generativelanguage.googleapis.com/v1beta/files/abc-123

func FileIDOf

func FileIDOf(f ai.File) (string, bool)

FileIDOf returns the file id held by a File that UploadFile, GetFile, ListFiles or FileID produced.

Example
package main

import (
	"fmt"

	"github.com/minodevss/ai-go"
	"github.com/minodevss/ai-go/google"
)

func main() {
	id, ok := google.FileIDOf(google.FileID("files/abc-123"))
	fmt.Println(id, ok)
	_, ok = google.FileIDOf(ai.File{URL: "https://example.com/a.pdf"})
	fmt.Println(ok)
}
Output:
abc-123 true
false

func FileSearch

func FileSearch(storeNames ...string) ai.Tool

FileSearch grounds answers in the named File Search stores, for example "fileSearchStores/docs-123".

Example
package main

import (
	"fmt"

	"github.com/minodevss/ai-go/google"
)

func main() {
	fmt.Println(google.FileSearch("fileSearchStores/docs-123").Name)
}
Output:
file_search

func Maps

func Maps() ai.Tool

Maps declares grounding with Google Maps.

Example
package main

import (
	"fmt"

	"github.com/minodevss/ai-go/google"
)

func main() {
	fmt.Println(google.Maps().Name)
}
Output:
google_maps
func Search() ai.Tool

Search declares grounding with Google Search; grounding metadata lands in the response Provider data and as Text citations.

func URLContext

func URLContext() ai.Tool

URLContext lets the model read the URLs it finds in the prompt.

Example
package main

import (
	"fmt"

	"github.com/minodevss/ai-go/google"
)

func main() {
	tool := google.URLContext()
	fmt.Println(tool.Name)
}
Output:
url_context

Types

type EmbeddingModel

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

EmbeddingModel embeds text, and for gemini-embedding-2 on AI Studio also images, audio, video and PDF. Its MaxBatch is 100 on AI Studio, 5 on Vertex and 1 for gemini-embedding-001 on Vertex.

func NewEmbeddingModel

func NewEmbeddingModel(id string) *EmbeddingModel
Example
package main

import (
	"fmt"

	"github.com/minodevss/ai-go/google"
)

func main() {
	m := google.NewEmbeddingModel("gemini-embedding-001")
	fmt.Println(m.ModelID(), m.MaxBatch())
}
Output:
gemini-embedding-001 100

func (*EmbeddingModel) Embed

func (*EmbeddingModel) MaxBatch

func (m *EmbeddingModel) MaxBatch() int

func (*EmbeddingModel) ModelID

func (m *EmbeddingModel) ModelID() string

func (*EmbeddingModel) Provider

func (m *EmbeddingModel) Provider() string

type ImageModel

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

ImageModel generates and edits images with a Nano Banana model. N above 1 sends N sequential requests. Input Files are sent as up to 14 reference images; masks are not supported.

func NewImageModel

func NewImageModel(id string) *ImageModel
Example
package main

import (
	"fmt"

	"github.com/minodevss/ai-go/google"
)

func main() {
	fmt.Println(google.NewImageModel("gemini-nano-banana-2.1").ModelID())
}
Output:
gemini-nano-banana-2.1

func (*ImageModel) GenerateImage

func (m *ImageModel) GenerateImage(ctx context.Context, c *ai.ImageCall) (*ai.ImageResponse, error)

func (*ImageModel) ModelID

func (m *ImageModel) ModelID() string

func (*ImageModel) Provider

func (m *ImageModel) Provider() string

type ImageOptions

type ImageOptions struct {
	SafetySettings []SafetySetting `json:"safetySettings,omitzero"`
}

ImageOptions are image settings passed with ai.Providers under "google", also on Vertex. Unset fields keep the API default.

Example
package main

import (
	"fmt"

	"github.com/minodevss/ai-go"
	"github.com/minodevss/ai-go/google"
)

func main() {
	p := ai.Providers(google.ImageOptions{SafetySettings: []google.SafetySetting{{Category: "HARM_CATEGORY_HARASSMENT", Threshold: "BLOCK_ONLY_HIGH"}}})
	_, ok := p["google"]
	fmt.Println(ok)
}
Output:
true

func (ImageOptions) ProviderName

func (ImageOptions) ProviderName() string

type LanguageModel

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

LanguageModel talks to generateContent and keeps every response part in Provider data for replay.

func Model

func Model(id string) *LanguageModel

Model returns a language model from a provider configured from the environment.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"os"

	"github.com/minodevss/ai-go"
	"github.com/minodevss/ai-go/google"
)

func exampleServer(responses map[string]string) *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = io.WriteString(w, responses[r.URL.Path])
	}))
}

const exampleReply = `{"candidates":[{"content":{"role":"model","parts":[{"text":"Hello from Gemini."}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":9,"thoughtsTokenCount":4,"candidatesTokenCount":6},"responseId":"resp-1"}`

func main() {
	srv := exampleServer(map[string]string{"/v1beta/models/gemini-3-flash:generateContent": exampleReply})
	defer srv.Close()
	if err := os.Setenv("GOOGLE_GEMINI_BASE_URL", srv.URL+"/v1beta"); err != nil {
		fmt.Println(err)
		return
	}
	defer os.Unsetenv("GOOGLE_GEMINI_BASE_URL")

	res, err := ai.GenerateText(context.Background(), google.Model("gemini-3-flash"), ai.TextRequest{
		Messages: []ai.Message{ai.User("Say hello.")},
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(res.Text)
}
Output:
Hello from Gemini.

func (*LanguageModel) BatchResults

func (m *LanguageModel) BatchResults(ctx context.Context, id string) iter.Seq2[ai.BatchEntry, error]

BatchResults reads inline responses or downloads the responses file; a response without a key is identified by its position.

func (*LanguageModel) BatchStatus

func (m *LanguageModel) BatchStatus(ctx context.Context, id string) (*ai.BatchStatus, error)

func (*LanguageModel) CancelBatch

func (m *LanguageModel) CancelBatch(ctx context.Context, id string) error

func (*LanguageModel) DeleteFile

func (m *LanguageModel) DeleteFile(ctx context.Context, id string) error

func (*LanguageModel) Generate

func (m *LanguageModel) Generate(ctx context.Context, c *ai.Call) (*ai.Response, error)

func (*LanguageModel) GetFile

func (m *LanguageModel) GetFile(ctx context.Context, id string) (*ai.File, error)

func (*LanguageModel) ListFiles

func (m *LanguageModel) ListFiles(ctx context.Context, c *ai.FileListCall) (*ai.FileList, error)

func (*LanguageModel) ModelID

func (m *LanguageModel) ModelID() string

func (*LanguageModel) Provider

func (m *LanguageModel) Provider() string

func (*LanguageModel) StartBatch

func (m *LanguageModel) StartBatch(ctx context.Context, calls []ai.BatchCall) (string, error)

StartBatch sends requests inline under 20 MB and uploads a JSONL file above that. Vertex AI is not supported.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/minodevss/ai-go"
	"github.com/minodevss/ai-go/google"
)

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		switch r.URL.Path {
		case "/v1beta/models/gemini-3-flash:batchGenerateContent":
			_, _ = io.WriteString(w, `{"name":"batches/123456"}`)
		default:
			_, _ = io.WriteString(w, `{"name":"batches/123456","done":true,"metadata":{"state":"JOB_STATE_SUCCEEDED"},"response":{"inlinedResponses":{"inlinedResponses":[{"metadata":{"key":"q1"},"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"Paris."}]},"finishReason":"STOP"}]}}]}}}`)
		}
	}))
	defer srv.Close()

	model := google.New(google.WithAPIKey("test-key"), google.WithBaseURL(srv.URL+"/v1beta")).Model("gemini-3-flash")
	job, err := ai.StartBatch(context.Background(), model, []ai.BatchItem{
		{ID: "q1", Request: ai.TextRequest{Messages: []ai.Message{ai.User("Capital of France?")}}},
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	if err := job.Wait(context.Background(), time.Second); err != nil {
		fmt.Println(err)
		return
	}
	for r := range job.Results(context.Background()) {
		fmt.Println(r.ID, r.Result.Text)
	}
}
Output:
q1 Paris.

func (*LanguageModel) Stream

func (m *LanguageModel) Stream(ctx context.Context, c *ai.Call) (*ai.StreamResponse, error)

func (*LanguageModel) UploadFile

func (m *LanguageModel) UploadFile(ctx context.Context, c *ai.FileUploadCall) (*ai.File, error)

type Option

type Option func(*options)

func WithAPIKey

func WithAPIKey(key string) Option
Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"

	"github.com/minodevss/ai-go"
	"github.com/minodevss/ai-go/google"
)

const exampleReply = `{"candidates":[{"content":{"role":"model","parts":[{"text":"Hello from Gemini."}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":9,"thoughtsTokenCount":4,"candidatesTokenCount":6},"responseId":"resp-1"}`

func headerServer(header string, got *string) *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		*got = r.Header.Get(header)
		w.Header().Set("Content-Type", "application/json")
		_, _ = io.WriteString(w, exampleReply)
	}))
}

func generateHello(p *google.Provider) error {
	_, err := ai.GenerateText(context.Background(), p.Model("gemini-3-flash"), ai.TextRequest{Messages: []ai.Message{ai.User("hi")}})
	return err
}

func main() {
	var key string
	srv := headerServer("x-goog-api-key", &key)
	defer srv.Close()

	if err := generateHello(google.New(google.WithAPIKey("test-key"), google.WithBaseURL(srv.URL))); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(key)
}
Output:
test-key

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL replaces the endpoint root. In Vertex mode it must include /projects/{project}/locations/{location}.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"

	"github.com/minodevss/ai-go"
	"github.com/minodevss/ai-go/google"
)

const exampleReply = `{"candidates":[{"content":{"role":"model","parts":[{"text":"Hello from Gemini."}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":9,"thoughtsTokenCount":4,"candidatesTokenCount":6},"responseId":"resp-1"}`

func generateHello(p *google.Provider) error {
	_, err := ai.GenerateText(context.Background(), p.Model("gemini-3-flash"), ai.TextRequest{Messages: []ai.Message{ai.User("hi")}})
	return err
}

func main() {
	var path string
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		path = r.URL.Path
		w.Header().Set("Content-Type", "application/json")
		_, _ = io.WriteString(w, exampleReply)
	}))
	defer srv.Close()

	if err := generateHello(google.New(google.WithBaseURL(srv.URL + "/proxy"))); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(path)
}
Output:
/proxy/models/gemini-3-flash:generateContent

func WithHTTPClient

func WithHTTPClient(c *http.Client) Option
Example
var used bool
client := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
	used = true
	rec := httptest.NewRecorder()
	rec.Header().Set("Content-Type", "application/json")
	_, _ = io.WriteString(rec, exampleReply)
	return rec.Result(), nil
})}

if err := generateHello(google.New(google.WithHTTPClient(client))); err != nil {
	fmt.Println(err)
	return
}
fmt.Println(used)
Output:
true

func WithHeaders

func WithHeaders(h http.Header) Option
Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"

	"github.com/minodevss/ai-go"
	"github.com/minodevss/ai-go/google"
)

const exampleReply = `{"candidates":[{"content":{"role":"model","parts":[{"text":"Hello from Gemini."}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":9,"thoughtsTokenCount":4,"candidatesTokenCount":6},"responseId":"resp-1"}`

func headerServer(header string, got *string) *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		*got = r.Header.Get(header)
		w.Header().Set("Content-Type", "application/json")
		_, _ = io.WriteString(w, exampleReply)
	}))
}

func generateHello(p *google.Provider) error {
	_, err := ai.GenerateText(context.Background(), p.Model("gemini-3-flash"), ai.TextRequest{Messages: []ai.Message{ai.User("hi")}})
	return err
}

func main() {
	var team string
	srv := headerServer("X-Team", &team)
	defer srv.Close()

	if err := generateHello(google.New(google.WithBaseURL(srv.URL), google.WithHeaders(http.Header{"X-Team": {"support"}}))); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(team)
}
Output:
support

func WithLimiter

func WithLimiter(l ai.Limiter) Option

WithLimiter makes every request of the provider wait on l first.

Example
var key string
srv := headerServer("x-goog-api-key", &key)
defer srv.Close()
limiter := &countingLimiter{}

if err := generateHello(google.New(google.WithBaseURL(srv.URL), google.WithLimiter(limiter))); err != nil {
	fmt.Println(err)
	return
}
fmt.Println(limiter.n)
Output:
1

func WithTokenSource

func WithTokenSource(ts TokenSource) Option

WithTokenSource sets the bearer token source of a Vertex provider. The default is DefaultTokenSource.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"

	"github.com/minodevss/ai-go"
	"github.com/minodevss/ai-go/google"
)

const exampleReply = `{"candidates":[{"content":{"role":"model","parts":[{"text":"Hello from Gemini."}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":9,"thoughtsTokenCount":4,"candidatesTokenCount":6},"responseId":"resp-1"}`

func headerServer(header string, got *string) *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		*got = r.Header.Get(header)
		w.Header().Set("Content-Type", "application/json")
		_, _ = io.WriteString(w, exampleReply)
	}))
}

func generateHello(p *google.Provider) error {
	_, err := ai.GenerateText(context.Background(), p.Model("gemini-3-flash"), ai.TextRequest{Messages: []ai.Message{ai.User("hi")}})
	return err
}

func main() {
	var auth string
	srv := headerServer("Authorization", &auth)
	defer srv.Close()

	p := google.New(
		google.WithVertex("my-project", "global"),
		google.WithBaseURL(srv.URL),
		google.WithTokenSource(func(context.Context) (string, error) { return "ya29.example", nil }),
	)
	if err := generateHello(p); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(auth)
}
Output:
Bearer ya29.example

func WithVertex

func WithVertex(project, location string) Option

WithVertex switches the provider to Vertex AI. Empty arguments fall back to GOOGLE_CLOUD_PROJECT, GOOGLE_CLOUD_LOCATION and "global".

Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"

	"github.com/minodevss/ai-go"
	"github.com/minodevss/ai-go/google"
)

func exampleServer(responses map[string]string) *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = io.WriteString(w, responses[r.URL.Path])
	}))
}

const exampleReply = `{"candidates":[{"content":{"role":"model","parts":[{"text":"Hello from Gemini."}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":9,"thoughtsTokenCount":4,"candidatesTokenCount":6},"responseId":"resp-1"}`

func main() {
	srv := exampleServer(map[string]string{"/v1/projects/my-project/locations/us-central1/publishers/google/models/gemini-3-flash:generateContent": exampleReply})
	defer srv.Close()

	p := google.New(
		google.WithVertex("my-project", "us-central1"),
		google.WithBaseURL(srv.URL+"/v1/projects/my-project/locations/us-central1"),
		google.WithTokenSource(func(context.Context) (string, error) { return "ya29.example", nil }),
	)
	res, err := ai.GenerateText(context.Background(), p.Model("gemini-3-flash"), ai.TextRequest{
		Messages: []ai.Message{ai.User("Say hello.")},
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(res.Text)
}
Output:
Hello from Gemini.

type Options

type Options struct {
	ThinkingBudget            *int              `json:"thinkingBudget,omitzero"`
	ThinkingLevel             string            `json:"thinkingLevel,omitzero"`
	IncludeThoughts           *bool             `json:"includeThoughts,omitzero"`
	SafetySettings            []SafetySetting   `json:"safetySettings,omitzero"`
	CachedContent             string            `json:"cachedContent,omitzero"`
	ResponseModalities        []string          `json:"responseModalities,omitzero"`
	Labels                    map[string]string `json:"labels,omitzero"`
	ServiceTier               string            `json:"serviceTier,omitzero"`
	ServerSideToolInvocations bool              `json:"serverSideToolInvocations,omitzero"`
	OpenAPISchemas            bool              `json:"openApiSchemas,omitzero"`
}

Options are Gemini request settings passed with ai.Providers under "google", also on Vertex. ThinkingBudget and ThinkingLevel override ai.TextRequest.Reasoning and exclude each other.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"

	"github.com/minodevss/ai-go"
	"github.com/minodevss/ai-go/google"
)

func exampleServer(responses map[string]string) *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = io.WriteString(w, responses[r.URL.Path])
	}))
}

const exampleReply = `{"candidates":[{"content":{"role":"model","parts":[{"text":"Hello from Gemini."}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":9,"thoughtsTokenCount":4,"candidatesTokenCount":6},"responseId":"resp-1"}`

func main() {
	srv := exampleServer(map[string]string{"/v1beta/models/gemini-3-flash:generateContent": exampleReply})
	defer srv.Close()
	model := google.New(google.WithAPIKey("test-key"), google.WithBaseURL(srv.URL+"/v1beta")).Model("gemini-3-flash")

	res, err := ai.GenerateText(context.Background(), model, ai.TextRequest{
		Messages:  []ai.Message{ai.User("Think, then answer.")},
		Reasoning: ai.ReasoningLow,
		Provider: ai.Providers(google.Options{
			SafetySettings: []google.SafetySetting{{Category: "HARM_CATEGORY_HARASSMENT", Threshold: "BLOCK_ONLY_HIGH"}},
			Labels:         map[string]string{"team": "support"},
		}),
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	data, _ := ai.ProviderValue[google.ResponseData](res.Provider, "google")
	fmt.Println(data.ResponseID)
}
Output:
resp-1

func (Options) ProviderName

func (Options) ProviderName() string

type Provider

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

Provider is safe for concurrent use and builds models that share one HTTP client and one rate limiter. Request options always use the key "google"; replay data uses "google" on AI Studio and "google-vertex" on Vertex.

func New

func New(opts ...Option) *Provider

New reads GEMINI_API_KEY, then GOOGLE_API_KEY, and GOOGLE_GEMINI_BASE_URL as defaults.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"

	"github.com/minodevss/ai-go"
	"github.com/minodevss/ai-go/google"
)

func exampleServer(responses map[string]string) *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = io.WriteString(w, responses[r.URL.Path])
	}))
}

const exampleReply = `{"candidates":[{"content":{"role":"model","parts":[{"text":"Hello from Gemini."}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":9,"thoughtsTokenCount":4,"candidatesTokenCount":6},"responseId":"resp-1"}`

func main() {
	srv := exampleServer(map[string]string{"/v1beta/models/gemini-3-flash:generateContent": exampleReply})
	defer srv.Close()

	p := google.New(google.WithAPIKey("test-key"), google.WithBaseURL(srv.URL+"/v1beta"))
	res, err := ai.GenerateText(context.Background(), p.Model("gemini-3-flash"), ai.TextRequest{
		Messages: []ai.Message{ai.User("Say hello.")},
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(res.Text)
	fmt.Println(res.Usage.Input, res.Usage.Output, res.Usage.Reasoning)
}
Output:
Hello from Gemini.
9 10 4

func (*Provider) DeleteFile

func (p *Provider) DeleteFile(ctx context.Context, id string) error
Example
p, stop := filesExampleProvider(map[string]string{"DELETE /v1beta/files/abc-123": `{}`})
defer stop()

fmt.Println(ai.DeleteFile(context.Background(), p, "abc-123"))
Output:
<nil>

func (*Provider) EmbeddingModel

func (p *Provider) EmbeddingModel(id string) *EmbeddingModel
Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"

	"github.com/minodevss/ai-go"
	"github.com/minodevss/ai-go/google"
)

func exampleServer(responses map[string]string) *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = io.WriteString(w, responses[r.URL.Path])
	}))
}

func main() {
	srv := exampleServer(map[string]string{"/v1beta/models/gemini-embedding-001:batchEmbedContents": `{"embeddings":[{"values":[0.25,0.5]},{"values":[0.75,1]}]}`})
	defer srv.Close()
	p := google.New(google.WithAPIKey("test-key"), google.WithBaseURL(srv.URL+"/v1beta"))

	res, err := ai.Embed(context.Background(), p.EmbeddingModel("gemini-embedding-001"), ai.EmbedRequest{
		Texts:     []string{"first", "second"},
		InputType: ai.InputDocument,
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(len(res.Embeddings), res.Embeddings[1])
}
Output:
2 [0.75 1]

func (*Provider) GetFile

func (p *Provider) GetFile(ctx context.Context, id string) (*ai.File, error)
Example
p, stop := filesExampleProvider(map[string]string{"GET /v1beta/files/abc-123": `{"name":"files/abc-123","displayName":"notes.txt","mimeType":"text/plain","state":"ACTIVE"}`})
defer stop()

f, err := ai.GetFile(context.Background(), p, "abc-123")
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(f.Filename, f.MediaType)
Output:
notes.txt text/plain

func (*Provider) ImageModel

func (p *Provider) ImageModel(id string) *ImageModel
Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"

	"github.com/minodevss/ai-go"
	"github.com/minodevss/ai-go/google"
)

func mediaServer(routes map[string]string) *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		body, ok := routes[r.Method+" "+r.URL.Path]
		if !ok {
			w.WriteHeader(http.StatusNotFound)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		_, _ = io.WriteString(w, body)
	}))
}

func main() {
	srv := mediaServer(map[string]string{"POST /v1beta/models/gemini-nano-banana-2.1:generateContent": `{"candidates":[{"content":{"parts":[{"inlineData":{"mimeType":"image/png","data":"aGVsbG8="}}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":5,"candidatesTokenCount":1290}}`})
	defer srv.Close()
	p := google.New(google.WithAPIKey("test-key"), google.WithBaseURL(srv.URL+"/v1beta"))

	res, err := ai.GenerateImage(context.Background(), p.ImageModel("gemini-nano-banana-2.1"), ai.ImageRequest{
		Prompt:      "a paper boat",
		AspectRatio: "16:9",
		Size:        "2K",
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(string(res.Images[0].Data), res.Images[0].MediaType, res.Usage.Output)
}
Output:
hello image/png 1290

func (*Provider) LanguageModel

func (p *Provider) LanguageModel(id string) (ai.LanguageModel, error)
Example
package main

import (
	"fmt"

	"github.com/minodevss/ai-go/google"
)

func main() {
	m, err := google.New(google.WithAPIKey("test-key")).LanguageModel("gemini-3-flash")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(m.ModelID())
}
Output:
gemini-3-flash

func (*Provider) ListFiles

func (p *Provider) ListFiles(ctx context.Context, c *ai.FileListCall) (*ai.FileList, error)
Example
p, stop := filesExampleProvider(map[string]string{"GET /v1beta/files": `{"files":[{"name":"files/abc-123","displayName":"notes.txt","state":"ACTIVE"}]}`})
defer stop()

list, err := ai.ListFiles(context.Background(), p, ai.FileListRequest{})
if err != nil {
	fmt.Println(err)
	return
}
id, _ := google.FileIDOf(list.Files[0])
fmt.Println(id)
Output:
abc-123

func (*Provider) Model

func (p *Provider) Model(id string) *LanguageModel
Example
package main

import (
	"fmt"

	"github.com/minodevss/ai-go/google"
)

func main() {
	m := google.New(google.WithAPIKey("test-key")).Model("gemini-3-flash")
	fmt.Println(m.Provider(), m.ModelID())
}
Output:
google gemini-3-flash

func (*Provider) RealtimeModel

func (p *Provider) RealtimeModel(id string) *RealtimeModel

func (*Provider) SpeechModel

func (p *Provider) SpeechModel(id string) *SpeechModel
Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/minodevss/ai-go"
	"github.com/minodevss/ai-go/google"
)

func mediaServer(routes map[string]string) *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		body, ok := routes[r.Method+" "+r.URL.Path]
		if !ok {
			w.WriteHeader(http.StatusNotFound)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		_, _ = io.WriteString(w, body)
	}))
}

func main() {
	srv := mediaServer(map[string]string{"POST /v1beta/models/gemini-3.8-flash-tts:generateContent": `{"candidates":[{"content":{"parts":[{"inlineData":{"mimeType":"audio/wav","data":"UklGRg=="}}]},"finishReason":"STOP"}]}`})
	defer srv.Close()
	p := google.New(google.WithAPIKey("test-key"), google.WithBaseURL(srv.URL+"/v1beta"))

	res, err := ai.GenerateSpeech(context.Background(), p.SpeechModel("gemini-3.8-flash-tts"), ai.SpeechRequest{
		Text:         "Have a wonderful day!",
		Voice:        "Kore",
		Instructions: "cheerful and friendly",
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(strings.TrimSpace(res.Audio.MediaType), len(res.Audio.Data))
}
Output:
audio/wav 4

func (*Provider) UploadFile

func (p *Provider) UploadFile(ctx context.Context, c *ai.FileUploadCall) (*ai.File, error)
Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/minodevss/ai-go"
	"github.com/minodevss/ai-go/google"
)

func main() {
	var srv *httptest.Server
	srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.URL.Path {
		case "/upload/v1beta/files":
			w.Header().Set("X-Goog-Upload-Url", srv.URL+"/session")
		default:
			w.Header().Set("Content-Type", "application/json")
			_, _ = io.WriteString(w, `{"file":{"name":"files/abc-123","displayName":"notes.txt","mimeType":"text/plain","uri":"https://generativelanguage.googleapis.com/v1beta/files/abc-123","state":"ACTIVE"}}`)
		}
	}))
	defer srv.Close()

	p := google.New(google.WithAPIKey("test-key"), google.WithBaseURL(srv.URL+"/v1beta"))
	f, err := ai.UploadFile(context.Background(), p, ai.FileUpload{Name: "notes.txt", MediaType: "text/plain", Data: strings.NewReader("hello")})
	if err != nil {
		fmt.Println(err)
		return
	}
	id, ok := google.FileIDOf(f)
	fmt.Println(id, ok, f.MediaType)
}
Output:
abc-123 true text/plain

func (*Provider) VideoModel

func (p *Provider) VideoModel(id string) *VideoModel
Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/minodevss/ai-go"
	"github.com/minodevss/ai-go/google"
)

func mediaServer(routes map[string]string) *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		body, ok := routes[r.Method+" "+r.URL.Path]
		if !ok {
			w.WriteHeader(http.StatusNotFound)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		_, _ = io.WriteString(w, body)
	}))
}

func main() {
	srv := mediaServer(map[string]string{
		"POST /v1beta/interactions":       `{"id":"v1_abc","status":"in_progress"}`,
		"GET /v1beta/interactions/v1_abc": `{"id":"v1_abc","status":"completed","steps":[{"type":"model_output","content":[{"type":"video","mime_type":"video/mp4","data":"bXA0"}]}]}`,
	})
	defer srv.Close()
	p := google.New(google.WithAPIKey("test-key"), google.WithBaseURL(srv.URL+"/v1beta"))

	res, err := ai.GenerateVideo(context.Background(), p.VideoModel("gemini-omni-1.2-flash"), ai.VideoRequest{
		Prompt:       "a fox in snow",
		Duration:     5 * time.Second,
		PollInterval: time.Millisecond,
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(res.ID, string(res.Videos[0].Data))
}
Output:
v1_abc mp4

type RealtimeModel

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

RealtimeModel talks to the Live API on AI Studio over a WebSocket. Vertex AI sessions are not supported.

func NewRealtimeModel

func NewRealtimeModel(id string) *RealtimeModel
Example
package main

import (
	"fmt"

	"github.com/minodevss/ai-go/google"
)

func main() {
	fmt.Println(google.NewRealtimeModel("gemini-3.8-live").ModelID())
}
Output:
gemini-3.8-live

func (*RealtimeModel) Connect

func (m *RealtimeModel) Connect(ctx context.Context, c *realtime.Config) (realtime.Conn, error)
Example
package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/coder/websocket"

	"github.com/minodevss/ai-go"
	"github.com/minodevss/ai-go/google"
	"github.com/minodevss/ai-go/realtime"
)

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		c, err := websocket.Accept(w, r, nil)
		if err != nil {
			return
		}
		defer c.CloseNow() //nolint:errcheck // the example server ends with the connection
		ctx := r.Context()
		if _, _, err := c.Read(ctx); err != nil {
			return
		}
		for _, msg := range []string{
			`{"setupComplete":{}}`,
			`{"serverContent":{"modelTurn":{"parts":[{"text":"Hi there"}]}}}`,
			`{"serverContent":{"turnComplete":true}}`,
		} {
			if err := c.Write(ctx, websocket.MessageText, []byte(msg)); err != nil {
				return
			}
		}
		c.Read(ctx) //nolint:errcheck // waits for the client to close
	}))
	defer srv.Close()
	p := google.New(google.WithAPIKey("key"), google.WithBaseURL(srv.URL+"/v1beta"))

	ctx := context.Background()
	sess, err := realtime.Connect(ctx, p.RealtimeModel("gemini-3.8-live"), realtime.Config{
		Instructions: "Answer in one sentence.",
		Provider:     ai.Providers(google.RealtimeOptions{ResponseModalities: []string{"TEXT"}}),
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	defer sess.Close()
	for ev := range sess.Events() {
		switch ev := ev.(type) {
		case realtime.TextDelta:
			fmt.Println(ev.Text)
		case realtime.TurnEnd:
			return
		}
	}
}
Output:
Hi there

func (*RealtimeModel) MintClientSecret

MintClientSecret creates an ephemeral token that starts one session within o.TTL, locked to this model and the settings of c.

Example
srv := exampleServer(map[string]string{"/v1beta/auth_tokens": `{"name":"auth_tokens/abc123"}`})
defer srv.Close()
p := google.New(google.WithAPIKey("key"), google.WithBaseURL(srv.URL+"/v1beta"))

cfg := realtime.Config{Instructions: "Greet the visitor.", Voice: "Kore"}
secret, err := realtime.MintClientSecret(context.Background(), p.RealtimeModel("gemini-3.8-live"), cfg, realtime.MintOptions{TTL: time.Minute})
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(secret.Value, secret.Locked)
Output:
auth_tokens/abc123 true

func (*RealtimeModel) ModelID

func (m *RealtimeModel) ModelID() string

func (*RealtimeModel) Provider

func (m *RealtimeModel) Provider() string

type RealtimeOptions

type RealtimeOptions struct {
	ResponseModalities       []string `json:"responseModalities,omitzero"`
	DisableTranscription     bool     `json:"disableTranscription,omitzero"`
	ContextWindowCompression bool     `json:"contextWindowCompression,omitzero"`
}

RealtimeOptions are Live API session settings passed in realtime.Config.Provider with ai.Providers. ResponseModalities defaults to AUDIO and ContextWindowCompression lifts the 15 minute limit of audio sessions.

Example
package main

import (
	"fmt"

	"github.com/minodevss/ai-go"
	"github.com/minodevss/ai-go/google"
)

func main() {
	p := ai.Providers(google.RealtimeOptions{ResponseModalities: []string{"TEXT"}})
	_, ok := p["google"]
	fmt.Println(ok)
}
Output:
true

func (RealtimeOptions) ProviderName

func (RealtimeOptions) ProviderName() string

type ResponseData

type ResponseData struct {
	ResponseID         string          `json:"responseId,omitzero"`
	ModelVersion       string          `json:"modelVersion,omitzero"`
	FinishMessage      string          `json:"finishMessage,omitzero"`
	GroundingMetadata  json.RawMessage `json:"groundingMetadata,omitzero"`
	URLContextMetadata json.RawMessage `json:"urlContextMetadata,omitzero"`
	CitationMetadata   json.RawMessage `json:"citationMetadata,omitzero"`
	SafetyRatings      json.RawMessage `json:"safetyRatings,omitzero"`
	PromptFeedback     json.RawMessage `json:"promptFeedback,omitzero"`
}

ResponseData is stored in Response.Provider under "google" (AI Studio) or "google-vertex". The metadata fields hold the API objects as received; streamed fragments are merged.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"

	"github.com/minodevss/ai-go"
	"github.com/minodevss/ai-go/google"
)

func exampleServer(responses map[string]string) *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = io.WriteString(w, responses[r.URL.Path])
	}))
}

const exampleReply = `{"candidates":[{"content":{"role":"model","parts":[{"text":"Hello from Gemini."}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":9,"thoughtsTokenCount":4,"candidatesTokenCount":6},"responseId":"resp-1"}`

func main() {
	srv := exampleServer(map[string]string{"/v1beta/models/gemini-3-flash:generateContent": exampleReply})
	defer srv.Close()
	p := google.New(google.WithAPIKey("test-key"), google.WithBaseURL(srv.URL+"/v1beta"))

	res, err := ai.GenerateText(context.Background(), p.Model("gemini-3-flash"), ai.TextRequest{Messages: []ai.Message{ai.User("hi")}})
	if err != nil {
		fmt.Println(err)
		return
	}
	data, ok := ai.ProviderValue[google.ResponseData](res.Provider, "google")
	fmt.Println(data.ResponseID, ok)
}
Output:
resp-1 true

type SafetySetting

type SafetySetting struct {
	Category  string `json:"category"`
	Threshold string `json:"threshold"`
}

type SpeechModel

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

SpeechModel synthesizes speech with a Gemini TTS model. Voice defaults to "Kore" and Format to "wav"; "pcm", "mulaw" and "alaw" need a Gemini 3.8 model.

func NewSpeechModel

func NewSpeechModel(id string) *SpeechModel
Example
package main

import (
	"fmt"

	"github.com/minodevss/ai-go/google"
)

func main() {
	fmt.Println(google.NewSpeechModel("gemini-3.8-flash-tts").ModelID())
}
Output:
gemini-3.8-flash-tts

func (*SpeechModel) GenerateSpeech

func (m *SpeechModel) GenerateSpeech(ctx context.Context, c *ai.SpeechCall) (*ai.SpeechResponse, error)

func (*SpeechModel) ModelID

func (m *SpeechModel) ModelID() string

func (*SpeechModel) Provider

func (m *SpeechModel) Provider() string

type SpeechOptions

type SpeechOptions struct {
	Speakers   []SpeechSpeaker `json:"speakers,omitzero"`
	Turns      []SpeechTurn    `json:"turns,omitzero"`
	SampleRate int             `json:"sampleRate,omitzero"`
}

SpeechOptions are speech settings passed with ai.Providers under "google". Turns needs up to two Speakers and replaces the call's Text, which must still be set; SampleRate applies to Gemini 3.8 models.

Example
package main

import (
	"fmt"

	"github.com/minodevss/ai-go"
	"github.com/minodevss/ai-go/google"
)

func main() {
	p := ai.Providers(google.SpeechOptions{SampleRate: 24000})
	_, ok := p["google"]
	fmt.Println(ok)
}
Output:
true

func (SpeechOptions) ProviderName

func (SpeechOptions) ProviderName() string

type SpeechSpeaker

type SpeechSpeaker struct {
	Name  string `json:"name"`
	Voice string `json:"voice"`
}

type SpeechTurn

type SpeechTurn struct {
	Speaker string `json:"speaker"`
	Text    string `json:"text"`
	Style   string `json:"style,omitzero"`
}

type TokenSource

type TokenSource func(ctx context.Context) (string, error)

TokenSource returns a current OAuth 2.0 access token and must be safe for concurrent use.

func DefaultTokenSource

func DefaultTokenSource(c *http.Client) TokenSource

DefaultTokenSource uses the key file named by GOOGLE_APPLICATION_CREDENTIALS, or else the metadata server.

Example
package main

import (
	"fmt"

	"github.com/minodevss/ai-go/google"
)

func main() {
	ts := google.DefaultTokenSource(nil)
	p := google.New(google.WithVertex("my-project", "global"), google.WithTokenSource(ts))
	fmt.Println(p.Model("gemini-3-flash").Provider())
}
Output:
google-vertex

func MetadataTokenSource

func MetadataTokenSource(c *http.Client) TokenSource

MetadataTokenSource fetches tokens from the Google Cloud metadata server; GCE_METADATA_HOST overrides its host.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"os"

	"github.com/minodevss/ai-go/google"
)

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		_, _ = io.WriteString(w, `{"access_token":"ya29.meta","expires_in":3600,"token_type":"Bearer"}`)
	}))
	defer srv.Close()
	if err := os.Setenv("GCE_METADATA_HOST", srv.Listener.Addr().String()); err != nil {
		fmt.Println(err)
		return
	}
	defer os.Unsetenv("GCE_METADATA_HOST")

	token, err := google.MetadataTokenSource(nil)(context.Background())
	fmt.Println(token, err)
}
Output:
ya29.meta <nil>

func ServiceAccountTokenSource

func ServiceAccountTokenSource(keyJSON []byte, c *http.Client) (TokenSource, error)

ServiceAccountTokenSource exchanges a JWT signed with a service account key for access tokens.

Example
package main

import (
	"fmt"

	"github.com/minodevss/ai-go/google"
)

func main() {
	_, err := google.ServiceAccountTokenSource([]byte(`{"type":"authorized_user"}`), nil)
	fmt.Println(err)
}
Output:
google: credentials of type "authorized_user" are not supported, want service_account

type VideoModel

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

VideoModel generates videos as long-running jobs: Veo on Vertex and Gemini Omni on AI Studio.

func NewVideoModel

func NewVideoModel(id string) *VideoModel
Example
package main

import (
	"fmt"

	"github.com/minodevss/ai-go/google"
)

func main() {
	fmt.Println(google.NewVideoModel("gemini-omni-1.2-flash").ModelID())
}
Output:
gemini-omni-1.2-flash

func (*VideoModel) ModelID

func (m *VideoModel) ModelID() string

func (*VideoModel) PollVideo

func (m *VideoModel) PollVideo(ctx context.Context, job *ai.VideoJob) (*ai.VideoPoll, error)

func (*VideoModel) Provider

func (m *VideoModel) Provider() string

func (*VideoModel) StartVideo

func (m *VideoModel) StartVideo(ctx context.Context, c *ai.VideoCall) (*ai.VideoJob, error)

type VideoOptions

type VideoOptions struct {
	StorageURI       string `json:"storageUri,omitzero"`
	NegativePrompt   string `json:"negativePrompt,omitzero"`
	PersonGeneration string `json:"personGeneration,omitzero"`
	Resolution       string `json:"resolution,omitzero"`
	GenerateAudio    *bool  `json:"generateAudio,omitzero"`
	SampleCount      int    `json:"sampleCount,omitzero"`
	ReferenceImages  bool   `json:"referenceImages,omitzero"`
}

VideoOptions are video settings passed with ai.Providers under "google" and apply to Veo on Vertex. ReferenceImages sends the call's Files as asset references instead of first and last frames.

Example
package main

import (
	"fmt"

	"github.com/minodevss/ai-go"
	"github.com/minodevss/ai-go/google"
)

func main() {
	p := ai.Providers(google.VideoOptions{ReferenceImages: true})
	_, ok := p["google"]
	fmt.Println(ok)
}
Output:
true

func (VideoOptions) ProviderName

func (VideoOptions) ProviderName() string

Jump to

Keyboard shortcuts

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