geminiwebapi

package
v5.2.5 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2025 License: MIT Imports: 30 Imported by: 0

Documentation

Index

Constants

View Source
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

View Source
const (
	ErrorUsageLimitExceeded   = 1037
	ErrorModelInconsistent    = 1050
	ErrorModelHeaderInvalid   = 1052
	ErrorIPTemporarilyBlocked = 1060
)

Known error codes returned from server

Variables

View Source
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

View Source
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,
	}
)
View Source
var (
	GeminiWebAliasOnce sync.Once
	GeminiWebAliasMap  map[string]string
)
View Source
var NanoBananaModel = map[string]struct{}{
	"gemini-2.5-flash-image-preview": {},
}

Functions

func AccountMetaKey

func AccountMetaKey(email, modelName string) string

AccountMetaKey builds the key for account-level metadata map.

func AddRoleTag

func AddRoleTag(role, content string, unclose bool) string

AddRoleTag wraps content with a role tag.

func AliasFromModelID

func AliasFromModelID(modelID string) string

AliasFromModelID builds the web alias for a Gemini model identifier.

func BuildPrompt

func BuildPrompt(msgs []RoleText, tagged bool, appendAssistant bool) string

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 ChunkByRunes(s string, size int) []string

func CleanupFiles

func CleanupFiles(paths []string)

func ConvDataPath

func ConvDataPath(tokenFilePath string) string

ConvDataPath returns the path for full conversation persistence based on token file path.

func ConvStorePath

func ConvStorePath(tokenFilePath string) string

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 Debug

func Debug(format string, v ...any)

func DebugRaw

func DebugRaw(format string, v ...any)

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 Error

func Error(format string, v ...any)

func EstimateTotalTokensFromRawJSON

func EstimateTotalTokensFromRawJSON(rawJSON []byte) int

EstimateTotalTokensFromRawJSON estimates token count by summing text parts.

func FetchGeneratedImageData

func FetchGeneratedImageData(gi GeneratedImage) (string, string, error)

func GetGeminiWebAliasedModels

func GetGeminiWebAliasedModels() []*registry.ModelInfo

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 Info

func Info(format string, v ...any)

func LoadConvData

func LoadConvData(path string) (map[string]ConversationRecord, map[string]string, error)

LoadConvData reads the full conversation data and index from disk.

func LoadConvStore

func LoadConvStore(path string) (map[string][]string, error)

LoadConvStore reads the account-level metadata store from disk.

func MapAliasToUnderlying

func MapAliasToUnderlying(name string) string

MapAliasToUnderlying normalizes web aliases back to canonical Gemini IDs.

func MaskToken

func MaskToken(s string) string

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

func MaskToken28(s string) string

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 MaxCharsPerRequest(cfg *config.Config) int

func MimeToExt

func MimeToExt(mimes []string, i int) string

func MimeToPreferredExt

func MimeToPreferredExt(mime string) string

func NeedRoleTags

func NeedRoleTags(msgs []RoleText) bool

NeedRoleTags checks if a list of messages requires role tags.

func NormalizeRole

func NormalizeRole(role string) string

NormalizeRole converts a role to a standard format (lowercase, 'model' -> 'assistant').

func RemoveThinkTags

func RemoveThinkTags(s string) string

RemoveThinkTags strips <think>...</think> blocks from a string.

func SaveConvData

func SaveConvData(path string, items map[string]ConversationRecord, index map[string]string) error

SaveConvData writes the full conversation data and index to disk atomically.

func SaveConvStore

func SaveConvStore(path string, data map[string][]string) error

SaveConvStore writes the account-level metadata store to disk atomically.

func SetLogLevel

func SetLogLevel(level string)

SetLogLevel adjusts logging verbosity using CLI-style strings.

func Sha256Hex

func Sha256Hex(s string) string

Sha256Hex computes the SHA256 hash of a string and returns its hex representation.

func Success

func Success(format string, v ...any)

func Warning

func Warning(format string, v ...any)

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 APIError

type APIError struct{ Msg string }

func (*APIError) Error

func (e *APIError) Error() string

type AuthError

type AuthError struct{ Msg string }

func (*AuthError) Error

func (e *AuthError) Error() string

type Candidate

type Candidate struct {
	RCID            string
	Text            string
	Thoughts        *string
	WebImages       []WebImage
	GeneratedImages []GeneratedImage
}

func (Candidate) Images

func (c Candidate) Images() []Image

func (Candidate) String

func (c Candidate) String() string

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 added in v5.2.4

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 added in v5.2.4

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"`
}

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 Gem

type Gem struct {
	ID          string
	Name        string
	Description *string
	Prompt      *string
	Predefined  bool
}

func (Gem) String

func (g Gem) String() string

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 GeneratedImage struct {
	Image
	Cookies map[string]string
}

func (GeneratedImage) Save

func (g GeneratedImage) Save(path string, filename string, fullSize bool, verbose bool, skipInvalidFilename bool, insecure bool) (string, error)

type Image

type Image struct {
	URL   string
	Title string
	Alt   string
	Proxy string
}

func (Image) Save

func (i Image) Save(path string, filename string, cookies map[string]string, verbose bool, skipInvalidFilename bool, insecure bool) (string, error)

func (Image) String

func (i Image) String() string

type ImageGenerationError

type ImageGenerationError struct{ APIError }

type Model

type Model struct {
	Name         string
	ModelHeader  http.Header
	AdvancedOnly bool
}

Model defines available model names and headers

func ModelFromName

func ModelFromName(name string) (Model, error)

ModelFromName returns a model by name or error if not found

type ModelInvalid

type ModelInvalid struct{ GeminiError }

type ModelOutput

type ModelOutput struct {
	Metadata   []string
	Candidates []Candidate
	Chosen     int
}

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 struct {
	Role string
	Text string
}

RoleText represents a turn in a conversation with a role and text content.

func AppendXMLWrapHintIfNeeded

func AppendXMLWrapHintIfNeeded(msgs []RoleText, disable bool) []RoleText

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 ParseMessagesAndFiles(rawJSON []byte) ([]RoleText, [][]byte, []string, [][]int, error)

func SanitizeAssistantMessages

func SanitizeAssistantMessages(msgs []RoleText) []RoleText

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

type WebImage

type WebImage struct{ Image }

Jump to

Keyboard shortcuts

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