gemini

package
v1.0.21 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2025 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package gemini provides extension implementation for Google Gemini AI provider. It handles conversion between standard and provider-specific request/response formats.

Package gemini provides a Google Gemini AI provider implementation. It includes support for chat completions, streaming, tool calling, and OAuth authentication.

Package gemini provides type definitions for Google Gemini AI provider. It includes request/response structures, streaming types, and function calling definitions.

Index

Constants

View Source
const (
	UserTierIDFree     = "free-tier"
	UserTierIDLegacy   = "legacy-tier"
	UserTierIDStandard = "standard-tier"
)

Constants for user tiers

View Source
const (
	IDETypeUnspecified  = "IDE_UNSPECIFIED"
	PlatformUnspecified = "PLATFORM_UNSPECIFIED"
	PluginTypeGemini    = "GEMINI"
)

Constants for client metadata

Variables

This section is empty.

Functions

func CreateGeminiProvider

func CreateGeminiProvider(config types.ProviderConfig) (types.Provider, error)

CreateGeminiProvider creates a new Gemini provider instance

func IsProjectIDRequired

func IsProjectIDRequired(err error) bool

IsProjectIDRequired checks if an error is a ProjectIDRequiredError

func RegisterGeminiFactory

func RegisterGeminiFactory(factory types.ProviderFactory)

RegisterGeminiFactory registers the Gemini provider with the factory

Types

type Candidate

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

Candidate represents a response candidate

type ClientMetadata

type ClientMetadata struct {
	IDEType       string `json:"ideType,omitempty"`
	IDEVersion    string `json:"ideVersion,omitempty"`
	PluginVersion string `json:"pluginVersion,omitempty"`
	Platform      string `json:"platform,omitempty"`
	UpdateChannel string `json:"updateChannel,omitempty"`
	DuetProject   string `json:"duetProject,omitempty"`
	PluginType    string `json:"pluginType,omitempty"`
	IDEName       string `json:"ideName,omitempty"`
}

ClientMetadata represents client metadata for onboarding

type CloudCodeRequestWrapper

type CloudCodeRequestWrapper struct {
	Model        string                 `json:"model"`
	Project      string                 `json:"project,omitempty"`
	UserPromptID string                 `json:"user_prompt_id,omitempty"`
	Request      GenerateContentRequest `json:"request"`
}

CloudCodeRequestWrapper wraps requests for CloudCode API

type CloudCodeResponseWrapper

type CloudCodeResponseWrapper struct {
	Response GenerateContentResponse `json:"response"`
}

CloudCodeResponseWrapper wraps responses from CloudCode API

type CloudaicompanionProject

type CloudaicompanionProject struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

CloudaicompanionProject represents a Cloud AI companion project

type Content

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

Content represents message content

type FileData added in v1.0.13

type FileData struct {
	MimeType string `json:"mimeType"`
	FileURI  string `json:"fileUri"`
}

FileData represents file data (URL/GCS URI)

type FunctionResponse added in v1.0.13

type FunctionResponse struct {
	Name     string                 `json:"name"`
	Response map[string]interface{} `json:"response"`
}

FunctionResponse represents a response to a function call

type GeminiConfig

type GeminiConfig struct {
	// Basic configuration
	APIKey      string   `json:"api_key"`
	APIKeys     []string `json:"api_keys,omitempty"`
	BaseURL     string   `json:"base_url,omitempty"`
	Model       string   `json:"model,omitempty"`
	DisplayName string   `json:"display_name,omitempty"`

	// Cloud Code API project ID
	ProjectID string `json:"project_id,omitempty"`
}

GeminiConfig represents Gemini-specific configuration

type GeminiExtension

type GeminiExtension struct {
	*types.BaseExtension
}

GeminiExtension implements CoreProviderExtension for Google Gemini

func NewGeminiExtension

func NewGeminiExtension() *GeminiExtension

NewGeminiExtension creates a new Gemini extension

func (*GeminiExtension) ProviderToStandard

func (e *GeminiExtension) ProviderToStandard(response interface{}) (*types.StandardResponse, error)

ProviderToStandard converts a Gemini response to standard format

func (*GeminiExtension) ProviderToStandardChunk

func (e *GeminiExtension) ProviderToStandardChunk(chunk interface{}) (*types.StandardStreamChunk, error)

ProviderToStandardChunk converts a Gemini stream chunk to standard format

func (*GeminiExtension) StandardToProvider

func (e *GeminiExtension) StandardToProvider(request types.StandardRequest) (interface{}, error)

StandardToProvider converts a standard request to Gemini format

func (*GeminiExtension) ValidateOptions

func (e *GeminiExtension) ValidateOptions(options map[string]interface{}) error

ValidateOptions validates Gemini-specific options

type GeminiFunctionCall

type GeminiFunctionCall struct {
	Name string                 `json:"name"`
	Args map[string]interface{} `json:"args"`
}

GeminiFunctionCall represents a function call from the model

type GeminiFunctionDeclaration

type GeminiFunctionDeclaration struct {
	Name        string       `json:"name"`
	Description string       `json:"description"`
	Parameters  GeminiSchema `json:"parameters"`
}

GeminiFunctionDeclaration represents a function declaration in Gemini format

type GeminiModelData

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

GeminiModelData represents a model in the models list

type GeminiModelsResponse

type GeminiModelsResponse struct {
	Models        []GeminiModelData `json:"models"`
	NextPageToken string            `json:"nextPageToken,omitempty"`
}

GeminiModelsResponse represents the response from /v1beta/models endpoint

type GeminiProperty

type GeminiProperty struct {
	Type        string   `json:"type"`
	Description string   `json:"description,omitempty"`
	Enum        []string `json:"enum,omitempty"`
}

GeminiProperty represents a property in the schema

type GeminiProvider

type GeminiProvider struct {
	*base.BaseProvider
	// contains filtered or unexported fields
}

GeminiProvider implements the Provider interface for Google Gemini with OAuth support

func NewGeminiProvider

func NewGeminiProvider(config types.ProviderConfig) *GeminiProvider

NewGeminiProvider creates a new Gemini provider

func (*GeminiProvider) Authenticate

func (p *GeminiProvider) Authenticate(ctx context.Context, authConfig types.AuthConfig) error

func (*GeminiProvider) Configure

func (p *GeminiProvider) Configure(config types.ProviderConfig) error

func (*GeminiProvider) Description

func (p *GeminiProvider) Description() string

func (*GeminiProvider) GenerateChatCompletion

func (p *GeminiProvider) GenerateChatCompletion(
	ctx context.Context,
	options types.GenerateOptions,
) (types.ChatCompletionStream, error)

GenerateChatCompletion generates a chat completion with OAuth/API key support

func (*GeminiProvider) GetAuthStatus

func (p *GeminiProvider) GetAuthStatus() map[string]interface{}

GetAuthStatus provides detailed authentication status using shared helper

func (*GeminiProvider) GetAuthURL added in v1.0.14

func (p *GeminiProvider) GetAuthURL(redirectURI string, state string) string

GetAuthURL generates an OAuth authorization URL for re-authentication

func (*GeminiProvider) GetDefaultModel

func (p *GeminiProvider) GetDefaultModel() string

func (*GeminiProvider) GetModels

func (p *GeminiProvider) GetModels(ctx context.Context) ([]types.Model, error)

func (*GeminiProvider) GetToolFormat

func (p *GeminiProvider) GetToolFormat() types.ToolFormat

func (*GeminiProvider) InvokeServerTool

func (p *GeminiProvider) InvokeServerTool(
	ctx context.Context,
	toolName string,
	params interface{},
) (interface{}, error)

func (*GeminiProvider) IsAPIKeyConfigured added in v1.0.17

func (p *GeminiProvider) IsAPIKeyConfigured() bool

IsAPIKeyConfigured checks if API key authentication is properly configured

func (*GeminiProvider) IsAuthenticated

func (p *GeminiProvider) IsAuthenticated() bool

func (*GeminiProvider) IsOAuthConfigured added in v1.0.17

func (p *GeminiProvider) IsOAuthConfigured() bool

IsOAuthConfigured checks if OAuth authentication is properly configured

func (*GeminiProvider) Logout

func (p *GeminiProvider) Logout(ctx context.Context) error

func (*GeminiProvider) Name

func (p *GeminiProvider) Name() string

func (*GeminiProvider) RefreshAllOAuthTokens

func (p *GeminiProvider) RefreshAllOAuthTokens(ctx context.Context) error

RefreshAllOAuthTokens using shared helper

func (*GeminiProvider) RefreshToken added in v1.0.14

func (p *GeminiProvider) RefreshToken(ctx context.Context) error

RefreshToken refreshes the OAuth token using the stored refresh token

func (*GeminiProvider) SetupUserProject

func (p *GeminiProvider) SetupUserProject(ctx context.Context) (string, error)

SetupUserProject performs the full onboarding flow and returns the Google Cloud project ID that the user belongs to. It will create a new project for the user if necessary and poll for the long‑running onboard operation to finish.

The method is analogous to the TypeScript implementation in llxprt-code/packages/core/src/code_assist/setup.ts.

func (*GeminiProvider) SupportsResponsesAPI

func (p *GeminiProvider) SupportsResponsesAPI() bool

func (*GeminiProvider) SupportsStreaming

func (p *GeminiProvider) SupportsStreaming() bool

func (*GeminiProvider) SupportsToolCalling

func (p *GeminiProvider) SupportsToolCalling() bool

func (*GeminiProvider) TestConnectivity added in v1.0.17

func (p *GeminiProvider) TestConnectivity(ctx context.Context) error

TestConnectivity performs a lightweight connectivity test to verify the provider can reach its service

func (*GeminiProvider) Type

func (p *GeminiProvider) Type() types.ProviderType

func (*GeminiProvider) UpdateRateLimitTier

func (p *GeminiProvider) UpdateRateLimitTier(requestsPerMinute int)

UpdateRateLimitTier adjusts client-side rate limits based on API tier. This allows users to configure their tier manually since Gemini doesn't provide rate limit headers in responses.

Common tiers:

  • Free tier: 15 RPM
  • Pay-as-you-go: 360 RPM

Parameters:

  • requestsPerMinute: The maximum number of requests allowed per minute for your tier

Example usage:

provider.UpdateRateLimitTier(360) // Pay-as-you-go tier

func (*GeminiProvider) ValidateToken added in v1.0.14

func (p *GeminiProvider) ValidateToken(ctx context.Context) (*types.TokenInfo, error)

ValidateToken validates the current OAuth token and returns detailed token information

type GeminiSchema

type GeminiSchema struct {
	Type       string                    `json:"type"`
	Properties map[string]GeminiProperty `json:"properties,omitempty"`
	Required   []string                  `json:"required,omitempty"`
}

GeminiSchema represents the schema for function parameters

type GeminiStream

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

GeminiStream implements ChatCompletionStream for real streaming responses

func (*GeminiStream) Close

func (s *GeminiStream) Close() error

func (*GeminiStream) Next

type GeminiStreamResponse

type GeminiStreamResponse struct {
	Candidates    []Candidate    `json:"candidates,omitempty"`
	UsageMetadata *UsageMetadata `json:"usageMetadata,omitempty"`
}

GeminiStreamResponse represents a streaming response chunk

type GeminiTool

type GeminiTool struct {
	FunctionDeclarations []GeminiFunctionDeclaration `json:"function_declarations"`
}

GeminiTool represents a tool available to the model

type GeminiUserTier

type GeminiUserTier struct {
	ID                                 string         `json:"id"`
	Name                               string         `json:"name"`
	Description                        string         `json:"description"`
	UserDefinedCloudaicompanionProject *bool          `json:"userDefinedCloudaicompanionProject,omitempty"`
	IsDefault                          *bool          `json:"isDefault,omitempty"`
	PrivacyNotice                      *PrivacyNotice `json:"privacyNotice,omitempty"`
	HasAcceptedTos                     *bool          `json:"hasAcceptedTos,omitempty"`
	HasOnboardedPreviously             *bool          `json:"hasOnboardedPreviously,omitempty"`
}

GeminiUserTier represents a user tier for Gemini

type GenerateContentRequest

type GenerateContentRequest struct {
	Contents         []Content         `json:"contents"`
	GenerationConfig *GenerationConfig `json:"generationConfig,omitempty"`
	Tools            []GeminiTool      `json:"tools,omitempty"`
}

GenerateContentRequest represents a request to generate content

type GenerateContentResponse

type GenerateContentResponse struct {
	Candidates    []Candidate    `json:"candidates"`
	UsageMetadata *UsageMetadata `json:"usageMetadata,omitempty"`
}

GenerateContentResponse represents a response from generate content

type GenerationConfig

type GenerationConfig struct {
	Temperature     float64 `json:"temperature,omitempty"`
	TopP            float64 `json:"topP,omitempty"`
	TopK            int     `json:"topK,omitempty"`
	MaxOutputTokens int     `json:"maxOutputTokens,omitempty"`
}

GenerationConfig represents generation configuration

type IneligibleTier

type IneligibleTier struct {
	ReasonCode    string `json:"reasonCode"`
	ReasonMessage string `json:"reasonMessage"`
	TierID        string `json:"tierId"`
	TierName      string `json:"tierName"`
}

IneligibleTier represents an ineligible tier

type InlineData added in v1.0.13

type InlineData struct {
	MimeType string `json:"mimeType"`
	Data     string `json:"data"`
}

InlineData represents inline media data (base64)

type LoadCodeAssistRequest

type LoadCodeAssistRequest struct {
	CloudaicompanionProject *string        `json:"cloudaicompanionProject,omitempty"`
	Metadata                ClientMetadata `json:"metadata"`
}

LoadCodeAssistRequest represents a request to load code assist

type LoadCodeAssistResponse

type LoadCodeAssistResponse struct {
	CurrentTier             *GeminiUserTier  `json:"currentTier,omitempty"`
	AllowedTiers            []GeminiUserTier `json:"allowedTiers,omitempty"`
	IneligibleTiers         []IneligibleTier `json:"ineligibleTiers,omitempty"`
	CloudaicompanionProject *string          `json:"cloudaicompanionProject,omitempty"`
}

LoadCodeAssistResponse represents a response from load code assist

type LongRunningOperationResponse

type LongRunningOperationResponse struct {
	Name     string               `json:"name"`
	Done     bool                 `json:"done"`
	Response *OnboardUserResponse `json:"response,omitempty"`
}

LongRunningOperationResponse represents a long-running operation response

type MockStream

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

MockStream implements ChatCompletionStream for testing

func (*MockStream) Close

func (ms *MockStream) Close() error

func (*MockStream) Next

func (ms *MockStream) Next() (types.ChatCompletionChunk, error)

type OnboardUserRequest

type OnboardUserRequest struct {
	TierID                  *string         `json:"tierId,omitempty"`
	CloudaicompanionProject *string         `json:"cloudaicompanionProject,omitempty"`
	Metadata                *ClientMetadata `json:"metadata,omitempty"`
}

OnboardUserRequest represents a request to onboard a user

type OnboardUserResponse

type OnboardUserResponse struct {
	CloudaicompanionProject *CloudaicompanionProject `json:"cloudaicompanionProject,omitempty"`
}

OnboardUserResponse represents a response from user onboarding

type Part

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

Part represents a part of content

type PrivacyNotice

type PrivacyNotice struct {
	ShowNotice bool    `json:"showNotice"`
	NoticeText *string `json:"noticeText,omitempty"`
}

PrivacyNotice represents a privacy notice

type ProjectIDRequiredError

type ProjectIDRequiredError struct{}

ProjectIDRequiredError is returned when a project ID is needed but not provided

func (*ProjectIDRequiredError) Error

func (e *ProjectIDRequiredError) Error() string

Error returns the error message

type UsageMetadata

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

UsageMetadata represents usage metadata

Jump to

Keyboard shortcuts

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