geminiwebapi

package
v6.1.3 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2025 License: MIT Imports: 36 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"
)

Gemini web endpoints and default headers ----------------------------------

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

Known error codes returned from the 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"},
	}
)
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 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

func BuildPrompt

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

BuildPrompt constructs the final prompt from a list of messages.

func ChunkByRunes

func ChunkByRunes(s string, size int) []string

func CleanupFiles

func CleanupFiles(paths []string)

func ConvBoltPath added in v6.0.4

func ConvBoltPath(tokenFilePath string) string

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

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

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

func MaskToken28

func MaskToken28(s string) string

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

Error hierarchy -----------------------------------------------------------

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

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 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
	// 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 (s *GeminiWebState) ConvertStream(ctx context.Context, modelName string, prep *geminiWebPrepared, gemBytes []byte) []string

func (*GeminiWebState) ConvertToTarget

func (s *GeminiWebState) ConvertToTarget(ctx context.Context, modelName string, prep *geminiWebPrepared, gemBytes []byte) []byte

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) Refresh

func (s *GeminiWebState) Refresh(ctx context.Context) error

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 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 metadata -------------------------------------------------------------

func ModelFromName

func ModelFromName(name string) (Model, error)

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 = conversation.Message

Conversation domain structures -------------------------------------------

func AppendXMLWrapHintIfNeeded

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

AppendXMLWrapHintIfNeeded appends an XML wrap hint to messages containing XML-like blocks.

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 = 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

type WebImage

type WebImage struct{ Image }

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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