Documentation
¶
Index ¶
- Constants
- Variables
- func AccountMetaKey(email, modelName string) string
- func AddRoleTag(role, content string, unclose bool) string
- func AliasFromModelID(modelID string) string
- func BuildPrompt(msgs []RoleText, tagged bool, appendAssistant bool) string
- func ChunkByRunes(s string, size int) []string
- func CleanupFiles(paths []string)
- func ConvBoltPath(tokenFilePath string) string
- func ConvertOutputToGemini(output *ModelOutput, modelName string, promptText string) ([]byte, error)
- func EnsureGeminiWebAliasMap()
- func EstimateTotalTokensFromRawJSON(rawJSON []byte) int
- func FetchGeneratedImageData(gi GeneratedImage) (string, string, error)
- func GetGeminiWebAliasedModels() []*registry.ModelInfo
- func LoadConvData(path string) (map[string]ConversationRecord, map[string]string, error)
- func LoadConvStore(path string) (map[string][]string, error)
- func MapAliasToUnderlying(name string) string
- func MaskToken28(s string) string
- func MaterializeInlineFiles(files [][]byte, mimes []string) ([]string, *interfaces.ErrorMessage)
- func MaxCharsPerRequest(cfg *config.Config) int
- func MimeToExt(mimes []string, i int) string
- func MimeToPreferredExt(mime string) string
- func NeedRoleTags(msgs []RoleText) bool
- func NormalizeRole(role string) string
- func RemoveThinkTags(s string) string
- func SaveConvData(path string, items map[string]ConversationRecord, index map[string]string) error
- func SaveConvStore(path string, data map[string][]string) error
- func WithInsecureTLS(insecure bool) func(*GeminiClient)
- type APIError
- type AuthError
- type Candidate
- type ChatSession
- func (cs *ChatSession) CID() string
- func (cs *ChatSession) ChooseCandidate(index int) (ModelOutput, error)
- func (cs *ChatSession) Metadata() []string
- func (cs *ChatSession) RCID() string
- func (cs *ChatSession) RID() string
- func (cs *ChatSession) RequestedModel() string
- func (cs *ChatSession) SendMessage(prompt string, files []string) (ModelOutput, error)
- func (cs *ChatSession) SetMetadata(v []string)
- func (cs *ChatSession) SetRequestedModel(name string)
- func (cs *ChatSession) String() string
- type ConversationRecord
- func BuildConversationRecord(model, clientID string, history []RoleText, output *ModelOutput, ...) (ConversationRecord, bool)
- func FindByMessageListIn(items map[string]ConversationRecord, index map[string]string, ...) (ConversationRecord, bool)
- func FindConversationIn(items map[string]ConversationRecord, index map[string]string, ...) (ConversationRecord, bool)
- func FindReusableSessionIn(items map[string]ConversationRecord, index map[string]string, ...) (ConversationRecord, []string, int, bool)
- type Gem
- type GeminiClient
- func (c *GeminiClient) Close(delaySec float64)
- func (c *GeminiClient) GenerateContent(prompt string, files []string, model Model, gem *Gem, chat *ChatSession) (ModelOutput, error)
- func (c *GeminiClient) Init(timeoutSec float64, verbose bool) error
- func (c *GeminiClient) RotateTS() (string, error)
- func (c *GeminiClient) StartChat(model Model, gem *Gem, metadata []string) *ChatSession
- type GeminiError
- type GeminiWebState
- func (s *GeminiWebState) ConvertStream(ctx context.Context, modelName string, prep *geminiWebPrepared, ...) []string
- func (s *GeminiWebState) ConvertToTarget(ctx context.Context, modelName string, prep *geminiWebPrepared, ...) []byte
- func (s *GeminiWebState) DoneStream(ctx context.Context, modelName string, prep *geminiWebPrepared) []string
- func (s *GeminiWebState) EnsureClient() error
- func (s *GeminiWebState) GetRequestMutex() *sync.Mutex
- func (s *GeminiWebState) Label() string
- func (s *GeminiWebState) Refresh(ctx context.Context) error
- func (s *GeminiWebState) Send(ctx context.Context, modelName string, reqPayload []byte, ...) ([]byte, *interfaces.ErrorMessage, *geminiWebPrepared)
- func (s *GeminiWebState) SetPendingMatch(match *conversation.MatchResult)
- func (s *GeminiWebState) TokenSnapshot() *gemini.GeminiWebTokenStorage
- type GeneratedImage
- type Image
- type ImageGenerationError
- type Model
- type ModelInvalid
- type ModelOutput
- type RoleText
- type StoredMessage
- type TemporarilyBlocked
- type TimeoutError
- type UsageLimitExceeded
- type ValueError
- type WebImage
Constants ¶
const ( EndpointGoogle = "https://www.google.com" EndpointInit = "https://gemini.google.com/app" EndpointGenerate = "https://gemini.google.com/_/BardChatUi/data/assistant.lamda.BardFrontendService/StreamGenerate" EndpointRotateCookies = "https://accounts.google.com/RotateCookies" EndpointUpload = "https://content-push.googleapis.com/upload" )
Gemini web endpoints and default headers ----------------------------------
const ( ErrorUsageLimitExceeded = 1037 ErrorModelInconsistent = 1050 ErrorModelHeaderInvalid = 1052 ErrorIPTemporarilyBlocked = 1060 )
Known error codes returned from the server.
Variables ¶
var ( HeadersGemini = http.Header{ "Content-Type": []string{"application/x-www-form-urlencoded;charset=utf-8"}, "Host": []string{"gemini.google.com"}, "Origin": []string{"https://gemini.google.com"}, "Referer": []string{"https://gemini.google.com/"}, "User-Agent": []string{"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"}, "X-Same-Domain": []string{"1"}, } HeadersRotateCookies = http.Header{ "Content-Type": []string{"application/json"}, } HeadersUpload = http.Header{ "Push-ID": []string{"feeds/mcudyrk2a4khkz"}, } )
var ( ModelUnspecified = Model{ Name: "unspecified", ModelHeader: http.Header{}, AdvancedOnly: false, } ModelG25Flash = Model{ Name: "gemini-2.5-flash", ModelHeader: http.Header{ "x-goog-ext-525001261-jspb": []string{"[1,null,null,null,\"71c2d248d3b102ff\",null,null,0,[4]]"}, }, AdvancedOnly: false, } ModelG25Pro = Model{ Name: "gemini-2.5-pro", ModelHeader: http.Header{ "x-goog-ext-525001261-jspb": []string{"[1,null,null,null,\"4af6c7f5da75d65d\",null,null,0,[4]]"}, }, AdvancedOnly: false, } ModelG20Flash = Model{ Name: "gemini-2.0-flash", ModelHeader: http.Header{ "x-goog-ext-525001261-jspb": []string{"[1,null,null,null,\"f299729663a2343f\"]"}, }, AdvancedOnly: false, } ModelG20FlashThinking = Model{ Name: "gemini-2.0-flash-thinking", ModelHeader: http.Header{ "x-goog-ext-525001261-jspb": []string{"[null,null,null,null,\"7ca48d02d802f20a\"]"}, }, AdvancedOnly: false, } )
var NanoBananaModel = map[string]struct{}{
"gemini-2.5-flash-image-preview": {},
}
Functions ¶
func AccountMetaKey ¶
AccountMetaKey builds the key for account-level metadata map.
func AddRoleTag ¶
AddRoleTag wraps content with a role tag.
func AliasFromModelID ¶
func BuildPrompt ¶
BuildPrompt constructs the final prompt from a list of messages.
func ChunkByRunes ¶
func CleanupFiles ¶
func CleanupFiles(paths []string)
func ConvBoltPath ¶ added in v6.0.4
ConvBoltPath returns the BoltDB file path used for both account metadata and conversation data. Different logical datasets are kept in separate buckets within this single DB file.
func ConvertOutputToGemini ¶
func ConvertOutputToGemini(output *ModelOutput, modelName string, promptText string) ([]byte, error)
ConvertOutputToGemini converts simplified ModelOutput to Gemini API-like JSON. promptText is used only to estimate usage tokens to populate usage fields.
func EnsureGeminiWebAliasMap ¶
func EnsureGeminiWebAliasMap()
func EstimateTotalTokensFromRawJSON ¶
EstimateTotalTokensFromRawJSON estimates token count by summing text parts.
func FetchGeneratedImageData ¶
func FetchGeneratedImageData(gi GeneratedImage) (string, string, error)
func LoadConvData ¶
LoadConvData reads the full conversation data and index from disk.
func LoadConvStore ¶
LoadConvStore reads the account-level metadata store from disk.
func MapAliasToUnderlying ¶
func MaskToken28 ¶
MaskToken28 masks a sensitive token for safe logging. Keep middle partially visible.
func MaterializeInlineFiles ¶
func MaterializeInlineFiles(files [][]byte, mimes []string) ([]string, *interfaces.ErrorMessage)
func MaxCharsPerRequest ¶
func MimeToPreferredExt ¶
func NeedRoleTags ¶
NeedRoleTags checks if a list of messages requires role tags.
func NormalizeRole ¶
NormalizeRole converts a role to a standard format (lowercase, 'model' -> 'assistant').
func RemoveThinkTags ¶
RemoveThinkTags strips <think>...</think> blocks from a string.
func SaveConvData ¶
SaveConvData writes the full conversation data and index to disk atomically.
func SaveConvStore ¶
SaveConvStore writes the account-level metadata store to disk atomically.
func WithInsecureTLS ¶
func WithInsecureTLS(insecure bool) func(*GeminiClient)
WithInsecureTLS sets skipping TLS verification (to mirror httpx verify=False)
Types ¶
type AuthError ¶
type AuthError struct{ Msg string }
Error hierarchy -----------------------------------------------------------
type Candidate ¶
type Candidate struct { RCID string Text string Thoughts *string WebImages []WebImage GeneratedImages []GeneratedImage }
type ChatSession ¶
type ChatSession struct {
// contains filtered or unexported fields
}
ChatSession holds conversation metadata
func (*ChatSession) CID ¶
func (cs *ChatSession) CID() string
func (*ChatSession) ChooseCandidate ¶
func (cs *ChatSession) ChooseCandidate(index int) (ModelOutput, error)
ChooseCandidate selects a candidate from last output and updates rcid
func (*ChatSession) Metadata ¶
func (cs *ChatSession) Metadata() []string
func (*ChatSession) RCID ¶
func (cs *ChatSession) RCID() string
func (*ChatSession) RID ¶
func (cs *ChatSession) RID() string
func (*ChatSession) RequestedModel ¶
func (cs *ChatSession) RequestedModel() string
func (*ChatSession) SendMessage ¶
func (cs *ChatSession) SendMessage(prompt string, files []string) (ModelOutput, error)
SendMessage shortcut to client's GenerateContent
func (*ChatSession) SetMetadata ¶
func (cs *ChatSession) SetMetadata(v []string)
func (*ChatSession) SetRequestedModel ¶
func (cs *ChatSession) SetRequestedModel(name string)
func (*ChatSession) String ¶
func (cs *ChatSession) String() string
type ConversationRecord ¶
type ConversationRecord struct { Model string `json:"model"` ClientID string `json:"client_id"` Metadata []string `json:"metadata,omitempty"` Messages []StoredMessage `json:"messages"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` }
func BuildConversationRecord ¶
func BuildConversationRecord(model, clientID string, history []RoleText, output *ModelOutput, metadata []string) (ConversationRecord, bool)
BuildConversationRecord constructs a ConversationRecord from history and the latest output. Returns false when output is empty or has no candidates.
func FindByMessageListIn ¶
func FindByMessageListIn(items map[string]ConversationRecord, index map[string]string, stableClientID, email, model string, msgs []RoleText) (ConversationRecord, bool)
FindByMessageListIn looks up a conversation record by hashed message list. It attempts both the stable client ID and a legacy email-based ID.
func FindConversationIn ¶
func FindConversationIn(items map[string]ConversationRecord, index map[string]string, stableClientID, email, model string, msgs []RoleText) (ConversationRecord, bool)
FindConversationIn tries exact then sanitized assistant messages.
func FindReusableSessionIn ¶
func FindReusableSessionIn(items map[string]ConversationRecord, index map[string]string, stableClientID, email, model string, msgs []RoleText) (ConversationRecord, []string, int, bool)
FindReusableSessionIn returns reusable metadata and the remaining message suffix.
type GeminiClient ¶
type GeminiClient struct { Cookies map[string]string Proxy string Running bool AccessToken string Timeout time.Duration // contains filtered or unexported fields }
GeminiClient is the async http client interface (Go port)
func NewGeminiClient ¶
func NewGeminiClient(secure1psid string, secure1psidts string, proxy string, opts ...func(*GeminiClient)) *GeminiClient
NewGeminiClient creates a client. Pass empty strings to auto-detect via browser cookies (not implemented in Go port).
func (*GeminiClient) Close ¶
func (c *GeminiClient) Close(delaySec float64)
func (*GeminiClient) GenerateContent ¶
func (c *GeminiClient) GenerateContent(prompt string, files []string, model Model, gem *Gem, chat *ChatSession) (ModelOutput, error)
GenerateContent sends a prompt (with optional files) and parses the response into ModelOutput.
func (*GeminiClient) Init ¶
func (c *GeminiClient) Init(timeoutSec float64, verbose bool) error
Init initializes the access token and http client.
func (*GeminiClient) RotateTS ¶
func (c *GeminiClient) RotateTS() (string, error)
RotateTS performs a RotateCookies request and returns the new __Secure-1PSIDTS value (if any).
func (*GeminiClient) StartChat ¶
func (c *GeminiClient) StartChat(model Model, gem *Gem, metadata []string) *ChatSession
StartChat returns a ChatSession attached to the client
type GeminiError ¶
type GeminiError struct{ Msg string }
func (*GeminiError) Error ¶
func (e *GeminiError) Error() string
type GeminiWebState ¶
type GeminiWebState struct {
// contains filtered or unexported fields
}
func NewGeminiWebState ¶
func NewGeminiWebState(cfg *config.Config, token *gemini.GeminiWebTokenStorage, storagePath, authLabel string) *GeminiWebState
func (*GeminiWebState) ConvertStream ¶
func (*GeminiWebState) ConvertToTarget ¶
func (*GeminiWebState) DoneStream ¶
func (s *GeminiWebState) DoneStream(ctx context.Context, modelName string, prep *geminiWebPrepared) []string
func (*GeminiWebState) EnsureClient ¶
func (s *GeminiWebState) EnsureClient() error
func (*GeminiWebState) GetRequestMutex ¶
func (s *GeminiWebState) GetRequestMutex() *sync.Mutex
func (*GeminiWebState) Label ¶ added in v6.0.4
func (s *GeminiWebState) Label() string
Label returns a stable account label for logging and persistence. If a storage file path is known, it uses the file base name (without extension). Otherwise, it falls back to the stable client ID (e.g., "gemini-web-<hash>").
func (*GeminiWebState) Send ¶
func (s *GeminiWebState) Send(ctx context.Context, modelName string, reqPayload []byte, opts cliproxyexecutor.Options) ([]byte, *interfaces.ErrorMessage, *geminiWebPrepared)
func (*GeminiWebState) SetPendingMatch ¶ added in v6.0.18
func (s *GeminiWebState) SetPendingMatch(match *conversation.MatchResult)
SetPendingMatch makes a cached conversation match available for the next request.
func (*GeminiWebState) TokenSnapshot ¶
func (s *GeminiWebState) TokenSnapshot() *gemini.GeminiWebTokenStorage
type GeneratedImage ¶
type ImageGenerationError ¶
type ImageGenerationError struct{ APIError }
type Model ¶
Model metadata -------------------------------------------------------------
func ModelFromName ¶
type ModelInvalid ¶
type ModelInvalid struct{ GeminiError }
type ModelOutput ¶
func SendWithSplit ¶
func SendWithSplit(chat *ChatSession, text string, files []string, cfg *config.Config) (ModelOutput, error)
func (ModelOutput) Images ¶
func (m ModelOutput) Images() []Image
func (ModelOutput) RCID ¶
func (m ModelOutput) RCID() string
func (ModelOutput) String ¶
func (m ModelOutput) String() string
func (ModelOutput) Text ¶
func (m ModelOutput) Text() string
func (ModelOutput) Thoughts ¶
func (m ModelOutput) Thoughts() *string
type RoleText ¶
type RoleText = conversation.Message
Conversation domain structures -------------------------------------------
func AppendXMLWrapHintIfNeeded ¶
AppendXMLWrapHintIfNeeded appends an XML wrap hint to messages containing XML-like blocks.
func ParseMessagesAndFiles ¶
func SanitizeAssistantMessages ¶
SanitizeAssistantMessages removes think tags from assistant messages.
type StoredMessage ¶
type StoredMessage = conversation.StoredMessage
type TemporarilyBlocked ¶
type TemporarilyBlocked struct{ GeminiError }
type TimeoutError ¶
type TimeoutError struct{ GeminiError }
type UsageLimitExceeded ¶
type UsageLimitExceeded struct{ GeminiError }
type ValueError ¶
type ValueError struct{ Msg string }
func (*ValueError) Error ¶
func (e *ValueError) Error() string