Documentation
¶
Index ¶
- Constants
- Variables
- func AccountMetaKey(email, modelName string) string
- func AddRoleTag(role, content string, unclose bool) string
- func AliasFromModelID(modelID string) string
- func ApplyCookiesSidecarToTokenStorage(tokenFilePath string, ts *gemini.GeminiWebTokenStorage) (bool, error)
- func BuildPrompt(msgs []RoleText, tagged bool, appendAssistant bool) string
- func BuildUpstreamRequestLog(account string, contextOn bool, useTags, explicitContext bool, prompt string, ...) string
- func ChunkByRunes(s string, size int) []string
- func CleanupFiles(paths []string)
- func ConvDataPath(tokenFilePath string) string
- func ConvStorePath(tokenFilePath string) string
- func ConvertOutputToGemini(output *ModelOutput, modelName string, promptText string) ([]byte, error)
- func CookiesSidecarPath(mainPath string) string
- func Debug(format string, v ...any)
- func DebugRaw(format string, v ...any)
- func EnsureGeminiWebAliasMap()
- func Error(format string, v ...any)
- func EstimateTotalTokensFromRawJSON(rawJSON []byte) int
- func FetchGeneratedImageData(gi GeneratedImage) (string, string, error)
- func FileExists(path string) bool
- func FlushCookiesSidecarToMain(tokenFilePath string, cookies map[string]string, ...) error
- func GetGeminiWebAliasedModels() []*registry.ModelInfo
- func HashConversation(clientID, model string, msgs []StoredMessage) string
- func HashMessage(m StoredMessage) string
- func Info(format string, v ...any)
- 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 MaskToken(s 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 SaveCookiesSidecar(tokenFilePath string, cookies map[string]string) error
- func SetLogLevel(level string)
- func Sha256Hex(s string) string
- func Success(format string, v ...any)
- func Warning(format string, v ...any)
- func WithAccountLabel(label string) func(*GeminiClient)
- 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) SendMessage(prompt string, files []string) (ModelOutput, error)
- func (cs *ChatSession) SetMetadata(v []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)
- 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, autoClose bool, closeDelaySec float64, autoRefresh bool, ...) error
- func (c *GeminiClient) StartChat(model Model, gem *Gem, metadata []string) *ChatSession
- type GeminiError
- type GeneratedImage
- type Image
- type ImageGenerationError
- type Model
- type ModelInvalid
- type ModelOutput
- type RoleText
- func AppendXMLWrapHintIfNeeded(msgs []RoleText, disable bool) []RoleText
- func FindReusableSessionIn(items map[string]ConversationRecord, index map[string]string, ...) ([]string, []RoleText)
- func ParseMessagesAndFiles(rawJSON []byte) ([]RoleText, [][]byte, []string, [][]int, error)
- func SanitizeAssistantMessages(msgs []RoleText) []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" )
Endpoints used by the Gemini web app
const ( ErrorUsageLimitExceeded = 1037 ErrorModelInconsistent = 1050 ErrorModelHeaderInvalid = 1052 ErrorIPTemporarilyBlocked = 1060 )
Known error codes returned from 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"}, } )
Default headers
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 ( GeminiWebAliasOnce sync.Once GeminiWebAliasMap map[string]string )
Functions ¶
func AccountMetaKey ¶
AccountMetaKey builds the key for account-level metadata map.
func AddRoleTag ¶
AddRoleTag wraps content with a role tag.
func AliasFromModelID ¶
AliasFromModelID builds the web alias for a Gemini model identifier.
func ApplyCookiesSidecarToTokenStorage ¶
func ApplyCookiesSidecarToTokenStorage(tokenFilePath string, ts *gemini.GeminiWebTokenStorage) (bool, error)
ApplyCookiesSidecarToTokenStorage loads cookies from sidecar into the provided token storage. Returns true when a sidecar was found and applied.
func BuildPrompt ¶
BuildPrompt constructs the final prompt from a list of messages.
func BuildUpstreamRequestLog ¶
func BuildUpstreamRequestLog(account string, contextOn bool, useTags, explicitContext bool, prompt string, filesCount int, reuse bool, metaLen int, gem *Gem) string
BuildUpstreamRequestLog builds a compact preview string for upstream request logging.
func ChunkByRunes ¶
func CleanupFiles ¶
func CleanupFiles(paths []string)
func ConvDataPath ¶
ConvDataPath returns the path for full conversation persistence based on token file path.
func ConvStorePath ¶
ConvStorePath returns the path for account-level metadata persistence based on token file path.
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 CookiesSidecarPath ¶
CookiesSidecarPath derives the sidecar cookie file path from the main token JSON path.
func DebugRaw ¶
DebugRaw logs without the module prefix; use sparingly for messages that should integrate with global formatting without extra tags.
func EnsureGeminiWebAliasMap ¶
func EnsureGeminiWebAliasMap()
EnsureGeminiWebAliasMap initializes alias lookup lazily.
func EstimateTotalTokensFromRawJSON ¶
EstimateTotalTokensFromRawJSON estimates token count by summing text parts.
func FetchGeneratedImageData ¶
func FetchGeneratedImageData(gi GeneratedImage) (string, string, error)
func FileExists ¶
FileExists reports whether the given path exists and is a regular file.
func FlushCookiesSidecarToMain ¶
func FlushCookiesSidecarToMain(tokenFilePath string, cookies map[string]string, base *gemini.GeminiWebTokenStorage) error
FlushCookiesSidecarToMain merges the sidecar cookies into the main token file and removes the sidecar. If sidecar is missing, it will combine the provided base token storage with the latest cookies.
func GetGeminiWebAliasedModels ¶
GetGeminiWebAliasedModels returns Gemini models exposed with web aliases.
func HashConversation ¶
func HashConversation(clientID, model string, msgs []StoredMessage) string
func HashMessage ¶
func HashMessage(m StoredMessage) string
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 ¶
MapAliasToUnderlying normalizes web aliases back to canonical Gemini IDs.
func MaskToken ¶
MaskToken hides the middle part of a sensitive value with '*'. It keeps up to left and right edge characters for readability. If input is very short, it returns a fully masked string of the same length.
func MaskToken28 ¶
MaskToken28 returns a fixed-length (28) masked representation showing: first 8 chars + 8 asterisks + 4 middle chars + last 8 chars. If the input is shorter than 20 characters, it returns a fully masked string of length min(len(s), 28).
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 SaveCookiesSidecar ¶
SaveCookiesSidecar writes the current cookies into a sidecar file next to the token file. This keeps the main token JSON stable until an orderly flush.
func SetLogLevel ¶
func SetLogLevel(level string)
SetLogLevel adjusts logging verbosity using CLI-style strings.
func WithAccountLabel ¶
func WithAccountLabel(label string) func(*GeminiClient)
WithAccountLabel sets an identifying label (e.g., token filename sans .json) for logging purposes.
func WithInsecureTLS ¶
func WithInsecureTLS(insecure bool) func(*GeminiClient)
WithInsecureTLS sets skipping TLS verification (to mirror httpx verify=False)
Types ¶
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) 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) 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"`
}
ConversationRecord stores a full conversation with its metadata for persistence.
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.
type GeminiClient ¶
type GeminiClient struct {
Cookies map[string]string
Proxy string
Running bool
AccessToken string
Timeout time.Duration
AutoClose bool
CloseDelay time.Duration
AutoRefresh bool
RefreshInterval 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, autoClose bool, closeDelaySec float64, autoRefresh bool, refreshIntervalSec float64, verbose bool) error
Init initializes the access token and http client.
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 GeneratedImage ¶
type ImageGenerationError ¶
type ImageGenerationError struct{ APIError }
type Model ¶
Model defines available model names and headers
func ModelFromName ¶
ModelFromName returns a model by name or error if not found
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 ¶
RoleText represents a turn in a conversation with a role and text content.
func AppendXMLWrapHintIfNeeded ¶
AppendXMLWrapHintIfNeeded appends an XML wrap hint to messages containing XML-like blocks.
func FindReusableSessionIn ¶
func FindReusableSessionIn(items map[string]ConversationRecord, index map[string]string, stableClientID, email, model string, msgs []RoleText) ([]string, []RoleText)
FindReusableSessionIn returns reusable metadata and the remaining message suffix.
func ParseMessagesAndFiles ¶
func SanitizeAssistantMessages ¶
SanitizeAssistantMessages removes think tags from assistant messages.
type StoredMessage ¶
type StoredMessage struct {
Role string `json:"role"`
Content string `json:"content"`
Name string `json:"name,omitempty"`
}
StoredMessage represents a single message in a conversation record.
func ToStoredMessages ¶
func ToStoredMessages(msgs []RoleText) []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