aistudio

package
v0.3.15 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 72 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	// MakerSuiteRPCBase 是 AI Studio RPC 根地址
	MakerSuiteRPCBase = "https://alkalimakersuite-pa.clients6.google.com/$rpc/google.internal.alkali.applications.makersuite.v1.MakerSuiteService/"

	// JSONProtobufContentType 是 MakerSuite 使用的数组协议媒体类型
	JSONProtobufContentType = "application/json+protobuf"
)
View Source
const AccountRejectionKind = "权限拒绝"

AccountRejectionKind 是上游以 403、协议错误码 7 暂时拒绝账户时冷却的类型名,也是其冷却原因的前缀

View Source
const CooldownQueueLimit = time.Minute

CooldownQueueLimit 为全部候选账户冷却时一个请求排队等待恢复的累计上限,覆盖分钟限额窗口

View Source
const DailyLimitKind = "每日限额"

DailyLimitKind 是每日限额冷却的类型名,也是其冷却原因的前缀

View Source
const DefaultTranscriptionModel = "gemini-3.5-transcribe"
View Source
const MaxAccountNoteLength = 120

MaxAccountNoteLength 是账户备注允许的最大字符数

View Source
const PlanLimitKind = "套餐限额"

PlanLimitKind 是套餐限额冷却的类型名,也是其冷却原因的前缀

View Source
const (
	StorageStateName = "storage-state.json"
)

Variables

View Source
var (
	// ErrInvalidArgument 表示请求参数在发送前已确定无效
	ErrInvalidArgument = errors.New("AI Studio 请求参数无效")
	// ErrModelNotFound 表示实时目录中不存在请求模型
	ErrModelNotFound = errors.New("AI Studio 实时目录中没有请求模型")
	// ErrNoEligibleAccount 表示没有账户具备请求所需能力
	ErrNoEligibleAccount = errors.New("没有符合条件的 AI Studio 账户")

	// ErrAccountNotFound 表示稳定账户 ID 不存在
	ErrAccountNotFound = errors.New("账户不存在")
	// ErrAccountExists 表示同一邮箱的账户目录已存在
	ErrAccountExists = errors.New("账户已存在")
	// ErrAccountLeased 表示账户当前存在进程内或跨进程租约
	ErrAccountLeased = errors.New("账户正在使用")
	// ErrAccountCoolingDown 表示租约账户在请求发出前进入冷却
	ErrAccountCoolingDown = errors.New("账户已进入冷却")
	// ErrResourceNotFound 表示资源没有创建账户映射
	ErrResourceNotFound = errors.New("资源账户映射不存在")
)
View Source
var ErrLoginCookieMissing = errors.New("Cookie 缺少登录 Cookie")

ErrLoginCookieMissing 表示 Cookie 中没有登录 AI Studio 所需的 Cookie

View Source
var ErrProtectedTransport = errors.New("受保护请求网络错误")

ErrProtectedTransport 表示 SpiderMonkey 后端受保护请求在出口连接上失败,VM 与页面状态不受影响

Functions

func AccountError added in v0.3.0

func AccountError(accountIDs string, err error) error

AccountError 以“账户 <ID>: <原因>”写明失败的账户,供 GroupedErrors.Join 使用

func AspectRatioLog added in v0.2.8

func AspectRatioLog(value string) (float64, bool)

AspectRatioLog 返回 W:H 宽高比的自然对数

func BuildGenerationDisabled added in v0.2.17

func BuildGenerationDisabled(err error) bool

BuildGenerationDisabled 判断错误是上游停用 Build 代理生成的 PROXY_GENERATION_DISABLED

func ChannelCooldownScope added in v0.2.0

func ChannelCooldownScope(channel Channel, scope string) string

ChannelCooldownScope 返回通道在作用域上的冷却键,Build 使用 build:<作用域>

func CheckSession added in v0.2.18

func CheckSession(ctx context.Context, options camoufoxnative.Options) error

CheckSession 像官网页面一样打开账户的 AI Studio 新对话页,被转到 Google 登录页时返回 camoufoxnative.ErrAuthenticationRequired,被转到拒绝页时返回对应的 camoufoxnative.AccessDenial

func ContextWithAPIKey added in v0.2.19

func ContextWithAPIKey(ctx context.Context, key string) context.Context

ContextWithAPIKey 返回带有请求所用 API key 的上下文,账户池只在该 key 绑定的账户中选号

func ContextWithAccount added in v0.3.6

func ContextWithAccount(ctx context.Context, accountID string) context.Context

ContextWithAccount 返回带有请求指定账户的上下文,账户池只用该账户

func ContextWithAccountLease

func ContextWithAccountLease(ctx context.Context, lease *AccountLease) context.Context

ContextWithAccountLease 将上层已持有的租约传给协议传输

func ContextWithAccountSelectionObserver

func ContextWithAccountSelectionObserver(ctx context.Context, observer func(*AccountLease)) context.Context

ContextWithAccountSelectionObserver 观察请求最终取得的账户租约

func ContextWithContinuationAccounts added in v0.3.6

func ContextWithContinuationAccounts(ctx context.Context, accounts ContinuationAccounts) context.Context

ContextWithContinuationAccounts 返回续写轮可经 accounts 换账户发送的上下文

func ContextWithRefreshSteps added in v0.3.13

func ContextWithRefreshSteps(ctx context.Context, report func(step AccountStep, index, total int)) context.Context

ContextWithRefreshSteps 让账户刷新与目录同步在进入每一步时调用 report,index 从 1 开始,total 为这次操作的步数

func ContextWithRegenerationObserver added in v0.3.14

func ContextWithRegenerationObserver(ctx context.Context, observer func(attempt int, reason string)) context.Context

ContextWithRegenerationObserver 在流在完成前中断、流尾为 5xx 或上游异常结束而重新生成之前调用 observer,attempt 从 1 起,reason 为中断错误或结束原因

func ContextWithReplyToolBypassObserver added in v0.3.14

func ContextWithReplyToolBypassObserver(ctx context.Context, observer func()) context.Context

ContextWithReplyToolBypassObserver 在开启回复工具但模型直接输出正文时调用 observer

func ContextWithReplyToolObserver added in v0.3.15

func ContextWithReplyToolObserver(ctx context.Context, observer ReplyToolObserver) context.Context

ContextWithReplyToolObserver 绑定回复工具启用与调用次数观察器

func ContextWithRequestPhaseObserver

func ContextWithRequestPhaseObserver(ctx context.Context, observer func(RequestPhase)) context.Context

ContextWithRequestPhaseObserver 记录受保护请求阶段

func ContextWithResidentCatalog added in v0.3.12

func ContextWithResidentCatalog(ctx context.Context) context.Context

ContextWithResidentCatalog 返回要求账户目录读取在常驻 Worker 的页面上进行、不临时载入页面的 ctx

func ContextWithSelectionScope added in v0.3.6

func ContextWithSelectionScope(ctx, source context.Context) context.Context

ContextWithSelectionScope 返回带有 source 中所用 API key 与指定账户的 ctx,供跨请求的操作沿用发起请求的选号范围

func ContextWithServiceRun added in v0.3.10

func ContextWithServiceRun(ctx context.Context, run context.Context) context.Context

ContextWithServiceRun 记下生成服务本次运行的上下文,服务停止时它被取消

func ContextWithStreamActivityObserver

func ContextWithStreamActivityObserver(ctx context.Context, observer func(int)) context.Context

ContextWithStreamActivityObserver 记录上游响应体实际到达的字节,ctx 已有的观察函数照常收到同样的字节

func ContextWithUpstreamModeObserver added in v0.2.2

func ContextWithUpstreamModeObserver(ctx context.Context, observer func(method, mode string, round int, reason string)) context.Context

ContextWithUpstreamModeObserver 记录实际 RPC、传输模式、续写轮次与流式回退原因

func DecodeAssistantStream added in v0.2.13

func DecodeAssistantStream(source io.Reader, decoder *AssistantStreamDecoder, emit func(Event) error) error

DecodeAssistantStream 解码 StreamCodeAssistantOfflineGeneration 响应并把事件交给 emit 消息列表在回复完成前正常结束时经 Reopen 重新打开一次任务流继续读取 停止读取与以已有内容结束本轮的条件见 docs/build.md 的“任务流”一节

func DecodeBuildStream added in v0.2.0

func DecodeBuildStream(source io.Reader, decoder *BuildStreamDecoder, emit func(Event) error) error

DecodeBuildStream 解码 ProxyStreamedCall 响应:field 1 为 [["<JSON>"]...],其后可带 google.rpc 状态

func DecodeBuildUnary added in v0.2.0

func DecodeBuildUnary(source io.Reader, decoder *BuildStreamDecoder, emit func(Event) error) error

DecodeBuildUnary 解码 ProxyUnaryCall 响应:field 1 为一个 Gemini API GenerateContentResponse JSON

func DecodeGenerateStream

func DecodeGenerateStream(source io.Reader, decoder *FrameDecoder, emit func(Event) error) error

DecodeGenerateStream 按网络到达顺序解码 GenerateContent repeated 帧

func DecodeInteractionStream added in v0.2.0

func DecodeInteractionStream(method string, source io.Reader, emit func(Event) error) error

DecodeInteractionStream 按网络顺序解码 CreateInteractionStream 或 GetInteractionStream 的事件与流尾状态

func DefinitiveAuthenticationFailure

func DefinitiveAuthenticationFailure(err error) bool

DefinitiveAuthenticationFailure 判断上游是否明确要求重新认证

func DefinitiveWAARuntimeFailure

func DefinitiveWAARuntimeFailure(err error) bool

DefinitiveWAARuntimeFailure 判断上游是否明确拒绝当前 WAA 运行态

func DiscoverPublicHeaders

func DiscoverPublicHeaders(ctx context.Context, client *http.Client) (http.Header, error)

DiscoverPublicHeaders 从 AI Studio 首页读取普通 RPC 所需的公开头

func EncodeAssistantRequest added in v0.2.13

func EncodeAssistantRequest(request GenerateRequest, defaults GenerationDefaults, target assistantTarget, requestID string) ([]byte, int, error)

EncodeAssistantRequest 编码写代码助手一轮的 CodeAssistantOffline 请求 field 2 由 WAA proof 写入,各字段依据见 docs/build.md 的“CodeAssistantOffline”一节

func EncodeBidiMediaEndRequest

func EncodeBidiMediaEndRequest() ([]byte, int, string, error)

EncodeBidiMediaEndRequest 编码官网实时媒体结束帧

func EncodeBidiMediaRequest

func EncodeBidiMediaRequest(mimeType string, data []byte) ([]byte, int, string, error)

EncodeBidiMediaRequest 编码官网实时音频或图像输入帧

func EncodeBidiSetupRequest

func EncodeBidiSetupRequest(request BidiRequest, runtime RequestContext) ([]byte, int, string, error)

EncodeBidiSetupRequest 编码 Live 或 Robotics 的已验证 setup 帧,系统指令按 clientSystemText 改写

func EncodeBidiTextRequest

func EncodeBidiTextRequest(text string) ([]byte, int, string, error)

EncodeBidiTextRequest 编码官网文本输入帧

func EncodeBidiToolResponseRequest

func EncodeBidiToolResponseRequest(results []FunctionResult) ([]byte, int, string, error)

EncodeBidiToolResponseRequest 编码官网函数响应帧

func EncodeBuildBidiSetup added in v0.2.8

func EncodeBuildBidiSetup(request BidiRequest) ([]byte, int, string, error)

EncodeBuildBidiSetup 编码 Build 代理的 Live 或实时音乐 setup,Live 字段与 Playground setup 的语义一致

func EncodeBuildCountTokensRequest added in v0.2.17

func EncodeBuildCountTokensRequest(request TokenCountRequest) (string, []byte, error)

EncodeBuildCountTokensRequest 编码 countTokens 的 Gemini API 路径与请求体,内容、系统指令、工具与媒体分辨率放在 generateContentRequest

func EncodeBuildEmbedRequest added in v0.2.8

func EncodeBuildEmbedRequest(model string, requests []EmbedContentRequest) (string, []byte, error)

EncodeBuildEmbedRequest 编码 batchEmbedContents 的 Gemini API 路径与请求体,每条请求带模型名

func EncodeBuildGenerateRequest added in v0.2.0

func EncodeBuildGenerateRequest(request GenerateRequest, defaults GenerationDefaults, imageRoute bool, unary bool) (string, []byte, error)

EncodeBuildGenerateRequest 编码 Build 代理转发的 Gemini API 路径与 JSON 请求体,unary 使用 generateContent

func EncodeBuildProxyRequest added in v0.2.0

func EncodeBuildProxyRequest(path string, body []byte, unary bool) ([]byte, int, error)

EncodeBuildProxyRequest 编码代理请求:ProxyStreamedCall 为 [路径, 请求体, WAA proof],ProxyUnaryCall 追加 HTTP 方法;返回正文与 WAA proof 字段在正文中的起始字节

func EncodeCountTokensRequest

func EncodeCountTokensRequest(request TokenCountRequest) ([]byte, error)

EncodeCountTokensRequest 编码 CountTokens 请求

func EncodeCreateDecisionRequest added in v0.3.6

func EncodeCreateDecisionRequest(request DecisionRequest) ([]byte, int, error)

EncodeCreateDecisionRequest 编码官网 CreateDecision 数组协议:模型、输入 Content 列表、问题 map 与 field 5 的 proof 位,返回正文与 proof 位在正文中的起始字节

func EncodeGenerateContentRequest

func EncodeGenerateContentRequest(request GenerateRequest, defaults GenerationDefaults, runtime RequestContext) ([]byte, int, error)

EncodeGenerateContentRequest 编码 GenerateContent 数组,返回正文与 WAA proof 字段(field 5)在正文中的起始字节

func EncodeGenerateImageRequest added in v0.2.18

func EncodeGenerateImageRequest(request ImageRequest) ([]byte, int)

EncodeGenerateImageRequest 编码官网 GenerateImage 数组协议:模型、提示词、proof 位与图片数、反向提示词、宽高比、输出分辨率配置,返回正文与 proof 位在正文中的起始字节

func EncodeGetInteractionStreamRequest added in v0.2.14

func EncodeGetInteractionStreamRequest(id string, model string) ([]byte, int, error)

EncodeGetInteractionStreamRequest 编码按 interaction ID 读取后台任务增量与终态的请求

func InteractionInlineMIME added in v0.3.2

func InteractionInlineMIME(mime string) bool

InteractionInlineMIME 表示该 MIME 的附件经 Interaction 模型路径与官网一样以内联数据发送,范围为图片枚举表中的类型

func IsVideoModel added in v0.2.15

func IsVideoModel(model Model) bool

IsVideoModel 表示模型经 generateContent 输出视频(如 Omni),能完成视频长任务

func MergePCM added in v0.2.18

func MergePCM(last *Part, next Part) bool

MergePCM 将思考标记、签名与格式都相同的 PCM 数据追加到 last,返回是否合并

func ModelAccessKey

func ModelAccessKey(scope string, modelID string) string

ModelAccessKey 返回关联真实目录模型的独立资格键

func NearestOption added in v0.2.8

func NearestOption(target float64, options []string, measure func(string) (float64, bool)) string

NearestOption 返回度量值与目标最接近的选项,距离相同时取度量值较大者

func NewProxyHTTPClient

func NewProxyHTTPClient(proxyURL string) (*http.Client, error)

NewProxyHTTPClient 创建普通 HTTP、HTTPS 或 SOCKS5 固定出口客户端

func NormalizeTimezone added in v0.3.1

func NormalizeTimezone(value string) string

NormalizeTimezone 去掉时区名两端的空白与其中的 Unicode 格式字符,如零宽空格、BOM 与方向标记

func QueuedCoolingError added in v0.3.9

func QueuedCoolingError(ctx context.Context, modelID string, cooldown CooldownState, queued time.Duration) error

QueuedCoolingError 返回全部候选账户冷却时的排队结果:最早恢复的冷却在已排队 queued 之后的上限内、不晚于 ctx 的期限且不是权限拒绝冷却时为 nil,否则为 AllCoolingError

func QuotaDayStart added in v0.3.15

func QuotaDayStart(now time.Time) time.Time

QuotaDayStart 返回 now 所在配额日(太平洋时间 00:00)的起始时刻

func RequestBuildOnly added in v0.2.17

func RequestBuildOnly(request GenerateRequest) bool

RequestBuildOnly 判断请求含 Playground 没有对应形式的设置:指定存储的 File Search

func RequestNeedsBuild added in v0.2.17

func RequestNeedsBuild(request GenerateRequest) bool

RequestNeedsBuild 判断请求是否含 Playground 无法完整表达的设置

func RequestQuotaCooldown added in v0.3.2

func RequestQuotaCooldown(reason string) bool

RequestQuotaCooldown 判断冷却原因是上游按每个请求判定是否放行的套餐限额或每日限额,用尽后较短的请求仍可能完成

func ResidentCatalog added in v0.3.12

func ResidentCatalog(ctx context.Context) bool

ResidentCatalog 判断 ctx 是否要求账户目录读取在常驻 Worker 的页面上进行

func ResolveSearchModelAlias added in v0.2.18

func ResolveSearchModelAlias(model string) (baseModel string, enableSearch bool)

ResolveSearchModelAlias 解析模型名末尾或思考后缀之前的搜索后缀,思考后缀保留在返回的型号上

func RestrictionDenial added in v0.3.7

func RestrictionDenial(err error) *camoufoxnative.AccessDenial

RestrictionDenial 返回错误中 Google 拒绝该账户本身使用 AI Studio 的原因,出口地区不受支持与其他错误返回 nil

func ServiceStopped added in v0.3.14

func ServiceStopped(ctx context.Context) bool

ServiceStopped 返回 ctx 所属的生成服务是否已停止,ctx 没有记下服务运行时为 false

func StartInputTokenEstimate added in v0.2.17

func StartInputTokenEstimate(request GenerateRequest) <-chan int64

StartInputTokenEstimate 取下请求中计入本地输入 Token 估算的文本、工具与引用元数据,在后台分词并把估算结果写入返回的通道

func SystemText added in v0.2.17

func SystemText(system []string) string

SystemText 返回系统指令各段文本按顺序连接的结果

func ToolPartTranscript added in v0.2.17

func ToolPartTranscript(part Part) (string, error)

ToolPartTranscript 返回函数调用、函数结果、代码执行与服务端工具步骤 part 的 Gemini API JSON 文本

func TranscriptionGenerationFailure

func TranscriptionGenerationFailure(err error) bool

TranscriptionGenerationFailure 判断错误是否来自转录生成阶段

func TruncateAccountNote added in v0.3.14

func TruncateAccountNote(note string) string

TruncateAccountNote 规范化账户备注:去掉首尾空白、折叠换行并在超过长度上限时按字符截断

func WriteStorageState

func WriteStorageState(filePath string, state StorageState) error

WriteStorageState 原子写回 Playwright storage state

Types

type AbnormalFinishError added in v0.3.9

type AbnormalFinishError struct {
	Reason  string
	Message string
	// Usage 是上游最后给出的用量
	Usage *Usage
}

AbnormalFinishError 表示上游以格式错误的函数调用、意外的工具调用或格式错误的响应结束且这次生成没有任何输出

func (*AbnormalFinishError) Error added in v0.3.9

func (e *AbnormalFinishError) Error() string

Error 返回上游异常结束生成的原因

type Account

type Account struct {
	ID           string        `json:"id"`
	Directory    string        `json:"-"`
	ConfigPath   string        `json:"-"`
	StoragePath  string        `json:"-"`
	RuntimePath  string        `json:"-"`
	Config       AccountConfig `json:"config"`
	StorageState StorageState  `json:"-"`
	Models       []Model       `json:"models,omitempty"`
	BenefitTier  BenefitTier   `json:"benefit_tier"`
	State        AccountState  `json:"state"`
	LastUsed     time.Time     `json:"last_used,omitempty"`
	// contains filtered or unexported fields
}

Account 表示一个稳定目录对应的 AI Studio 账户

func (*Account) AcceptLanguage

func (a *Account) AcceptLanguage() string

AcceptLanguage 返回账户 locale 对应的请求语言头

func (*Account) EffectiveProxy

func (a *Account) EffectiveProxy(globalProxy string) string

EffectiveProxy 返回账户固定代理、代理池绑定或全局代理

func (*Account) PoolProxy added in v0.2.12

func (a *Account) PoolProxy(globalProxy string) string

PoolProxy 返回账户的代理池绑定,未绑定时返回全局代理

func (*Account) SetPoolProxy added in v0.2.12

func (a *Account) SetPoolProxy(proxy string)

SetPoolProxy 设置账户加入账户池前使用的代理池绑定

func (*Account) SupportsMethod

func (a *Account) SupportsMethod(modelID string, method string) bool

SupportsMethod 判断账户模型是否声明目标方法

func (*Account) SupportsModel

func (a *Account) SupportsModel(modelID string) bool

SupportsModel 判断账户实时目录是否包含模型

type AccountCandidateGroups

type AccountCandidateGroups struct {
	WarmReady        []string
	WarmAvailable    []string
	WarmBusy         []string
	StandbyReady     []string
	StandbyBusy      []string
	EarliestCooldown CooldownState
	Eligible         bool
}

AccountCandidateGroups 表示 warm 与 standby 账户的实时可调度状态

type AccountCandidateState

type AccountCandidateState struct {
	ModelAccess ModelAccessState
}

AccountCandidateState 表示账户候选的模型资格状态

type AccountConfig

type AccountConfig struct {
	Label    string `json:"label"`
	Note     string `json:"note,omitempty"`
	Enabled  bool   `json:"enabled"`
	Proxy    string `json:"proxy"`
	Locale   string `json:"locale"`
	Timezone string `json:"timezone"`
	AuthUser int    `json:"auth_user,omitempty"`
}

AccountConfig 表示账户目录中的固定最小配置

func DefaultAccountConfig

func DefaultAccountConfig(label string) AccountConfig

DefaultAccountConfig 返回新账户的最小配置,语言与时区由调用方按出口位置填写

func (AccountConfig) Validate

func (c AccountConfig) Validate() error

Validate 校验账户固定配置

type AccountLease

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

AccountLease 表示一个账户请求槽位

func AccountLeaseFromContext

func AccountLeaseFromContext(ctx context.Context) (*AccountLease, bool)

AccountLeaseFromContext 返回当前请求唯一的账户租约

func (*AccountLease) Account

func (l *AccountLease) Account() *Account

Account 返回当前租约持有的账户

func (*AccountLease) AfterRelease added in v0.3.11

func (l *AccountLease) AfterRelease(run func())

AfterRelease 在租约归还后于后台执行 run,租约已归还时立即在后台执行

func (*AccountLease) AuthGeneration added in v0.2.17

func (l *AccountLease) AuthGeneration() uint64

AuthGeneration 返回账户当前的认证版本号

func (*AccountLease) BeginAuthRefresh

func (l *AccountLease) BeginAuthRefresh() (func(), bool)

BeginAuthRefresh 为当前账户取得认证刷新独占窗口

func (*AccountLease) BeginOpeningWait added in v0.3.1

func (l *AccountLease) BeginOpeningWait() func()

BeginOpeningWait 把租约标记为等待 Worker 启动占位,返回的函数在等待结束后撤销标记

func (*AccountLease) BindFileResource

func (l *AccountLease) BindFileResource(ctx context.Context, file FileRef, metadata FileMetadata) error

BindFileResource 保存上传文件的账户绑定与公开元数据,metadata 提供大小、用途、公开文件名、摘要、视频时长、创建时间与到期时间,创建时间为零时取当前时间

func (*AccountLease) BindVideoOperation

func (l *AccountLease) BindVideoOperation(
	ctx context.Context,
	resourceID string,
	metadata VideoResourceMetadata,
) (ResourceBinding, error)

BindVideoOperation 保存视频任务账户与公开对象元数据

func (*AccountLease) BindVideoResult added in v0.2.14

func (l *AccountLease) BindVideoResult(ctx context.Context, operationID string, fileID string) error

BindVideoResult 保存视频任务可下载的结果文件并绑定该文件

func (*AccountLease) Channel added in v0.2.0

func (l *AccountLease) Channel() Channel

Channel 返回租约本次使用的上游通道

func (*AccountLease) CheckedAt

func (l *AccountLease) CheckedAt() time.Time

CheckedAt 返回当前账户请求取得租约的时间

func (*AccountLease) ConfirmAuthenticationFailure added in v0.2.18

func (l *AccountLease) ConfirmAuthenticationFailure(ctx context.Context, cause error) error

ConfirmAuthenticationFailure 在官网页面确认账户会话失效时保存 cause 对应的认证失败状态,会话有效时账户状态不变

func (*AccountLease) CooldownScope added in v0.2.0

func (l *AccountLease) CooldownScope(scope string) string

CooldownScope 返回租约通道在模型作用域上的冷却键

func (*AccountLease) CoolingDown added in v0.1.6

func (l *AccountLease) CoolingDown(modelID string) bool

CoolingDown 返回租约账户当前是否处于全局或指定模型的冷却

func (*AccountLease) InteractionRoute added in v0.3.14

func (l *AccountLease) InteractionRoute(modelID string) InteractionRouting

InteractionRoute 返回模型在租约账户与当前通道上的 Interaction 选路

func (*AccountLease) MarkAuthenticationValid

func (l *AccountLease) MarkAuthenticationValid() error

MarkAuthenticationValid 保存当前租约确认的认证成功状态

func (*AccountLease) MergeSetCookieHeaders

func (l *AccountLease) MergeSetCookieHeaders(headers []string, requestURL string, now time.Time) error

MergeSetCookieHeaders 将响应 Cookie 合并到账户最新持久状态

func (*AccountLease) Model added in v0.3.14

func (l *AccountLease) Model(modelID string) (Model, bool)

Model 返回租约账户实时目录中的模型

func (*AccountLease) ModelAccessGeneration

func (l *AccountLease) ModelAccessGeneration() uint64

ModelAccessGeneration 返回租约开始时的模型资格目录版本号

func (*AccountLease) ProofDone added in v0.3.10

func (l *AccountLease) ProofDone()

ProofDone 记录生成租约已取完 proof,账户不再为它排队取 proof

func (*AccountLease) RefreshStorageState

func (l *AccountLease) RefreshStorageState(
	generation uint64,
	update func(*StorageState) error,
	prepareCommit func() error,
) error

RefreshStorageState 为 generation 下失效的认证提交一次新认证,generation 之后已有提交时直接复用;prepareCommit 在写入新认证前执行

func (*AccountLease) Release

func (l *AccountLease) Release() error

Release 释放账户文件和进程内租约

func (*AccountLease) ReloadStorageState

func (l *AccountLease) ReloadStorageState() (StorageState, error)

ReloadStorageState 在租约内重新读取认证状态

func (*AccountLease) ReplaceCookies

func (l *AccountLease) ReplaceCookies(cookies []StateCookie) error

ReplaceCookies 以固定指纹浏览器当前 Cookie 替换账户最新持久状态,只有轮换 Cookie 变化且磁盘状态在 rotatingCookieWriteInterval 内写过时不写盘

func (*AccountLease) ReplaceResource

func (l *AccountLease) ReplaceResource(previousResourceID string, resourceID string, kind string) error

ReplaceResource 原子替换当前租约账户的单个资源绑定

func (*AccountLease) Retain added in v0.3.5

func (l *AccountLease) Retain() func() error

Retain 让租约在返回的函数调用前保持占用,期间的 Release 推迟到该函数调用时生效

func (*AccountLease) SaveConfig

func (l *AccountLease) SaveConfig(value AccountConfig) error

SaveConfig 在租约内原子写回账户固定配置

func (*AccountLease) SaveStorageState

func (l *AccountLease) SaveStorageState(state StorageState) error

SaveStorageState 在租约内原子写回认证状态

func (*AccountLease) VideoOperationBinding

func (l *AccountLease) VideoOperationBinding(resourceID string) (ResourceBinding, error)

VideoOperationBinding 返回当前账户持有的视频任务元数据

func (*AccountLease) WaitForAuthRefresh added in v0.2.3

func (l *AccountLease) WaitForAuthRefresh(ctx context.Context, generation uint64) error

WaitForAuthRefresh 等待其他正常请求释放,或等到 generation 之后已经提交的新认证;等待 Worker 启动占位的租约不算正常请求

type AccountLoadFailure added in v0.3.11

type AccountLoadFailure struct {
	ID        string
	Directory string
	Err       error
}

AccountLoadFailure 是一个无法载入的账户目录与原因

type AccountPool

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

AccountPool 在账户之间执行能力与并发槽位调度

func NewAccountPool

func NewAccountPool(accounts []*Account, perAccountConcurrency int) *AccountPool

NewAccountPool 创建账户独占调度池

func (*AccountPool) Account

func (p *AccountPool) Account(accountID string) (*Account, error)

Account 返回稳定 ID 对应的账户

func (*AccountPool) AccountChannelAvailable added in v0.2.0

func (p *AccountPool) AccountChannelAvailable(accountID string, selection AccountSelection) bool

AccountChannelAvailable 返回账户是否还有支持选择且未冷却的通道

func (*AccountPool) AccountCoolingDown added in v0.1.6

func (p *AccountPool) AccountCoolingDown(accountID string, modelID string) bool

AccountCoolingDown 返回账户当前是否处于全局或指定模型的冷却

func (*AccountPool) AccountsMissingBuildCatalog added in v0.3.15

func (p *AccountPool) AccountsMissingBuildCatalog() []string

AccountsMissingBuildCatalog 返回启用、可同步且尚未缓存 Build 模型目录的账户 ID

func (*AccountPool) AcquireAccount

func (p *AccountPool) AcquireAccount(ctx context.Context, accountID string) (*AccountLease, error)

AcquireAccount 为管理操作获取不受调度状态限制的指定账户租约

func (*AccountPool) AcquireFor

func (p *AccountPool) AcquireFor(ctx context.Context, selection AccountSelection) (*AccountLease, error)

AcquireFor 按模型方法账户或资源粘性获取账户槽位

func (*AccountPool) AcquireResource

func (p *AccountPool) AcquireResource(ctx context.Context, resourceID string) (*AccountLease, error)

AcquireResource 获取创建资源的固定账户

func (*AccountPool) Activity added in v0.1.6

func (p *AccountPool) Activity(accountID string) (bool, time.Time)

Activity 返回账户是否存在活动租约或独占操作及最近使用时间

func (*AccountPool) Add

func (p *AccountPool) Add(account *Account) (resultErr error)

Add 将新账户加入当前调度池

func (*AccountPool) AssistantModel added in v0.2.13

func (p *AccountPool) AssistantModel(modelID string) bool

AssistantModel 判断模型是否为经 Build 写代码助手生成的 -build 模型

func (*AccountPool) BidiMethod added in v0.2.8

func (p *AccountPool) BidiMethod(modelID string) string

BidiMethod 返回模型的实时方法:Build 目录以 bidiGenerateMusic 提供的模型为实时音乐,其余为 bidiGenerateContent

func (*AccountPool) BindResourceKind

func (p *AccountPool) BindResourceKind(resourceID string, accountID string, kind string) error

BindResourceKind 将带类型的资源 ID 固定到创建账户

func (*AccountPool) BootstrapModel

func (p *AccountPool) BootstrapModel(accountID string) (string, error)

BootstrapModel 返回账户使用的通用 WAA 初始化模型,账户还没有目录时为 preferredBootstrapModelID,由首次页面载入取得目录

func (*AccountPool) BootstrapModels

func (p *AccountPool) BootstrapModels(accountID string) ([]string, error)

BootstrapModels 返回账户实时目录中的 WAA 初始化模型

func (*AccountPool) BuildEnabled added in v0.2.0

func (p *AccountPool) BuildEnabled() bool

BuildEnabled 返回 Build 通道是否启用

func (*AccountPool) ByBenefitTier added in v0.3.5

func (p *AccountPool) ByBenefitTier(accountIDs []string) []string

ByBenefitTier 把账户按权益从高到低稳定排序,同权益保持传入顺序

func (*AccountPool) CandidateStates

func (p *AccountPool) CandidateStates(accountIDs []string, modelID string) map[string]AccountCandidateState

CandidateStates 返回候选账户的模型资格状态

func (*AccountPool) CandidateStatesForScope

func (p *AccountPool) CandidateStatesForScope(
	accountIDs []string,
	modelID string,
	modelAccessScope string,
) map[string]AccountCandidateState

CandidateStatesForScope 返回指定资格范围的候选账户状态

func (*AccountPool) CanonicalModelID added in v0.1.6

func (p *AccountPool) CanonicalModelID(modelID string) string

CanonicalModelID 把实时目录中的模型别名换成上游接受的正式模型 ID

func (*AccountPool) CatalogModels added in v0.2.0

func (p *AccountPool) CatalogModels(models []Model) []Model

CatalogModels 返回完整目录,每项带有启用账户可以调用的通道,按 callableFirst 排列

func (*AccountPool) Changed added in v0.1.6

func (p *AccountPool) Changed() <-chan struct{}

Changed 返回账户池下一次租约或状态变化时关闭的通道

func (*AccountPool) ClassifyCandidates

func (p *AccountPool) ClassifyCandidates(
	ctx context.Context,
	selection AccountSelection,
	warmAccountIDs []string,
) (AccountCandidateGroups, error)

ClassifyCandidates 按 warm 集合分类目标请求的候选账户

func (*AccountPool) ClearAccountState added in v0.3.13

func (p *AccountPool) ClearAccountState(accountID string) error

ClearAccountState 清除账户的服务受限、全局冷却与需要重新登录的标记并删除 runtime-state.json 中的受限与全局冷却记录,各模型的冷却保留,启用的账户回到就绪

func (*AccountPool) ClearCooldown added in v0.2.14

func (p *AccountPool) ClearCooldown(accountID string, scope string) error

ClearCooldown 清除账户在作用域上的冷却,作用域为全局 *、模型 ID 或 build:<模型 ID>

func (*AccountPool) ClearCooldownIfGeneration

func (p *AccountPool) ClearCooldownIfGeneration(
	accountID string,
	modelAccessScope string,
	generation uint64,
	checkedAt time.Time,
) error

ClearCooldownIfGeneration 清除当前目录版本下的作用域冷却

func (*AccountPool) ClearHiddenModels added in v0.3.15

func (p *AccountPool) ClearHiddenModels() []string

ClearHiddenModels 从全部账户的内存目录与隐藏模型记录中移除官网隐藏模型,返回发生变化的账户 ID

func (*AccountPool) ClearPageCooldownIfGeneration added in v0.3.9

func (p *AccountPool) ClearPageCooldownIfGeneration(accountID string, generation uint64, checkedAt time.Time) error

ClearPageCooldownIfGeneration 在账户页面载入成功后清除当前目录版本下的全局冷却,上游额度冷却保留到恢复时间

func (*AccountPool) EnabledAccounts added in v0.1.6

func (p *AccountPool) EnabledAccounts() []string

EnabledAccounts 返回已启用账户 ID

func (*AccountPool) FileMetadata

func (p *AccountPool) FileMetadata(ctx context.Context, fileID string) (FileMetadata, error)

FileMetadata 返回 runtime-state 中的公开文件元数据

func (*AccountPool) ForgetModelAccessVerifiedIfGeneration

func (p *AccountPool) ForgetModelAccessVerifiedIfGeneration(
	accountID string,
	modelID string,
	generation uint64,
	checkedAt time.Time,
) (bool, error)

ForgetModelAccessVerifiedIfGeneration 删除当前目录版本下过期的模型成功记录

func (*AccountPool) InlineMediaAccount added in v0.3.0

func (p *AccountPool) InlineMediaAccount(contents []Content) string

InlineMediaAccount 返回已上传 contents 中最多未过期内联附件的可用账户,没有符合条件的账户时返回空串

func (*AccountPool) ListFiles added in v0.2.8

func (p *AccountPool) ListFiles(ctx context.Context) ([]FileMetadata, error)

ListFiles 刷新全部账户 runtime-state 后返回公开上传文件,按创建时间从新到旧排列

func (*AccountPool) MarkAuthRequired

func (p *AccountPool) MarkAuthRequired(accountID string, reason string) error

MarkAuthRequired 将账户标记为需要重新登录

func (*AccountPool) MarkCooldownIfGeneration

func (p *AccountPool) MarkCooldownIfGeneration(
	accountID string,
	modelAccessScope string,
	generation uint64,
	checkedAt time.Time,
	until time.Time,
	reason string,
) error

MarkCooldownIfGeneration 保存当前目录版本下的作用域冷却,同范围已有更晚恢复的冷却时保留它

func (*AccountPool) MarkModelAccessVerifiedIfGeneration

func (p *AccountPool) MarkModelAccessVerifiedIfGeneration(
	accountID string,
	modelID string,
	generation uint64,
	checkedAt time.Time,
) (bool, error)

MarkModelAccessVerifiedIfGeneration 保存当前目录版本下的模型生成成功记录

func (*AccountPool) MarkQuotaCooldownIfGeneration added in v0.2.11

func (p *AccountPool) MarkQuotaCooldownIfGeneration(
	accountID string,
	modelAccessScope string,
	generation uint64,
	checkedAt time.Time,
	cooldown QuotaCooldown,
) (time.Time, bool, error)

MarkQuotaCooldownIfGeneration 保存当前目录版本下检查时间为 checkedAt 的额度冷却,递增冷却按同范围上一次冷却计算,同范围已有恢复更晚的冷却或恢复时刻相差不到一分钟的套餐限额冷却时保留它,套餐限额或每日限额冷却期间的其他额度失败只冷却回退选号,换成恢复更晚的同类冷却时回退选号的冷却保留;返回该冷却的恢复时刻与冷却是否因此改变,结果早于已记录的检查时间时恢复时刻为零值

func (*AccountPool) MarkReady

func (p *AccountPool) MarkReady(accountID string) error

MarkReady 将账户恢复为可调度状态

func (*AccountPool) MarkRestricted added in v0.3.7

func (p *AccountPool) MarkRestricted(accountID string, denial *camoufoxnative.AccessDenial) error

MarkRestricted 把账户标为服务受限并把原因写入 runtime-state.json,之后不再为该账户载入页面;目录同步成功时恢复,上游要求验证账户的受限只在刷新账户状态时的生成请求不再被要求验证后恢复

func (*AccountPool) MergeSetCookieHeaders added in v0.3.14

func (p *AccountPool) MergeSetCookieHeaders(accountID string, headers []string, requestURL string, now time.Time) error

MergeSetCookieHeaders 将响应 Cookie 合并到账户最新持久状态

func (*AccountPool) MissingModel added in v0.3.0

func (p *AccountPool) MissingModel(modelID string) bool

MissingModel 判断已载入的实时目录中没有该模型,请求会以 ErrModelNotFound 失败

func (*AccountPool) ModelAccessGeneration

func (p *AccountPool) ModelAccessGeneration(accountID string) uint64

ModelAccessGeneration 返回账户当前模型资格目录版本号

func (*AccountPool) NoEligibleError added in v0.1.5

func (p *AccountPool) NoEligibleError(selection AccountSelection) error

NoEligibleError 返回列出候选账户不可调度原因的无账户错误

func (*AccountPool) OrderCandidates

func (p *AccountPool) OrderCandidates(accountIDs []string, modelAccessScope string) []string

OrderCandidates 按当前策略排列候选账户而不推进轮询位置

func (*AccountPool) OutputContinuationRounds added in v0.2.10

func (p *AccountPool) OutputContinuationRounds(modelID string, maxOutputTokens *int64) int

OutputContinuationRounds 返回请求按官网自动续写需要的轮数,不需要续写时为 1

func (*AccountPool) PlaygroundEnabled added in v0.2.12

func (p *AccountPool) PlaygroundEnabled() bool

PlaygroundEnabled 返回 Playground 通道是否启用

func (*AccountPool) PreferWarmPool

func (p *AccountPool) PreferWarmPool(accountIDs []string, warm []string) []string

PreferWarmPool 按权益分层轮选初始热账户,round-robin 优先尚无或较少热账户的权益层,同层按覆盖度、当日用量少与最久未用优先,fill-first 时 ACCOUNT_ORDER 列出的账户在前

func (*AccountPool) PublicModels added in v0.2.10

func (p *AccountPool) PublicModels(models []Model) []Model

PublicModels 返回已启用通道可以提供的目录项,只因账户权益不足而无法调用的模型同样列出且通道为空,按 callableFirst 排列

func (*AccountPool) ReloadStorageState added in v0.3.14

func (p *AccountPool) ReloadStorageState(accountID string) (StorageState, error)

ReloadStorageState 重新读取账户的认证状态

func (*AccountPool) Remove

func (p *AccountPool) Remove(accountID string, deleteDirectory func(*Account) error) (*Account, error)

Remove 在账户空闲时删除持久目录并移出调度池

func (*AccountPool) ResetModelAccess

func (p *AccountPool) ResetModelAccess(accountID string) error

ResetModelAccess 清空账户的实测模型资格

func (*AccountPool) ResourceIDForContents

func (pool *AccountPool) ResourceIDForContents(ctx context.Context, contents []Content) (string, error)

ResourceIDForContents 校验全部文件引用并返回首个资源供生成账户选择

func (*AccountPool) SaveCatalogCache added in v0.2.17

func (p *AccountPool) SaveCatalogCache(accountID string, source json.RawMessage) error

SaveCatalogCache 把账户的 ListModels 响应、官网隐藏模型、当前 Build 模型目录与同步时刻写入账户目录的 catalog.json

func (*AccountPool) ScopedSelection added in v0.3.11

func (p *AccountPool) ScopedSelection(ctx context.Context, selection AccountSelection) AccountSelection

ScopedSelection 把请求指定的账户、所用 API key 与模型绑定的账户并入选择,指定账户与绑定资源的选择不受模型绑定限制

func (*AccountPool) SeedUsage added in v0.3.15

func (p *AccountPool) SeedUsage(seed AccountUsageSeed)

SeedUsage 把启动或换代时从请求账本读回的最近使用时间与当日请求数注入账户池

func (*AccountPool) SetAPIKeyAccounts added in v0.2.19

func (p *AccountPool) SetAPIKeyAccounts(accounts map[string][]string)

SetAPIKeyAccounts 设置各 API key 可用的账户 ID,未列出的 key 可用全部账户

func (*AccountPool) SetAccountOrder added in v0.3.3

func (p *AccountPool) SetAccountOrder(accountIDs []string)

SetAccountOrder 设置 fill-first 依次使用的账户 ID

func (*AccountPool) SetBuildCatalog added in v0.2.0

func (p *AccountPool) SetBuildCatalog(accountID string, models []Model) error

SetBuildCatalog 保存账户 Build 代理返回的 Gemini API 模型目录

func (*AccountPool) SetCatalog

func (p *AccountPool) SetCatalog(accountID string, tier BenefitTier, models []Model) error

SetCatalog 替换账户的权益等级与实时模型目录

func (*AccountPool) SetEnabled added in v0.3.4

func (p *AccountPool) SetEnabled(accountID string, enabled bool) (*Account, error)

SetEnabled 写回账户启用状态并立即生效,不等待账户上的在途请求

func (*AccountPool) SetHiddenModels added in v0.3.7

func (p *AccountPool) SetHiddenModels(accountID string, hidden map[string]string, discovered bool) error

SetHiddenModels 记下账户目录中的官网隐藏模型与本次同步是否探测过官网隐藏模型,随下一次 SaveCatalogCache 写入

func (*AccountPool) SetModelAccounts added in v0.3.3

func (p *AccountPool) SetModelAccounts(accounts map[string][]string)

SetModelAccounts 设置模型可用的账户 ID,未列出的模型可用全部账户

func (*AccountPool) SetModelChannels added in v0.2.14

func (p *AccountPool) SetModelChannels(channels map[string]Channel)

SetModelChannels 设置模型限定使用的上游通道,键为模型 ID

func (*AccountPool) SetNote added in v0.3.14

func (p *AccountPool) SetNote(accountID string, note string) (*Account, error)

SetNote 写回账户备注并立即生效,不等待账户上的在途请求

func (*AccountPool) SetPerAccountConcurrency added in v0.2.11

func (p *AccountPool) SetPerAccountConcurrency(limit int)

SetPerAccountConcurrency 设置单账户同时处理的请求数并唤醒等待中的请求

func (*AccountPool) SetRefreshStep added in v0.3.13

func (p *AccountPool) SetRefreshStep(accountID string, step AccountStep, index, total int)

SetRefreshStep 记录立即刷新进入第 index 步 step,共 total 步,step 为空表示刷新结束

func (*AccountPool) SetRoutingStrategy

func (p *AccountPool) SetRoutingStrategy(strategy string)

SetRoutingStrategy 设置账户轮询或优先填满策略

func (*AccountPool) SetSessionCheck added in v0.2.18

func (p *AccountPool) SetSessionCheck(check func(context.Context, *Account) error)

SetSessionCheck 设置认证失败后确认账户会话是否失效的检查

func (*AccountPool) SetTransition added in v0.3.4

func (p *AccountPool) SetTransition(accountID string, operation AccountTransition, step AccountStep)

SetTransition 记录停用收尾、目录同步或账户保存进行到的步骤,operation 为空表示结束

func (*AccountPool) SetUpstreamChannels added in v0.2.0

func (p *AccountPool) SetUpstreamChannels(channels []Channel)

SetUpstreamChannels 设置生成请求按顺序启用的上游通道

func (*AccountPool) SlotBusy added in v0.3.13

func (p *AccountPool) SlotBusy(accountID string) bool

SlotBusy 表示账户此刻没有空闲的普通槽位,取槽位的操作要等在途请求结束;账户不存在时为 false

func (*AccountPool) Status

func (p *AccountPool) Status() []AccountStatus

Status 返回账户池的脱敏状态

func (*AccountPool) TryAcquireFor

func (p *AccountPool) TryAcquireFor(ctx context.Context, selection AccountSelection) (*AccountLease, bool, error)

TryAcquireFor 尝试获取账户槽位并立即返回当前结果

func (*AccountPool) VerificationRequired added in v0.3.14

func (p *AccountPool) VerificationRequired(accountID string) bool

VerificationRequired 判断账户是否因上游要求验证而受限

func (*AccountPool) WithoutPendingProofs added in v0.3.10

func (p *AccountPool) WithoutPendingProofs(accountIDs []string) []string

WithoutPendingProofs 返回 accountIDs 中没有生成租约在等待或生成 proof 的账户,保持原顺序

type AccountPublishLease

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

AccountPublishLease 保护新账户从稳定目录发布到运行时

func (*AccountPublishLease) Release

func (lease *AccountPublishLease) Release() error

Release 结束新账户运行时发布窗口

type AccountRefresh added in v0.2.11

type AccountRefresh struct {
	PreviousTier   BenefitTier
	Tier           BenefitTier
	PreviousModels int
	Models         int
	ModelsChanged  bool
	Skipped        bool
}

AccountRefresh 为一次账户状态刷新前后的权益与模型数,ModelsChanged 表示该账户的目录条目有变化

type AccountRuntimeLease

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

AccountRuntimeLease 保证同一邮箱只有一个 WAA runtime

func AcquireAccountRuntimeLease

func AcquireAccountRuntimeLease(accountID string) (*AccountRuntimeLease, error)

AcquireAccountRuntimeLease 锁定当前用户下的账户 WAA runtime

func (*AccountRuntimeLease) Release

func (lease *AccountRuntimeLease) Release() error

Release 释放账户 WAA runtime 锁

type AccountSelection

type AccountSelection struct {
	ModelID           string
	ModelAccessScope  string
	Method            string
	Capability        string
	AccountID         string
	ResourceID        string
	AllowedAccountIDs []string
	// PreferredAccountID 是可用时先于其他账户选择的账户
	PreferredAccountID string
	PlaygroundOnly     bool
	Channel            Channel
	PreferredChannel   Channel
	// IgnoreQuotaCooldown 为 true 时套餐限额、每日限额与权限拒绝冷却中的账户照常参与选号,拒绝记录有效期内拒绝过不大于 RequestSize 的请求的账户除外,余量多的账户优先
	IgnoreQuotaCooldown bool
	// RequestSize 是请求输入正文的字节数,0 表示未知
	RequestSize int64
	// contains filtered or unexported fields
}

AccountSelection 描述账户调度所需的能力或粘性条件

type AccountState

type AccountState string

AccountState 表示账户当前是否可调度

const (
	// AccountReady 表示账户可以接收请求
	AccountReady AccountState = "ready"
	// AccountBusy 表示账户存在活动请求
	AccountBusy AccountState = "busy"
	// AccountCooldown 表示账户或模型处于冷却期
	AccountCooldown AccountState = "cooldown"
	// AccountAuthRequired 表示账户需要重新登录
	AccountAuthRequired AccountState = "auth_required"
	// AccountRestricted 表示 Google 拒绝该账户使用 AI Studio
	AccountRestricted AccountState = "restricted"
	// AccountUnavailable 表示账户初始化或运行失败
	AccountUnavailable AccountState = "unavailable"
	// AccountDisabled 表示账户已停用
	AccountDisabled AccountState = "disabled"
)

type AccountStatus

type AccountStatus struct {
	ID          string                   `json:"id"`
	Label       string                   `json:"label"`
	Note        string                   `json:"note,omitempty"`
	State       AccountState             `json:"state"`
	Enabled     bool                     `json:"enabled"`
	Proxy       string                   `json:"proxy"`
	Egress      string                   `json:"egress"`
	Locale      string                   `json:"locale"`
	Timezone    string                   `json:"timezone"`
	Models      []string                 `json:"models"`
	BenefitTier string                   `json:"benefit_tier"`
	Cooldowns   map[string]CooldownState `json:"-"`
	LastUsed    *time.Time               `json:"last_used,omitempty"`
	Message     string                   `json:"message,omitempty"`
	Directory   string                   `json:"-"`
	// Transition 是账户正在进行的后台操作,没有时为空
	Transition AccountTransition `json:"-"`
	// TransitionStep 是后台操作当前的步骤,操作没有分步时为空
	TransitionStep AccountStep `json:"-"`
	// TransitionIndex 与 TransitionTotal 是立即刷新当前步骤的序号与步数,其他操作为 0
	TransitionIndex int `json:"-"`
	TransitionTotal int `json:"-"`
	// TransitionSince 是进入当前操作或步骤的时刻
	TransitionSince time.Time `json:"-"`
	// ActiveRequests 是账户上进行中的请求数
	ActiveRequests int `json:"-"`
	// CatalogError 是已有目录的账户最近一次权益或目录读取失败的原因,下一次读取成功后为空
	CatalogError string `json:"-"`
	// CatalogSyncedAt 是目录缓存最近一次同步的时刻,没有一致的缓存时为零值
	CatalogSyncedAt time.Time `json:"-"`
	// HiddenDiscovered 表示账户目录同步时探测过官网隐藏模型,HiddenModels 是目录中的官网隐藏模型数
	HiddenDiscovered bool `json:"-"`
	HiddenModels     int  `json:"-"`
	// VerificationRequired 表示账户因上游要求验证而受限,可在官网验证页完成验证后恢复
	VerificationRequired bool `json:"verification_required,omitempty"`
	// DeviceBoundSession 表示账户会话带 __Secure-1PSIDRTS 且缺少本地续签材料,约 2 小时内失效
	DeviceBoundSession bool `json:"device_bound_session,omitempty"`
}

AccountStatus 表示管理界面使用的脱敏账户状态

type AccountStep added in v0.3.13

type AccountStep string

AccountStep 是后台操作当前的步骤

const (
	// AccountStepWaiting 表示操作正在等账户的在途请求结束
	AccountStepWaiting AccountStep = "waiting"
	// AccountStepCatalog 表示正在载入页面读取权益与模型目录
	AccountStepCatalog AccountStep = "catalog"
	// AccountStepVerifying 表示正在发一次生成请求核对验证状态
	AccountStepVerifying AccountStep = "verifying"
)

type AccountStore

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

AccountStore 从一个或多个账户文件或目录加载账户

func NewAccountStore

func NewAccountStore(paths ...string) *AccountStore

NewAccountStore 创建账户目录存储

func (*AccountStore) Create

func (s *AccountStore) Create(accountConfig AccountConfig, state StorageState) (*Account, *AccountPublishLease, error)

Create 创建并锁定以认证邮箱命名的账户目录

func (*AccountStore) Delete

func (s *AccountStore) Delete(account *Account) error

Delete 删除账户的稳定目录

func (*AccountStore) DeleteFailure added in v0.3.11

func (s *AccountStore) DeleteFailure(id string) (bool, error)

DeleteFailure 删除无法载入的账户目录 id,返回它是否是无法载入的账户目录

func (*AccountStore) Failures added in v0.3.11

func (s *AccountStore) Failures() []AccountLoadFailure

Failures 返回最近一次 Load 中无法载入、尚未删除的账户目录

func (*AccountStore) Load

func (s *AccountStore) Load() ([]*Account, error)

Load 扫描账户目录并恢复冷却与资源粘性,无法载入的账户目录跳过并记入 Failures

func (*AccountStore) RecordRestrictedImport added in v0.3.7

func (s *AccountStore) RecordRestrictedImport(email string, reason string) error

RecordRestrictedImport 在账户根目录记下导入时被 Google 限制使用 AI Studio 的账户邮箱与原因

func (*AccountStore) RestrictedImports added in v0.3.7

func (s *AccountStore) RestrictedImports() (map[string]string, error)

RestrictedImports 返回账户根目录中记下的导入时被 Google 限制使用 AI Studio 的账户小写邮箱与原因,没有单一账户根目录时为空

type AccountTransition added in v0.3.4

type AccountTransition string

AccountTransition 是账户正在进行的后台操作

const (
	// AccountDraining 表示账户已停用,正在等待在途请求结束并关闭 Worker
	AccountDraining AccountTransition = "draining"
	// AccountSyncing 表示账户已启用、添加、导入或重新登录,正在载入页面同步模型目录
	AccountSyncing AccountTransition = "syncing"
	// AccountSaving 表示正在保存账户配置或登录状态
	AccountSaving AccountTransition = "saving"
	// AccountRefreshing 表示正在立即刷新账户
	AccountRefreshing AccountTransition = "refreshing"
)

type AccountUsageEntry added in v0.3.15

type AccountUsageEntry struct {
	Account  string
	Model    string
	Channel  Channel
	LastUsed time.Time
}

AccountUsageEntry 表示单个账户在指定模型与通道上的最近使用时刻

type AccountUsageSeed added in v0.3.15

type AccountUsageSeed struct {
	Entries          []AccountUsageEntry
	QuotaDayStart    time.Time
	QuotaDayRequests map[string]int64
}

AccountUsageSeed 保存启动或换代时注入账户池的历史使用信息

type AccountVerifyDriver added in v0.3.14

type AccountVerifyDriver interface {
	Verify(context.Context, AccountVerifyRequest) (bool, error)
}

AccountVerifyDriver 定义在独立浏览器中打开账户验证页并自动再核对的能力

type AccountVerifyRequest added in v0.3.14

type AccountVerifyRequest struct {
	Directory         string
	StorageState      StorageState
	AuthUser          int
	Proxy             string
	Locale            string
	Timezone          string
	View              *camoufoxnative.LiveView
	CheckVerification func(context.Context, StorageState) (bool, error)
	OnVerifyStep      func(string)
	PollInterval      time.Duration
}

AccountVerifyRequest 描述在独立浏览器中打开账户验证页所需的环境与核对回调

type AccountsNotReadyError added in v0.1.5

type AccountsNotReadyError struct {
	Reasons []string
	// States 是各不可调度账户的状态,与 Reasons 一一对应,停用的账户为 AccountDisabled
	States []AccountState
}

AccountsNotReadyError 表示支持请求的账户都处于不可调度状态

func (*AccountsNotReadyError) Error added in v0.1.5

func (e *AccountsNotReadyError) Error() string

func (*AccountsNotReadyError) Unwrap added in v0.1.5

func (e *AccountsNotReadyError) Unwrap() error

type AgentConfig added in v0.3.0

type AgentConfig struct {
	Type                  string `json:"type,omitempty"`
	Model                 string `json:"model,omitempty"`
	MaxTotalTokens        int64  `json:"max_total_tokens,omitempty"`
	ThinkingSummaries     string `json:"thinking_summaries,omitempty"`
	Visualization         string `json:"visualization,omitempty"`
	CollaborativePlanning bool   `json:"collaborative_planning,omitempty"`
}

AgentConfig 是 Interactions API 的 agent_config:Antigravity 所用的模型与 token 上限,Deep Research 的思考摘要(auto、none)、可视化(auto、off)与协作规划,空值为官网默认

type AgentEnvironment added in v0.3.2

type AgentEnvironment struct {
	ID      string              `json:"id,omitempty"`
	Sources []EnvironmentSource `json:"sources,omitempty"`
	// Allowlist 为空时新环境按官网默认禁止出站,已有环境保持原网络设置
	Allowlist []EgressRule `json:"allowlist,omitempty"`
	// NetworkDisabled 表示禁止全部出站
	NetworkDisabled bool `json:"network_disabled,omitempty"`
}

AgentEnvironment 是 Interactions API 的 environment:ID 为已有环境,Sources 为挂载到环境中的源,Allowlist 为出站白名单

type AllCoolingError added in v0.1.7

type AllCoolingError struct {
	ModelID string
	Until   time.Time
	Reason  string
}

AllCoolingError 表示请求的全部候选账户都在冷却且不会很快恢复

func (*AllCoolingError) Error added in v0.1.7

func (e *AllCoolingError) Error() string

func (*AllCoolingError) ErrorCode added in v0.1.7

func (e *AllCoolingError) ErrorCode() string

ErrorCode 返回 OpenAI 兼容的额度错误代码,最早恢复的是权限拒绝冷却时为账户暂时不可用

func (*AllCoolingError) HTTPStatus added in v0.1.7

func (e *AllCoolingError) HTTPStatus() int

HTTPStatus 返回额度耗尽对应的 429,最早恢复的是权限拒绝冷却时返回账户暂时不可用的 503

func (*AllCoolingError) RetryAt added in v0.2.11

func (e *AllCoolingError) RetryAt(now time.Time) time.Time

RetryAt 返回最早恢复的时刻,最早恢复的是权限拒绝冷却且在一分钟之后时返回零值

type AppletProtectedRequest added in v0.3.8

type AppletProtectedRequest struct {
	Model      string
	Binding    string
	Digest     string
	ProofField int
}

AppletProtectedRequest 是 Build 应用与云项目 RPC 的 proof 参数:proof 绑定 Binding 的 SHA-256,Digest 非空时直接绑定 Digest

type AppletProtectedTransport added in v0.3.8

type AppletProtectedTransport interface {
	DoProtectedApplet(context.Context, AppletProtectedRequest, RPCRequest) (*RPCResponse, error)
}

AppletProtectedTransport 是能为 Build 应用与云项目 RPC 写入 fresh proof 的受保护传输

type AssistantService added in v0.3.0

type AssistantService interface {
	AssistantAccount(context.Context, GenerateRequest) string
}

AssistantService 是可以查询写代码助手对话所在账户的生成服务

type AssistantStreamDecoder added in v0.2.13

type AssistantStreamDecoder struct {
	// Functions 是请求声明的函数名,不为空时正文中的调用代码块解码为函数调用
	Functions []string
	// Reopen 以同一任务重新打开任务流
	Reopen func() (io.ReadCloser, error)
	// contains filtered or unexported fields
}

AssistantStreamDecoder 把写代码助手的步骤快照解码为增量事件

func (*AssistantStreamDecoder) Decode added in v0.2.13

func (d *AssistantStreamDecoder) Decode(raw json.RawMessage, path string) ([]Event, error)

Decode 解码一条消息 [null, null, [步骤...], trajectory ID]:步骤 field 1 为对话轮、6 为错误(状态为 3 时不终止任务)、10 为工具动作、12 为序号、13 为状态(1 完成、2 进行中、4 失败)、16 为用量

func (*AssistantStreamDecoder) End added in v0.2.13

func (d *AssistantStreamDecoder) End() ([]Event, error)

End 在本轮回复结束、函数调用之后模型继续输出正文或流结束时返回扣下的正文或函数调用、搜索来源、各步骤用量之和与完成事件

type AssistantUploader added in v0.2.13

type AssistantUploader interface {
	UploadAssistantFile(context.Context, string, Blob) (string, error)
}

AssistantUploader 以账户身份上传写代码助手附件并返回上传路径

type AuthExtension

type AuthExtension struct {
	Source AuthSource           `json:"source"`
	OAuth  *ChromeOAuthMaterial `json:"oauth,omitempty"`
	Bound  *BoundSession        `json:"bound_session,omitempty"`
}

AuthExtension 保存 aistudio2api 认证扩展

type AuthSource

type AuthSource struct {
	Browser string `json:"browser"`
	Root    string `json:"root,omitempty"`
	Profile string `json:"profile,omitempty"`
	Email   string `json:"email,omitempty"`
}

AuthSource 记录认证状态的来源

type BenefitTier

type BenefitTier int64

BenefitTier 表示 AI Studio 返回的账户权益等级

const (
	// BenefitTierFree 表示账户没有 Google AI 订阅权益
	BenefitTierFree BenefitTier = 0
	// BenefitTierPro 表示 Google AI Pro 权益
	BenefitTierPro BenefitTier = 1
	// BenefitTierUltra 表示 Google AI Ultra 权益
	BenefitTierUltra BenefitTier = 2
	// BenefitTierPlus 表示 Google AI Plus 权益
	BenefitTierPlus BenefitTier = 3
)

func DecodeBenefitTier added in v0.3.14

func DecodeBenefitTier(raw []byte) (BenefitTier, error)

DecodeBenefitTier 解码 GetAiStudioBenefitTier 响应正文为账户权益等级

func (BenefitTier) HeaderValue

func (tier BenefitTier) HeaderValue() string

HeaderValue 返回官网 RPC 使用的权益请求头值

func (BenefitTier) String

func (tier BenefitTier) String() string

String 返回账户权益的稳定显示名称

type BidiContextWindow added in v0.2.14

type BidiContextWindow struct {
	TriggerTokens int64 `json:"trigger_tokens"`
	TargetTokens  int64 `json:"target_tokens"`
}

BidiContextWindow 表示 Live 会话的滑动上下文窗口,上下文达到 TriggerTokens 时缩减到 TargetTokens

type BidiEvent

type BidiEvent struct {
	Kind          BidiEventKind      `json:"kind"`
	Text          string             `json:"text,omitempty"`
	Media         *Blob              `json:"media,omitempty"`
	Transcription *BidiTranscription `json:"transcription,omitempty"`
	ToolCall      *FunctionCall      `json:"tool_call,omitempty"`
	ToolCallIDs   []string           `json:"tool_call_ids,omitempty"`
	SessionToken  string             `json:"session_token,omitempty"`
	Resumable     bool               `json:"resumable,omitempty"`
	Raw           json.RawMessage    `json:"raw,omitempty"`
	Err           error              `json:"-"`
}

BidiEvent 保存按上游顺序输出的实时事件

func ParseBidiServerPayload

func ParseBidiServerPayload(raw json.RawMessage) ([]BidiEvent, error)

ParseBidiServerPayload 解码一条 WebChannel 业务 payload

func ParseBuildBidiServerPayload added in v0.2.8

func ParseBuildBidiServerPayload(raw json.RawMessage) ([]BidiEvent, error)

ParseBuildBidiServerPayload 解码 Build 代理 WebChannel 的一条业务 payload:状态、控制标记或 ProxyResponse 列表

type BidiEventKind

type BidiEventKind string

BidiEventKind 表示双向实时协议事件

const (
	// BidiEventSetupComplete 表示上游已接受会话配置
	BidiEventSetupComplete BidiEventKind = "setup_complete"
	// BidiEventText 表示模型文本增量
	BidiEventText BidiEventKind = "text"
	// BidiEventMedia 表示模型媒体增量
	BidiEventMedia BidiEventKind = "media"
	// BidiEventInputTranscription 表示输入转写增量
	BidiEventInputTranscription BidiEventKind = "input_transcription"
	// BidiEventOutputTranscription 表示输出转写增量
	BidiEventOutputTranscription BidiEventKind = "output_transcription"
	// BidiEventInterimInputTranscription 表示实时转录模型当前累计的临时输入转写
	BidiEventInterimInputTranscription BidiEventKind = "interim_input_transcription"
	// BidiEventGenerationComplete 表示当前生成已完成
	BidiEventGenerationComplete BidiEventKind = "generation_complete"
	// BidiEventTurnComplete 表示当前对话轮次已完成
	BidiEventTurnComplete BidiEventKind = "turn_complete"
	// BidiEventInterrupted 表示当前模型输出被打断
	BidiEventInterrupted BidiEventKind = "interrupted"
	// BidiEventToolCall 表示模型发起函数调用
	BidiEventToolCall BidiEventKind = "tool_call"
	// BidiEventToolCallCancellation 表示模型取消尚未完成的函数调用
	BidiEventToolCallCancellation BidiEventKind = "tool_call_cancellation"
	// BidiEventSessionResumption 表示上游更新恢复令牌
	BidiEventSessionResumption BidiEventKind = "session_resumption"
	// BidiEventGoAway 表示上游要求结束当前连接
	BidiEventGoAway BidiEventKind = "go_away"
	// BidiEventUsage 表示上游返回用量字段
	BidiEventUsage BidiEventKind = "usage"
	// BidiEventProvider 表示已保留的未归一化上游字段
	BidiEventProvider BidiEventKind = "provider"
	// BidiEventClosed 表示 WebChannel 已结束
	BidiEventClosed BidiEventKind = "closed"
	// BidiEventError 表示双向实时协议错误
	BidiEventError BidiEventKind = "error"
)

type BidiMode

type BidiMode string

BidiMode 区分 Gemini Live 与 Robotics Streaming 的独立会话配置

const (
	// BidiModeLive 表示音频输出的 Gemini Live 会话
	BidiModeLive BidiMode = "live"
	// BidiModeRobotics 表示文本输出的 Robotics Streaming 会话
	BidiModeRobotics BidiMode = "robotics"
)

type BidiProtectedTransport

type BidiProtectedTransport interface {
	OpenBidiProtected(context.Context, BidiRequest, RequestContext, *AccountLease, func() error) (*BidiSession, error)
}

BidiProtectedTransport 建立持有当前账户租约的 WebChannel 会话

type BidiRequest

type BidiRequest struct {
	Model string
	Mode  BidiMode
	// OutputModality 表示 Live 会话输出 audio 或 text
	OutputModality           string
	Translation              *BidiTranslationConfig
	Transcription            *BidiTranscriptionConfig
	Tools                    []FunctionDeclaration
	SystemInstruction        string
	Voice                    string
	MediaResolution          string
	ThinkingLevel            string
	ContextWindow            *BidiContextWindow
	GoogleSearch             bool
	AccountID                string
	AllowedAccountIDs        []string
	SessionToken             string
	ModelAccessScope         string
	RecoverWAARuntime        func(context.Context, string, error) (bool, error)
	ObserveWAARuntime        func(string, uint64)
	ObserveModelAccessChange func()
	ObserveAccountFailure    func(string, error)
	// contains filtered or unexported fields
}

BidiRequest 定义一条双向实时会话

type BidiService

type BidiService interface {
	OpenBidi(context.Context, BidiRequest) (*BidiSession, error)
}

BidiService 创建 Gemini Live 或 Robotics Streaming 会话

type BidiSession

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

BidiSession 保存一条 Google WebChannel 双向会话

func (*BidiSession) Channel added in v0.2.8

func (s *BidiSession) Channel() Channel

Channel 返回会话使用的上游通道

func (*BidiSession) Close

func (s *BidiSession) Close() error

Close 取消网络读取并等待账户租约释放

func (*BidiSession) Done

func (s *BidiSession) Done() <-chan struct{}

Done 在 WebChannel 释放账户后关闭

func (*BidiSession) Events

func (s *BidiSession) Events() <-chan BidiEvent

Events 返回上游按网络顺序产生的事件

func (*BidiSession) Model

func (s *BidiSession) Model() string

Model 返回会话使用的模型

func (*BidiSession) SendMedia

func (s *BidiSession) SendMedia(ctx context.Context, mimeType string, data []byte) error

SendMedia 把一条官网实时音频或图像输入帧排入前向通道,发送失败在后续调用返回

func (*BidiSession) SendMediaEnd

func (s *BidiSession) SendMediaEnd(ctx context.Context) error

SendMediaEnd 发送官网实时媒体结束帧并等待此前排队的媒体帧送达

func (*BidiSession) SendMusicConfig added in v0.2.8

func (s *BidiSession) SendMusicConfig(ctx context.Context, config json.RawMessage) error

SendMusicConfig 发送实时音乐的生成参数

func (*BidiSession) SendMusicPrompts added in v0.2.8

func (s *BidiSession) SendMusicPrompts(ctx context.Context, prompts []WeightedPrompt) error

SendMusicPrompts 发送实时音乐的加权提示词

func (*BidiSession) SendPlaybackControl added in v0.2.8

func (s *BidiSession) SendPlaybackControl(ctx context.Context, control string) error

SendPlaybackControl 发送实时音乐的播放控制

func (*BidiSession) SendText

func (s *BidiSession) SendText(ctx context.Context, text string) error

SendText 发送一条官网文本输入帧

func (*BidiSession) SendToolResponses

func (s *BidiSession) SendToolResponses(ctx context.Context, results []FunctionResult) error

SendToolResponses 发送官网函数响应帧

type BidiTranscription

type BidiTranscription struct {
	Text         string `json:"text"`
	Finished     bool   `json:"finished,omitempty"`
	DurationMS   int64  `json:"duration_ms,omitempty"`
	LanguageCode string `json:"language_code,omitempty"`
}

BidiTranscription 保存实时转写字段

type BidiTranscriptionConfig added in v0.2.0

type BidiTranscriptionConfig struct {
	LanguageCodes    []string `json:"language_codes,omitempty"`
	CustomVocabulary []string `json:"custom_vocabulary,omitempty"`
	Smart            bool     `json:"smart,omitempty"`
}

BidiTranscriptionConfig 表示实时转录模型的输入转录参数

type BidiTranslationConfig added in v0.2.0

type BidiTranslationConfig struct {
	TargetLanguageCode string `json:"target_language_code"`
	EchoTargetLanguage bool   `json:"echo_target_language,omitempty"`
}

BidiTranslationConfig 表示实时翻译模型的目标语言

type Blob

type Blob struct {
	MIME string `json:"mime"`
	Data []byte `json:"data"`
}

Blob 表示内联二进制内容

func NewBlob added in v0.3.10

func NewBlob(mime string, data []byte) *Blob

NewBlob 返回请求中由客户端提交、之后不再改写的附件,SHA256 第一次计算的摘要随附件保存,账户选择、轮次摘要与上传共用

func (*Blob) SHA256 added in v0.3.10

func (blob *Blob) SHA256() [sha256.Size]byte

SHA256 返回附件内容的 SHA-256:NewBlob 创建的附件只在第一次调用时计算,其余附件每次现算

type BoundSession added in v0.3.3

type BoundSession struct {
	ID          string   `json:"id"`
	RefreshURL  string   `json:"refresh_url"`
	Credentials []string `json:"credentials"`
}

BoundSession 是 OAuthMultilogin 登记的 Google DBSC 会话,以 OAuth 材料的设备绑定密钥刷新

type BuildProtectedTransport added in v0.2.8

type BuildProtectedTransport interface {
	DoProtectedBuild(context.Context, AccountSelection, string, RPCRequest) (*RPCResponse, error)
}

BuildProtectedTransport 原子完成 Build 代理请求的 fresh WAA proof、field 3 写入和同 context 发送,string 参数为写入页面的提示词

type BuildStreamDecoder added in v0.2.0

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

BuildStreamDecoder 把 Build 代理返回的 Gemini API 响应块转换为规范事件

func (*BuildStreamDecoder) Decode added in v0.2.0

func (d *BuildStreamDecoder) Decode(raw []byte) ([]Event, error)

Decode 解码一个 Gemini API GenerateContentResponse JSON

func (*BuildStreamDecoder) End added in v0.2.0

func (d *BuildStreamDecoder) End() error

End 校验流已经出现 finishReason

type Channel added in v0.2.0

type Channel string

Channel 表示生成请求的上游额度来源

const (
	// ChannelPlayground 表示官网 Playground 的 GenerateContent
	ChannelPlayground Channel = "playground"
	// ChannelBuild 表示官网 Build 应用代理的 Gemini API 调用
	ChannelBuild Channel = "build"
	// ChannelAssistant 表示官网 Build 写代码助手,只服务 -build 模型
	ChannelAssistant Channel = "assistant"
)

type ChromeOAuthMaterial

type ChromeOAuthMaterial struct {
	GaiaID            string `json:"gaia_id"`
	RefreshToken      string `json:"refresh_token"`
	WrappedBindingKey []byte `json:"wrapped_binding_key,omitempty"`
}

ChromeOAuthMaterial 保存 Chrome OAuth 续签材料,设备绑定密钥可为空

type Citation

type Citation struct {
	URL     string `json:"url"`
	Title   string `json:"title,omitempty"`
	Start   int    `json:"start,omitempty"`
	End     int    `json:"end,omitempty"`
	License string `json:"license,omitempty"`
}

Citation 表示模型返回的来源

type Client

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

Client 实现 AI Studio 私有协议核心

func NewClient

func NewClient(options ClientOptions) *Client

NewClient 创建协议客户端

func (*Client) ApplyPageCatalog added in v0.3.0

func (c *Client) ApplyPageCatalog(ctx context.Context, accountID string, page camoufoxnative.PageCatalog) (BenefitTier, []Model, error)

ApplyPageCatalog 以账户会话页面载入时的响应更新条款状态、权益与模型目录,账户尚未同意条款时按官网条款对话框发送 AcceptTerms,本进程同意过的账户不再发送

func (*Client) BuildModelsForAccount added in v0.2.0

func (c *Client) BuildModelsForAccount(ctx context.Context, accountID string) ([]Model, error)

BuildModelsForAccount 经 ProxyUnaryCall 读取账户 Build 代理的 Gemini API 模型目录

func (*Client) ClearHiddenModels added in v0.3.15

func (c *Client) ClearHiddenModels(accountID string)

ClearHiddenModels 从账户当前内存目录中移除官网隐藏模型

func (*Client) CountTokensForAccount

func (c *Client) CountTokensForAccount(ctx context.Context, accountID string, request TokenCountRequest) (TokenCount, error)

CountTokensForAccount 使用指定账户调用权威 token 计数,Build 租约经 Build 代理计数

func (*Client) CreateDecision added in v0.3.6

func (c *Client) CreateDecision(ctx context.Context, request DecisionRequest) (DecisionResult, error)

CreateDecision 发送 CreateDecision 并返回各问题的回答

func (*Client) DiscoverHiddenModels added in v0.3.7

func (c *Client) DiscoverHiddenModels(ctx context.Context, accountID string) (map[string]string, error)

DiscoverHiddenModels 从账户页面载入的官网前端主程序与对话页分块找出 ListModels 没有列出的推荐模型,经 CountTokens 确认可用后加入账户目录,返回隐藏模型 ID 到依据模型 ID 的映射

func (*Client) EnsureDisclaimerAcknowledged added in v0.2.14

func (c *Client) EnsureDisclaimerAcknowledged(ctx context.Context, accountID string, mode BidiMode) error

EnsureDisclaimerAcknowledged 读取账户的官网用户偏好,账户尚未确认该模式的首次使用提示时与官网对话框的 Acknowledge 一样发送 UpdateUserPreferences

func (*Client) Generate

func (c *Client) Generate(ctx context.Context, request GenerateRequest) (<-chan Event, error)

func (*Client) GenerateAccessToken

func (c *Client) GenerateAccessToken(ctx context.Context, accountID string) (string, error)

GenerateAccessToken 获取网页账户授权的短期 bearer token

func (*Client) GenerateImage added in v0.2.18

func (c *Client) GenerateImage(ctx context.Context, request ImageRequest) ([]GeneratedImage, error)

GenerateImage 按官网 Imagen 页发送 GenerateImage 并返回图片

func (*Client) GenerateTitle added in v0.2.15

func (c *Client) GenerateTitle(ctx context.Context, accountID string, request TitleRequest) (string, error)

GenerateTitle 按官网试用页发送 GenerateTitle:正文为提示词、回答与 WAA proof,没有回答时回答位为 null

func (*Client) VideoFrameTokensForAccount added in v0.3.2

func (c *Client) VideoFrameTokensForAccount(ctx context.Context, accountID string, request VideoFramesRequest) (int64, error)

VideoFrameTokensForAccount 以指定账户调用 StreamExtractVideoFrames 并返回按视频设置抽帧后的 token 数

type ClientOptions

type ClientOptions struct {
	Transport       RPCTransport
	Protected       ProtectedTransport
	ContextProvider RequestContextProvider
	Pages           PageCatalogProvider
	Static          StaticFetcher
}

ClientOptions 定义协议客户端的窄依赖

type CodeExecutionResult

type CodeExecutionResult struct {
	Outcome string `json:"outcome"`
	Output  string `json:"output,omitempty"`
	ID      string `json:"id,omitempty"`
}

CodeExecutionResult 表示 AI Studio 内置代码执行器返回的结果

type ComputerUse added in v0.2.17

type ComputerUse struct {
	Environment                    string   `json:"environment"`
	ExcludedPredefinedFunctions    []string `json:"excluded_predefined_functions,omitempty"`
	DisabledSafetyPolicies         []string `json:"disabled_safety_policies,omitempty"`
	EnablePromptInjectionDetection bool     `json:"enable_prompt_injection_detection,omitempty"`
}

ComputerUse 是 Computer Use 工具的运行环境与预置函数设置

type Content

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

Content 表示一条规范消息

func AgentInput added in v0.3.0

func AgentInput(contents []Content, continued bool) []Content

AgentInput 按官网选取 agent 后台任务实际发送的输入内容:续接上游 interaction 时只取最后一个模型轮之后的内容,否则只取用户内容

func EncodeCreateInteractionRequest added in v0.2.14

func EncodeCreateInteractionRequest(request GenerateRequest, model Model) ([]byte, int, []Content, error)

EncodeCreateInteractionRequest 编码官网 CreateInteraction 请求并返回参与 WAA 绑定的内容,按 field 79 选路写入模型目标(field 18)或 agent 目标(field 19)

func EncodeCreateInteractionStreamRequest added in v0.2.0

func EncodeCreateInteractionStreamRequest(request GenerateRequest, defaults GenerationDefaults) ([]byte, int, []Content, error)

EncodeCreateInteractionStreamRequest 编码官网 CreateInteractionStream 请求并返回参与 WAA 绑定的文本内容

type ContentPolicyError added in v0.3.2

type ContentPolicyError struct {
	Reason  string
	Message string
	// Usage 是下游还没有收到事件就结束时上游给出的用量
	Usage *Usage
}

ContentPolicyError 表示上游以内容策略类原因结束生成

func (*ContentPolicyError) Error added in v0.3.2

func (e *ContentPolicyError) Error() string

Error 返回上游结束生成的内容策略原因

type ContentTokens added in v0.2.17

type ContentTokens struct {
	PartTokens []int64 `json:"partTokens,omitempty"`
	RoleTokens int64   `json:"roleTokens,omitempty"`
}

ContentTokens 是一个 content 或系统指令的逐 Part token 数与角色 token 数

type ContinuationAccounts added in v0.3.6

type ContinuationAccounts func(context.Context, error) (context.Context, error)

ContinuationAccounts 在续写轮以可换账户的错误失败后返回改由其他账户发送该轮的上下文

type CooldownState

type CooldownState struct {
	Until  time.Time `json:"until"`
	Reason string    `json:"reason,omitempty"`
	Level  int       `json:"level,omitempty"`
	// Fallback 是套餐限额或每日限额冷却期间,忽略这两类冷却的回退选号另受的较早结束的冷却
	Fallback *CooldownState `json:"fallback,omitempty"`
	// RejectedSize 是套餐限额或每日限额冷却期间上游在 RejectedUntil 之前以额度拒绝过的最小请求输入字节数
	RejectedSize int64 `json:"rejected_size,omitempty"`
	// RejectedUntil 是 RejectedSize 失效的时刻
	RejectedUntil time.Time `json:"rejected_until,omitzero"`
	// RejectedLevel 是拒绝记录有效期在 rejectedSizeBackoff 中的档位,取值范围 1..len(rejectedSizeBackoff)
	RejectedLevel int `json:"rejected_level,omitempty"`
}

CooldownState 表示账户或模型暂时不可调度的状态

func (CooldownState) Active

func (c CooldownState) Active(now time.Time) bool

Active 判断冷却状态当前是否生效

type DecisionAnswer added in v0.3.6

type DecisionAnswer struct {
	Key           string
	Type          string
	Confidence    float64
	Noul          float64
	Choice        string
	Score         float64
	Probabilities []DecisionProbability
	Legend        []DecisionProbability
}

DecisionAnswer 是一个问题的回答,Probabilities 与 Legend 按上游顺序排列

type DecisionModalityTokens added in v0.3.6

type DecisionModalityTokens struct {
	Modality string
	Tokens   int64
}

DecisionModalityTokens 是一种输入模态的 token 数,Modality 为 text、image 或 audio

type DecisionOption added in v0.3.6

type DecisionOption struct {
	ID          string
	Description string
}

DecisionOption 是 choice 问题的一个选项

type DecisionProbability added in v0.3.6

type DecisionProbability struct {
	Key         string
	Value       float64
	Description string
}

DecisionProbability 是选项或等级的概率,Legend 中 Description 为等级说明

type DecisionProtectedTransport added in v0.3.6

type DecisionProtectedTransport interface {
	DoProtectedDecision(context.Context, DecisionRequest, RPCRequest) (*RPCResponse, error)
}

DecisionProtectedTransport 原子完成 CreateDecision fresh WAA proof、field 5 写入和同 context 发送

type DecisionQuestion added in v0.3.6

type DecisionQuestion struct {
	Key          string
	Type         string
	Instructions []string
	// Criteria 是 noul 为真与为假的说明,HasCriteria 表示请求给出了 criteria
	TrueDescription  string
	FalseDescription string
	HasCriteria      bool
	// Options 是 choice 的选项 ID 与说明
	Options []DecisionOption
	// Levels 是 score 从低到高各等级的说明
	Levels []string
}

DecisionQuestion 是一个决策问题,Type 为 noul、choice 或 score

type DecisionRequest added in v0.3.6

type DecisionRequest struct {
	Model     string
	Input     []Part
	Questions []DecisionQuestion
	AccountID string
}

DecisionRequest 是 Decisions API 请求,Model 为实时目录中带 createDecision 方法的模型,Input 为各问题共用的输入

type DecisionResult added in v0.3.6

type DecisionResult struct {
	Answers         []DecisionAnswer
	InputTokens     int64
	InputByModality []DecisionModalityTokens
	TotalTokens     int64
}

DecisionResult 是 CreateDecision 的回答与输入用量

func DecodeCreateDecisionResponse added in v0.3.6

func DecodeCreateDecisionResponse(body io.Reader) (DecisionResult, error)

DecodeCreateDecisionResponse 解码 CreateDecision 响应:field 1 为问题键与回答,field 2 为用量(输入 token、各模态 token 与 field 10 的总 token),输入被拦截时 field 3 为拦截原因与说明,返回 PromptFeedbackError

type DecisionService added in v0.3.6

type DecisionService interface {
	CreateDecision(context.Context, DecisionRequest) (DecisionResult, error)
}

DecisionService 以 Gemini Decision 模型回答决策问题

type DriveFileChecker added in v0.2.18

type DriveFileChecker interface {
	DriveFileExists(context.Context, string, string, string) (bool, error)
}

DriveFileChecker 负责使用账户固定出口查询 Drive 文件是否存在

type DriveFileReader added in v0.3.9

type DriveFileReader interface {
	ReadDriveFile(ctx context.Context, accountID, token, fileID string)
}

DriveFileReader 负责像官网对话中显示附件一样读取 Drive 文件

type DriveTransport

type DriveTransport interface {
	UploadDrive(context.Context, string, string, UploadRequest) (FileRef, error)
	DownloadDrive(context.Context, string, string, string) (MediaStream, error)
	DeleteDrive(context.Context, string, string, string) error
}

DriveTransport 负责使用账户固定出口访问 Google Drive

type EgressRule added in v0.3.2

type EgressRule struct {
	Domain     string            `json:"domain"`
	Headers    map[string]string `json:"headers,omitempty"`
	Credential string            `json:"credential,omitempty"`
}

EgressRule 是出站白名单的一条规则,Headers 为注入匹配请求的请求头,Credential 为服务端凭据 ID

type EmbedContentRequest added in v0.2.8

type EmbedContentRequest struct {
	Content              Content
	TaskType             string
	Title                string
	OutputDimensionality *int64
}

EmbedContentRequest 表示一条 embedding 输入与参数

type EmbeddingRequest added in v0.2.8

type EmbeddingRequest struct {
	ID                    string
	Model                 string
	Requests              []EmbedContentRequest
	AccountID             string
	CandidateAccountIDs   []string
	RecoverWAARuntime     func(context.Context, string, error) (bool, error)
	ObserveAccountFailure func(string, error)
}

EmbeddingRequest 定义一次经 Build 通道的 embedding 调用

type EmbeddingResult added in v0.2.8

type EmbeddingResult struct {
	Embeddings [][]float64
	TokenCount int64
}

EmbeddingResult 保存与输入顺序一致的向量和上游统计的输入 token 数

func DecodeBuildEmbedResponse added in v0.2.8

func DecodeBuildEmbedResponse(source io.Reader, expected int) (EmbeddingResult, error)

DecodeBuildEmbedResponse 解码 ProxyUnaryCall 返回的 BatchEmbedContentsResponse,向量数必须与请求数一致

type EmbeddingService added in v0.2.8

type EmbeddingService interface {
	Embed(context.Context, EmbeddingRequest) (EmbeddingResult, error)
}

EmbeddingService 定义 embedding 公开端点所需能力

type EnvironmentSource added in v0.3.2

type EnvironmentSource struct {
	Type     string `json:"type"`
	Source   string `json:"source,omitempty"`
	Target   string `json:"target,omitempty"`
	Content  string `json:"content,omitempty"`
	Encoding string `json:"encoding,omitempty"`
}

EnvironmentSource 是挂载到环境中的一个源,Type 为 gcs、inline 或 repository

type Event

type Event struct {
	Kind EventKind `json:"kind"`
	Part
	Grounding    *GroundingMetadata `json:"grounding,omitempty"`
	Citation     *Citation          `json:"citation,omitempty"`
	Usage        *Usage             `json:"usage,omitempty"`
	FinishReason string             `json:"finish_reason,omitempty"`
	// EnvironmentID 是 agent 交互结束时返回的远程环境 ID
	EnvironmentID string `json:"environment_id,omitempty"`
	FinishMessage string `json:"finish_message,omitempty"`
	StopSequence  string `json:"stop_sequence,omitempty"`
	ProviderModel string `json:"provider_model,omitempty"`
	// SafetyRatings 是结束事件携带的候选安全评级
	SafetyRatings []SafetyRating `json:"safety_ratings,omitempty"`
	// TurnToken 是上游响应帧的轮次令牌
	TurnToken string `json:"turn_token,omitempty"`
	// DebugInfo 是 Build 通道单次响应的 debugInfo
	DebugInfo json.RawMessage `json:"debug_info,omitempty"`
	// DetailedFinishReason 是 Build 通道结束事件的 detailedFinishReason
	DetailedFinishReason json.RawMessage `json:"detailed_finish_reason,omitempty"`
	// ResponseID 是上游给出的该响应的 responseId
	ResponseID string `json:"response_id,omitempty"`
	// InteractionID 与 AccountID 是 agent 后台任务的上游 interaction ID 与所属账户,随结束事件给出
	InteractionID string `json:"interaction_id,omitempty"`
	AccountID     string `json:"account_id,omitempty"`
	// FrameUsage 是事件所在上游帧给出的累计用量
	FrameUsage *Usage `json:"frame_usage,omitempty"`
	// FinishFrame 表示事件来自带结束原因的上游帧
	FinishFrame bool  `json:"finish_frame,omitempty"`
	Err         error `json:"-"`
	// TrailingError 是上游在函数调用之后结束生成的错误,结束事件仍按正常完成输出给客户端
	TrailingError error `json:"-"`
}

Event 表示协议核心输出的规范事件,内容事件携带上游返回的完整 Part

func (Event) HasContent added in v0.2.17

func (event Event) HasContent() bool

HasContent 表示事件携带内容或独立签名

type EventKind

type EventKind string

EventKind 表示规范流事件类型

const (
	// EventText 表示正文增量
	EventText EventKind = "text"
	// EventReasoning 表示思考摘要增量
	EventReasoning EventKind = "reasoning"
	// EventToolCall 表示函数调用
	EventToolCall EventKind = "tool_call"
	// EventServerToolCall 表示上游服务端工具调用
	EventServerToolCall EventKind = "server_tool_call"
	// EventServerToolResponse 表示上游服务端工具结果
	EventServerToolResponse EventKind = "server_tool_response"
	// EventExecutableCode 表示内置代码执行器生成代码
	EventExecutableCode EventKind = "executable_code"
	// EventCodeExecutionResult 表示内置代码执行结果
	EventCodeExecutionResult EventKind = "code_execution_result"
	// EventGrounding 表示 Google 工具来源信息
	EventGrounding EventKind = "grounding"
	// EventCitation 表示来源信息
	EventCitation EventKind = "citation"
	// EventMedia 表示媒体产物
	EventMedia EventKind = "media"
	// EventThoughtSignature 表示独立思考签名
	EventThoughtSignature EventKind = "thought_signature"
	// EventUsage 表示权威用量
	EventUsage EventKind = "usage"
	// EventFinish 表示正常完成
	EventFinish EventKind = "finish"
	// EventError 表示上游错误
	EventError EventKind = "error"
)

type ExecutableCode

type ExecutableCode struct {
	Language string `json:"language"`
	Code     string `json:"code"`
	ID       string `json:"id,omitempty"`
}

ExecutableCode 表示 AI Studio 内置代码执行器生成的代码

type ExternalMedia

type ExternalMedia struct {
	MIME string `json:"mime"`
	URL  string `json:"url"`
}

ExternalMedia 表示可由 AI Studio 直接读取的外部媒体

func ExternalMediaForURL

func ExternalMediaForURL(raw string) (*ExternalMedia, bool)

ExternalMediaForURL 返回 AI Studio 可直接读取的外部媒体

type FileMetadata

type FileMetadata struct {
	ID        string
	Name      string
	MIME      string
	Purpose   string
	Size      int64
	CreatedAt time.Time
	// Alias 是客户端上传时指定的公开文件名
	Alias string
	// SHA256 是文件内容的 SHA-256 摘要,Base64 编码
	SHA256 string
	// VideoDuration 是 MP4 与 QuickTime 视频的时长
	VideoDuration time.Duration
	// ExpiresAt 是文件的到期时间,零值表示不过期
	ExpiresAt time.Time
}

FileMetadata 表示已上传文件的持久元数据

type FileRef

type FileRef struct {
	ID   string `json:"id"`
	Name string `json:"name,omitempty"`
	MIME string `json:"mime,omitempty"`
}

FileRef 表示已上传文件引用

type FileService

type FileService interface {
	UploadFile(context.Context, UploadRequest) (FileRef, error)
	FileMetadata(context.Context, string) (FileMetadata, error)
	ListFiles(context.Context) ([]FileMetadata, error)
	DownloadFile(context.Context, string) (MediaStream, error)
	DeleteFile(context.Context, string) error
}

FileService 定义公开文件 API 依赖的能力

type FrameDecoder

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

FrameDecoder 将 field 1 repeated 帧转换为规范事件

func NewFrameDecoder

func NewFrameDecoder() *FrameDecoder

NewFrameDecoder 创建单次 GenerateContent 的有状态解码器

func (*FrameDecoder) Decode

func (d *FrameDecoder) Decode(raw json.RawMessage) ([]Event, error)

Decode 解码一条 repeated 流帧

func (*FrameDecoder) End

func (d *FrameDecoder) End() error

End 校验流已经出现正常完成帧

type FunctionCall

type FunctionCall struct {
	ID               string          `json:"id"`
	Name             string          `json:"name"`
	Arguments        json.RawMessage `json:"arguments"`
	ThoughtSignature string          `json:"thought_signature,omitempty"`
}

FunctionCall 表示模型发起的函数调用

type FunctionDeclaration

type FunctionDeclaration struct {
	Name        string          `json:"name"`
	Description string          `json:"description,omitempty"`
	Parameters  json.RawMessage `json:"parameters,omitempty"`
	// Response 是函数返回值的 JSON Schema,Playground 没有对应字段
	Response json.RawMessage `json:"response,omitempty"`
	Strict   bool            `json:"strict,omitempty"`
	// Behavior 为 Live 函数的调用方式 BLOCKING 或 NON_BLOCKING,不区分大小写
	Behavior string `json:"behavior,omitempty"`
}

FunctionDeclaration 表示客户端声明的函数

type FunctionResult

type FunctionResult struct {
	ID      string          `json:"id"`
	Name    string          `json:"name,omitempty"`
	Content json.RawMessage `json:"content"`
	// WillContinue 表示非阻塞函数之后还会发送同一调用的响应
	WillContinue bool `json:"will_continue,omitempty"`
}

FunctionResult 表示客户端返回的函数结果

type GenerateRequest

type GenerateRequest struct {
	ID    string `json:"id"`
	Model string `json:"model"`
	// System 是系统指令的各段文本
	System    []string         `json:"system,omitempty"`
	Contents  []Content        `json:"contents"`
	Config    GenerationConfig `json:"config,omitempty"`
	Tools     Tools            `json:"tools,omitempty"`
	AccountID string           `json:"account_id,omitempty"`
	// SafetySettings 覆盖对应类别的拦截阈值,未列出的类别保持关闭
	SafetySettings []SafetySetting `json:"safety_settings,omitempty"`
	// ServiceTier 是 Gemini API 服务等级 flex、standard 或 priority
	ServiceTier string `json:"service_tier,omitempty"`
	// Store 设置上游是否记录本次请求
	Store *bool `json:"store,omitempty"`
	// Labels 是请求的计费标签
	Labels map[string]string `json:"labels,omitempty"`
	// AgentConfig 是 agent 的运行配置
	AgentConfig *AgentConfig `json:"agent_config,omitempty"`
	// Environment 是 agent 的远程环境,nil 时为官网默认的新环境
	Environment *AgentEnvironment `json:"environment,omitempty"`
	// PreviousInteractionID 是上一轮 agent 后台任务的上游 interaction ID,有值时只发送上一模型轮之后的输入
	PreviousInteractionID string `json:"previous_interaction_id,omitempty"`
	// ImageRoute 内部标记:图像生成模型(由模型目录能力推导)
	ImageRoute bool `json:"-"`
	// Unary 标记单次非流式请求(在 Build 代理中使用 ProxyUnaryCall)
	Unary bool `json:"-"`
	// Background 标记没有客户端等待首事件的后台任务
	Background bool `json:"-"`
	// Truncate 在生成前按模型上下文窗口移除最早的完整轮次
	Truncate bool `json:"-"`
	// KeepAbnormalFinish 表示异常结束重新生成耗尽且没有输出时仍以该结束原因结束,供按官方形状输出的 Gemini 入口使用
	KeepAbnormalFinish bool `json:"-"`
	// ReplyTool 表示经内部 final 函数交付正文以减轻角色扮演场景的流式截断
	ReplyTool bool `json:"-"`
	// UserMessageRewrite 表示发往上游前改写用户消息的模式(off、traditional、martian),开启时要求模型默认以简体中文回复
	UserMessageRewrite string `json:"-"`
	// ThinkingGuard 表示引导思考阶段保持简洁抽象不复述敏感词并将思考上限收敛到低档,以减轻思考阶段触发上游过滤截断
	ThinkingGuard bool `json:"-"`
	// contains filtered or unexported fields
}

GenerateRequest 表示供应商无关的生成请求

func ResolveSearchGenerateRequest added in v0.2.18

func ResolveSearchGenerateRequest(request GenerateRequest, aliases, search bool) GenerateRequest

ResolveSearchGenerateRequest 将搜索型号解析为基础型号并合入 Google 搜索

type GeneratedImage added in v0.2.18

type GeneratedImage struct {
	Data          string
	MIMEType      string
	BlockedReason string
}

GeneratedImage 是 GenerateImage 返回的一张图片,BlockedReason 为被安全策略拦下的原因

func ParseGenerateImageResponse added in v0.2.18

func ParseGenerateImageResponse(body io.Reader) ([]GeneratedImage, error)

ParseGenerateImageResponse 解码 GenerateImage 响应字段 1 的图片:1 base64 数据、2 MIME、3 安全拦截原因

type GenerationConfig

type GenerationConfig struct {
	Temperature      *float64 `json:"temperature,omitempty"`
	TopP             *float64 `json:"top_p,omitempty"`
	TopK             *int     `json:"top_k,omitempty"`
	MaxOutputTokens  *int64   `json:"max_output_tokens,omitempty"`
	StopSequences    []string `json:"stop_sequences,omitempty"`
	ResponseMIMEType string   `json:"response_mime_type,omitempty"`
	// ResponseSchema 是 Gemini API responseSchema 形式的 OpenAPI Schema
	ResponseSchema json.RawMessage `json:"response_schema,omitempty"`
	// ResponseJSONSchema 是 JSON Schema 形式的结构化输出约束
	ResponseJSONSchema  json.RawMessage      `json:"response_json_schema,omitempty"`
	ResponseModalities  []ResponseModality   `json:"response_modalities,omitempty"`
	ImageConfig         *ImageConfig         `json:"image_config,omitempty"`
	VideoConfig         *VideoConfig         `json:"video_config,omitempty"`
	SpeechConfig        *SpeechConfig        `json:"speech_config,omitempty"`
	TranscriptionConfig *TranscriptionConfig `json:"transcription_config,omitempty"`
	ReasoningEffort     string               `json:"reasoning_effort,omitempty"`
	ThinkingBudget      *int64               `json:"thinking_budget,omitempty"`
	Seed                *int64               `json:"seed,omitempty"`
	// MediaResolution 为输入媒体分辨率,取 Gemini API 枚举名
	MediaResolution string `json:"media_resolution,omitempty"`
	// EnhancedCivicAnswers 开启公民议题增强回答
	EnhancedCivicAnswers bool `json:"enhanced_civic_answers,omitempty"`
	// HideThinking 控制公开响应的思考块可见性
	HideThinking bool `json:"hide_thinking,omitempty"`
}

GenerationConfig 表示已验证的生成参数

func ApplyModelSuffix added in v0.2.10

func ApplyModelSuffix(model string, config GenerationConfig) (string, GenerationConfig, error)

ApplyModelSuffix 把模型名末尾的 (思考设置) 写入生成参数并返回去掉后缀的模型 ID,后缀优先于请求体中的思考参数

type GenerationDefaults

type GenerationDefaults struct {
	MaxOutputTokens      int64
	Temperature          *float64
	TopP                 *float64
	TopK                 *int
	Thinking             bool
	ThinkingBudget       bool
	ThinkingLevel        bool
	DefaultThinkingLevel int64
	ThinkingLevels       []int64
	// ImageRoute 表示图像生成模型(官网 GenerateContent 走扩展约束)
	ImageRoute bool
	// OutputResolution 表示支持输出分辨率(官网会带 imageConfig 与扩展槽位)
	OutputResolution bool
	// InteractionStream 表示官网经 CreateInteractionStream 生成的模型
	InteractionStream bool
	// InteractionTask 表示官网经 CreateInteraction 创建后台任务、经 GetInteractionStream 读取结果的模型
	InteractionTask bool
	// InteractionAgent 表示 field 79 kind == 1 的 agent 目标
	InteractionAgent bool
	// InteractionModel 表示 field 79 kind == 2 的模型目标
	InteractionModel bool
	// VideoOutput 表示具备次能力码 14 与 chat_model 的视频输出聊天模型(官网 _.rl)
	VideoOutput bool
	// VideoResolution 为视频输出分辨率选项中的第一项,Interaction 视频输出格式的默认分辨率
	VideoResolution string
	// ContinuedOutputTokens 表示自动续写模型的输出总上限,其他模型为 0
	ContinuedOutputTokens int64
}

GenerationDefaults 保存 ListModels 返回的生成默认值

type GoogleSearchOptions

type GoogleSearchOptions struct {
	WebSearch      bool                   `json:"web_search,omitempty"`
	ImageSearch    bool                   `json:"image_search,omitempty"`
	TimeRange      *GoogleSearchTimeRange `json:"time_range,omitempty"`
	ContextSize    string                 `json:"context_size,omitempty"`
	UserLocation   json.RawMessage        `json:"user_location,omitempty"`
	AllowedDomains []string               `json:"allowed_domains,omitempty"`
	BlockedDomains []string               `json:"blocked_domains,omitempty"`
}

GoogleSearchOptions 表示 Google Search 的检索类型与时间范围

type GoogleSearchTimeRange

type GoogleSearchTimeRange struct {
	StartTime time.Time `json:"start_time,omitzero"`
	EndTime   time.Time `json:"end_time,omitzero"`
}

GoogleSearchTimeRange 表示 Google Search 的检索时间范围

type GroundingChunk

type GroundingChunk struct {
	Source  string `json:"source"`
	URI     string `json:"uri,omitempty"`
	Title   string `json:"title,omitempty"`
	Text    string `json:"text,omitempty"`
	PlaceID string `json:"place_id,omitempty"`
	// ImageURI 是图片搜索来源的图片地址,URI 为图片所在网页
	ImageURI string `json:"image_uri,omitempty"`
	Domain   string `json:"domain,omitempty"`
	// PlaceAnswerSources 是 Maps 来源的评论片段
	PlaceAnswerSources json.RawMessage `json:"place_answer_sources,omitempty"`
	// SiteName 与 SearchResultMapping 是网页来源的站点名与它在搜索结果中的位置
	SiteName            string          `json:"site_name,omitempty"`
	SearchResultMapping json.RawMessage `json:"search_result_mapping,omitempty"`
	// Origin 与 ReferenceID 是上游给出的来源产生方式与引用编号
	Origin      string `json:"origin,omitempty"`
	ReferenceID string `json:"reference_id,omitempty"`
}

GroundingChunk 表示 Google 工具检索到的一个来源,Source 为 web、image、retrieved_context 或 maps

type GroundingMetadata

type GroundingMetadata struct {
	SearchEntryPoint       *SearchEntryPoint  `json:"search_entry_point,omitempty"`
	Chunks                 []GroundingChunk   `json:"chunks,omitempty"`
	Supports               []GroundingSupport `json:"supports,omitempty"`
	DynamicRetrievalScore  *float64           `json:"dynamic_retrieval_score,omitempty"`
	WebSearchQueries       []string           `json:"web_search_queries,omitempty"`
	ImageSearchQueries     []string           `json:"image_search_queries,omitempty"`
	MapsWidgetContextToken string             `json:"maps_widget_context_token,omitempty"`
	URLContext             []URLMetadata      `json:"url_context,omitempty"`
}

GroundingMetadata 表示 Google Search、URL Context 和 Maps 的来源信息

type GroundingSegment

type GroundingSegment struct {
	PartIndex  int    `json:"part_index,omitempty"`
	StartIndex int    `json:"start_index,omitempty"`
	EndIndex   int    `json:"end_index,omitempty"`
	Text       string `json:"text,omitempty"`
}

GroundingSegment 表示正文中由来源支撑的片段

type GroundingSupport

type GroundingSupport struct {
	Segment          GroundingSegment `json:"segment"`
	ChunkIndices     []int            `json:"chunk_indices,omitempty"`
	ConfidenceScores []float64        `json:"confidence_scores,omitempty"`
	// RenderedParts 是该片段对应的图片等渲染 Part 下标
	RenderedParts []int `json:"rendered_parts,omitempty"`
	// Origin 是上游给出的支撑关系产生方式
	Origin string `json:"origin,omitempty"`
}

GroundingSupport 表示正文片段与来源下标的关联

type GroupedErrors added in v0.3.0

type GroupedErrors []groupedError

GroupedErrors 按原因文字归并错误:原因相同的只保留一条并记下因它失败的账户,按原因首次出现的顺序排列

func (*GroupedErrors) Add added in v0.3.0

func (groups *GroupedErrors) Add(accountID string, err error)

Add 记录 accountID 因 err 失败,accountID 为空时只记录原因

func (GroupedErrors) Join added in v0.3.0

func (groups GroupedErrors) Join(wrap func(accountIDs string, err error) error) error

Join 合并为一个错误,每种原因一条,记有账户的原因由 wrap 写明因它失败的全部账户

type HTTPTransportOptions

type HTTPTransportOptions struct {
	Pool        *AccountPool
	Signer      *Signer
	Headers     ProtocolHeaderProvider
	GlobalProxy string
}

HTTPTransportOptions 定义普通 MakerSuite RPC 的账户与网络依赖

type ImageConfig

type ImageConfig struct {
	AspectRatio string `json:"aspect_ratio,omitempty"`
	ImageSize   string `json:"image_size,omitempty"`
}

ImageConfig 表示图片生成参数

type ImageProtectedTransport added in v0.2.18

type ImageProtectedTransport interface {
	DoProtectedImage(context.Context, ImageRequest, RPCRequest) (*RPCResponse, error)
}

ImageProtectedTransport 原子完成 GenerateImage fresh WAA proof、field 3 写入和同 context 发送

type ImageRequest added in v0.2.18

type ImageRequest struct {
	Model          string
	Prompt         string
	SampleCount    int
	NegativePrompt string
	AspectRatio    string
	ImageSize      string
	AccountID      string
}

ImageRequest 是 Imagen 文生图请求,Model 为实时目录中带 predict 方法的模型

type ImageService added in v0.2.18

type ImageService interface {
	GenerateImage(context.Context, ImageRequest) ([]GeneratedImage, error)
}

ImageService 生成 Imagen 图片

type InteractionMethod added in v0.3.15

type InteractionMethod string

InteractionMethod 表示模型经 ListModels field 79 选定的生成接口

const (
	// InteractionMethodGenerateContent 表示走普通 GenerateContent 接口
	InteractionMethodGenerateContent InteractionMethod = "GenerateContent"
	// InteractionMethodCreateInteractionStream 表示走非后台 CreateInteractionStream 接口
	InteractionMethodCreateInteractionStream InteractionMethod = "CreateInteractionStream"
	// InteractionMethodCreateInteraction 表示走后台 CreateInteraction 与 GetInteractionStream 接口
	InteractionMethodCreateInteraction InteractionMethod = "CreateInteraction"
)

type InteractionRouting added in v0.3.15

type InteractionRouting struct {
	Method InteractionMethod
	Target InteractionTarget
}

InteractionRouting 是由 ListModels field 79 换算出的生成接口与目标位置

func ResolveInteractionRouting added in v0.3.15

func ResolveInteractionRouting(kind int64, background bool) InteractionRouting

ResolveInteractionRouting 按官网 _.Ol、_.Pl、Rl、_.Sl 四个谓词把 ListModels field 79 的 kind 与 background 换算为接口与目标位置;不识别的 kind 走 GenerateContent

func (InteractionRouting) IsAgent added in v0.3.15

func (r InteractionRouting) IsAgent() bool

IsAgent 表示目标为 agent(field 79 kind == 1)

func (InteractionRouting) IsInteraction added in v0.3.15

func (r InteractionRouting) IsInteraction() bool

IsInteraction 表示模型经 Interactions API 生成

func (InteractionRouting) IsModel added in v0.3.15

func (r InteractionRouting) IsModel() bool

IsModel 表示目标为模型(field 79 kind == 2)

func (InteractionRouting) IsStream added in v0.3.15

func (r InteractionRouting) IsStream() bool

IsStream 表示模型经 CreateInteractionStream 生成

func (InteractionRouting) IsTask added in v0.3.15

func (r InteractionRouting) IsTask() bool

IsTask 表示模型经 CreateInteraction 创建后台任务并经 GetInteractionStream 读取结果

type InteractionTarget added in v0.3.15

type InteractionTarget string

InteractionTarget 表示 Interaction 请求中目标写入模型槽位还是 agent 槽位

const (
	// InteractionTargetNone 表示不走 Interactions API
	InteractionTargetNone InteractionTarget = ""
	// InteractionTargetModel 表示模型目标(field 79 kind == 2,写 interaction field 18)
	InteractionTargetModel InteractionTarget = "model"
	// InteractionTargetAgent 表示 agent 目标(field 79 kind == 1,写 interaction field 19)
	InteractionTargetAgent InteractionTarget = "agent"
)

type IsolatedLoginDriver

type IsolatedLoginDriver interface {
	Login(context.Context, IsolatedLoginRequest) (IsolatedLoginResult, error)
}

IsolatedLoginDriver 定义独立浏览器登录

type IsolatedLoginRequest

type IsolatedLoginRequest struct {
	Directory          string
	Proxy              string
	Locale             string
	Timezone           string
	View               *camoufoxnative.LiveView
	OnLoggedIn         func(context.Context, IsolatedLoginResult) error
	CheckVerification  func(context.Context, StorageState) (bool, error)
	OnVerifyStep       func(string)
	VerifyPollInterval time.Duration
}

IsolatedLoginRequest 描述独立浏览器登录所需的稳定环境,View 不为空时登录画面显示在管理页登录窗口

type IsolatedLoginResult

type IsolatedLoginResult struct {
	StorageState        StorageState
	Email               string
	VerifiedAt          time.Time
	DriveError          string
	CloseError          string
	Saved               bool
	VerificationPending bool
	VerificationError   string
}

IsolatedLoginResult 返回独立浏览器导出的认证状态

type Language added in v0.2.14

type Language struct {
	Code string `json:"code"`
	Name string `json:"name"`
}

Language 是模型可选语言的代码与显示名

type MCPServer added in v0.2.17

type MCPServer struct {
	Name             string            `json:"name"`
	URL              string            `json:"url"`
	Headers          map[string]string `json:"headers,omitempty"`
	Timeout          string            `json:"timeout,omitempty"`
	SSEReadTimeout   string            `json:"sse_read_timeout,omitempty"`
	TerminateOnClose *bool             `json:"terminate_on_close,omitempty"`
	AllowedTools     []string          `json:"allowed_tools,omitempty"`
	// ReadOnly 为 true 时只允许 tools/list 中标记只读的工具
	ReadOnly bool `json:"-"`
	// DisabledTools 是从 tools/list 工具全集中排除的工具
	DisabledTools []string `json:"-"`
}

MCPServer 是由上游连接并调用的 Streamable HTTP MCP 服务器

type MakerSuiteHTTPTransport

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

MakerSuiteHTTPTransport 使用账户固定出口发送普通 RPC

func NewMakerSuiteHTTPTransport

func NewMakerSuiteHTTPTransport(options HTTPTransportOptions) (*MakerSuiteHTTPTransport, error)

NewMakerSuiteHTTPTransport 创建普通 MakerSuite RPC 传输

func (*MakerSuiteHTTPTransport) CloseIdleConnections

func (t *MakerSuiteHTTPTransport) CloseIdleConnections()

CloseIdleConnections 关闭全部固定出口的空闲连接

func (*MakerSuiteHTTPTransport) DeleteDrive

func (t *MakerSuiteHTTPTransport) DeleteDrive(ctx context.Context, accountID string, token string, fileID string) (err error)

DeleteDrive 通过当前账户固定出口删除 Drive 文件

func (*MakerSuiteHTTPTransport) Do

Do 发送普通 MakerSuite RPC 并让响应 body 持有租约,账户有 WAA Worker 时 pageIssuedRPCs 中的方法与 issuedByPage 上下文中的请求由页面发出

func (*MakerSuiteHTTPTransport) DownloadDrive

func (t *MakerSuiteHTTPTransport) DownloadDrive(ctx context.Context, accountID string, token string, fileID string) (MediaStream, error)

DownloadDrive 通过当前账户固定出口下载 Drive 文件

func (*MakerSuiteHTTPTransport) DriveFileExists added in v0.2.18

func (t *MakerSuiteHTTPTransport) DriveFileExists(ctx context.Context, accountID string, token string, fileID string) (_ bool, err error)

DriveFileExists 通过当前账户固定出口按官网视频页的元数据请求查询 Drive 文件是否存在

func (*MakerSuiteHTTPTransport) FetchStatic added in v0.3.7

func (t *MakerSuiteHTTPTransport) FetchStatic(ctx context.Context, accountID string, address string) ([]byte, error)

FetchStatic 经账户的固定出口以 GET 读取官网静态资源

func (*MakerSuiteHTTPTransport) GlobalProxy added in v0.3.15

func (t *MakerSuiteHTTPTransport) GlobalProxy() string

GlobalProxy 返回当前默认出口代理

func (*MakerSuiteHTTPTransport) ReadDriveFile added in v0.3.9

func (t *MakerSuiteHTTPTransport) ReadDriveFile(ctx context.Context, accountID, token, fileID string)

ReadDriveFile 像官网对话中新一轮显示附件一样经 gapi 读取 Drive v3 discovery 文档与文件的 ID、类型、名称和缩略图地址,再载入去掉尺寸后缀的缩略图;失败只记日志

func (*MakerSuiteHTTPTransport) SetGlobalProxy added in v0.3.15

func (t *MakerSuiteHTTPTransport) SetGlobalProxy(proxy string) error

SetGlobalProxy 替换默认出口代理并校验可建立代理客户端,不中断进行中的请求

func (*MakerSuiteHTTPTransport) UploadAssistantFile added in v0.2.13

func (t *MakerSuiteHTTPTransport) UploadAssistantFile(ctx context.Context, accountID string, blob Blob) (string, error)

UploadAssistantFile 以账户身份按官网对话面板的 /_/upload 可续传协议上传附件,返回上传路径

func (*MakerSuiteHTTPTransport) UploadDrive

func (t *MakerSuiteHTTPTransport) UploadDrive(ctx context.Context, accountID string, token string, request UploadRequest) (_ FileRef, err error)

UploadDrive 通过当前账户固定出口上传 Drive 文件

type MediaStream

type MediaStream struct {
	Body io.ReadCloser
	MIME string
	Name string
	Size int64
}

MediaStream 表示需要调用方关闭的媒体响应流

type ModalityTokenCount added in v0.2.17

type ModalityTokenCount struct {
	Modality   string `json:"modality"`
	TokenCount int64  `json:"tokenCount,omitempty"`
}

ModalityTokenCount 是单一模态的 token 数

type Model

type Model struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Version     string `json:"version,omitempty"`
	// Stage 是模型阶段,取值为 Gemini API ModelStage 枚举名
	Stage            string   `json:"stage,omitempty"`
	Methods          []string `json:"methods"`
	InputTokenLimit  int64    `json:"input_token_limit,omitempty"`
	OutputTokenLimit int64    `json:"output_token_limit,omitempty"`
	Temperature      *float64 `json:"temperature,omitempty"`
	MaxTemperature   *float64 `json:"max_temperature,omitempty"`
	TopP             *float64 `json:"top_p,omitempty"`
	TopK             *int     `json:"top_k,omitempty"`
	// ThinkingLevels 是模型支持的思考档位,按目录 field 72 的顺序排列
	ThinkingLevels       []string `json:"thinking_levels,omitempty"`
	DefaultThinkingLevel string   `json:"default_thinking_level,omitempty"`
	// ThinkingBudget 是可设思考预算的模型的预算默认值、上下限与能否关闭思考,上游未给出的项省略
	ThinkingBudget *ThinkingBudget `json:"thinking_budget,omitempty"`
	// ToolCompatibility 是可同时开启的工具对
	ToolCompatibility [][2]string         `json:"tool_compatibility,omitempty"`
	Details           *ModelDetails       `json:"details,omitempty"`
	Capabilities      map[string]bool     `json:"capabilities,omitempty"`
	CapabilityOptions map[string][]string `json:"capability_options,omitempty"`
	// VoiceDetails 是 TTS 与 Live 模型的音色介绍,顺序与官网音色列表一致
	VoiceDetails []VoiceDetail `json:"voice_details,omitempty"`
	// Languages 是实时翻译与转录模型可选的语言,顺序与官网语言列表一致
	Languages   []Language `json:"languages,omitempty"`
	AccessModes []int64    `json:"access_modes,omitempty"`
	Paid        bool       `json:"paid,omitempty"`
	Channels    []string   `json:"channels,omitempty"`
	// AgentModel 是 agent 默认使用的模型 ID
	AgentModel string `json:"agent_model,omitempty"`
	// Hidden 表示官网前端已配置、ListModels 尚未列出、经 CountTokens 确认可用的模型
	Hidden bool `json:"hidden,omitempty"`
}

Model 表示实时模型目录中的模型

func ModelsWithSearchAliases added in v0.2.18

func ModelsWithSearchAliases(models []Model) []Model

ModelsWithSearchAliases 为支持生成与 Google 搜索的对话模型补充搜索型号

func ParseBuildModels added in v0.2.0

func ParseBuildModels(raw []byte) ([]Model, string, error)

ParseBuildModels 解析 Gemini API models.list 响应

func ParseModels

func ParseModels(source io.Reader) ([]Model, error)

ParseModels 解码 ListModels 的数组协议

type ModelAccess

type ModelAccess struct {
	State     ModelAccessState `json:"state"`
	CheckedAt time.Time        `json:"checked_at"`
	Reason    string           `json:"reason,omitempty"`
}

ModelAccess 保存账户模型资格的实测结果

type ModelAccessError added in v0.2.10

type ModelAccessError struct {
	Model       string
	AccessModes []int64
	// Accounts 是请求限定的账户(按请求指定、key 绑定或模型绑定),为空时指全部启用账户
	Accounts []string
}

ModelAccessError 表示模型只对启用账户都不具备的权益开放

func (*ModelAccessError) Error added in v0.2.10

func (e *ModelAccessError) Error() string

func (*ModelAccessError) ErrorCode added in v0.2.10

func (e *ModelAccessError) ErrorCode() string

ErrorCode 返回 OpenAI 兼容的错误代码

func (*ModelAccessError) HTTPStatus added in v0.2.10

func (e *ModelAccessError) HTTPStatus() int

HTTPStatus 返回权益不足对应的状态码

type ModelAccessState

type ModelAccessState string

ModelAccessState 表示账户对单个模型的实测调用资格

const (
	// ModelAccessVerified 表示账户已成功调用模型
	ModelAccessVerified ModelAccessState = "verified"
)

type ModelDetails added in v0.2.14

type ModelDetails struct {
	Summary         string       `json:"summary,omitempty"`
	Alias           string       `json:"alias,omitempty"`
	Warning         string       `json:"warning,omitempty"`
	DocsURL         string       `json:"docs_url,omitempty"`
	ModelCardURL    string       `json:"model_card_url,omitempty"`
	ReleaseDate     int64        `json:"release_date,omitempty"`
	KnowledgeCutoff int64        `json:"knowledge_cutoff,omitempty"`
	Pricing         []ModelPrice `json:"pricing,omitempty"`
	PricingURL      string       `json:"pricing_url,omitempty"`
	PricingNote     string       `json:"pricing_note,omitempty"`
}

ModelDetails 是 ListModels field 39 的模型说明,日期为 Unix 秒

type ModelPrice added in v0.2.14

type ModelPrice struct {
	Text             string   `json:"text,omitempty"`
	Label            string   `json:"label,omitempty"`
	UpTo             int64    `json:"up_to,omitempty"`
	Thinking         bool     `json:"thinking,omitempty"`
	Input            *float64 `json:"input,omitempty"`
	InputPerRequest  bool     `json:"input_per_request,omitempty"`
	Output           *float64 `json:"output,omitempty"`
	OutputPerRequest bool     `json:"output_per_request,omitempty"`
}

ModelPrice 是模型价格的一行:Text 为上游给出的整句说明;Input、Output 为每百万 token 美元,按次计价时对应 PerRequest 为真;UpTo 为该档输入 token 上限,Thinking 标记思考档

type NativeLoginDriver

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

NativeLoginDriver 通过纯 Go WebDriver BiDi 完成隔离登录

func NewNativeLoginDriver

func NewNativeLoginDriver(camoufoxPath string) (*NativeLoginDriver, error)

NewNativeLoginDriver 创建纯 Go Camoufox 登录驱动

func (*NativeLoginDriver) Login

Login 启动隔离 Camoufox 供用户登录并导出认证状态

func (*NativeLoginDriver) Verify

func (driver *NativeLoginDriver) Verify(ctx context.Context, request AccountVerifyRequest) (bool, error)

Verify 启动隔离 Camoufox 载入已有账户的认证状态并停在官网验证页,自动再核对直到通过或窗口关闭

type NativeWorker

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

NativeWorker 将单个账户的 Camoufox 或 SpiderMonkey WAA runtime 适配为受保护请求 preparer

func NewNativeWorker

func NewNativeWorker(ctx context.Context, accountID string, options camoufoxnative.Options) (*NativeWorker, error)

NewNativeWorker 启动单个账户的 Camoufox WAA runtime

func NewSpiderMonkeyWorker added in v0.2.18

func NewSpiderMonkeyWorker(ctx context.Context, accountID string, options camoufoxnative.Options) (*NativeWorker, error)

NewSpiderMonkeyWorker 启动单个账户的 SpiderMonkey WAA runtime

func (*NativeWorker) BrowserStorageState

func (worker *NativeWorker) BrowserStorageState(ctx context.Context) (StorageState, error)

BrowserStorageState 返回账户 WAA runtime 当前 Cookie 状态

func (*NativeWorker) Close

func (worker *NativeWorker) Close() error

Close 关闭账户 WAA runtime

func (*NativeWorker) MergeSetCookieHeaders added in v0.3.3

func (worker *NativeWorker) MergeSetCookieHeaders(ctx context.Context, headers []string, requestURL string) error

MergeSetCookieHeaders 把账户在页面之外取得的响应 Cookie 写入当前页面

func (*NativeWorker) PageCatalog added in v0.3.0

func (worker *NativeWorker) PageCatalog() camoufoxnative.PageCatalog

PageCatalog 返回账户当前页面载入时目录 RPC 的响应正文

func (*NativeWorker) Prepare

Prepare 生成 fresh proof,请求带 Proof 时沿用该 proof,正文原样返回,发送时在 ProofAt 处写入;在页面界面运行的 GenerateContent 由页面应用取 proof,只返回公共协议头

func (*NativeWorker) ProtocolHeaders

func (worker *NativeWorker) ProtocolHeaders(ctx context.Context, _ string) (http.Header, error)

ProtocolHeaders 返回当前账户官网请求的动态公共头

func (*NativeWorker) Reload added in v0.3.0

func (worker *NativeWorker) Reload(ctx context.Context) error

Reload 按官网冷启动重新载入账户页面,新页面就绪后切换:还没在旧页面上取 proof、上传附件或发送的请求在新页面上取 proof,已在旧页面或新开页面上取过 proof、上传附件或发送的请求在原页面上完成,原页面在其租约归还后关闭,新页面同时分给其他请求

func (*NativeWorker) Retire added in v0.3.10

func (worker *NativeWorker) Retire()

Retire 让 Camoufox 后端的页面在后台离开并关闭浏览器,随后的 Close 不再等待;SpiderMonkey 后端不做操作

func (*NativeWorker) SendPageRPC added in v0.3.10

func (worker *NativeWorker) SendPageRPC(ctx context.Context, signer *Signer, rpc RPCRequest) (*RPCResponse, error)

SendPageRPC 像官网页面一样在当前页面中发出一次 MakerSuite RPC:带页面的公共协议头与 rpc 的请求头,以页面当前的 Cookie 签名,Cookie 由页面自己附带

func (*NativeWorker) SendProtected

func (worker *NativeWorker) SendProtected(ctx context.Context, request ProtectedRequest) (*RPCResponse, error)

SendProtected 经账户 WAA runtime 流式发送已准备的请求,响应带实际写入的 proof Camoufox 后端未带 proof 的 GenerateContent 在页面界面运行,请求头、proof 与随后的 CountTokens 由页面应用产生 其余 GenerateContent 发出 pageCountTokensDelay 后由 runtime 以相同请求头统计页面提示词的 token

func (*NativeWorker) State

func (worker *NativeWorker) State() WorkerState

State 返回账户 WAA runtime 状态

type Output added in v0.2.17

type Output struct {
	Parts []Part
	// contains filtered or unexported fields
}

Output 按上游顺序累积一次生成的内容 Part,同一 Part 的流式正文与 PCM 音频分块合并

func (*Output) Add added in v0.2.17

func (output *Output) Add(event Event)

Add 并入一个内容事件

func (Output) History added in v0.2.17

func (output Output) History() Content

History 返回续接历史中的模型轮次:思考 Part 只保留签名

func (Output) Reasoning added in v0.2.17

func (output Output) Reasoning() []Part

Reasoning 返回思考 Part

func (Output) Visible added in v0.2.17

func (output Output) Visible() []Part

Visible 返回非思考 Part

type PageCatalogProvider added in v0.3.0

type PageCatalogProvider interface {
	PageCatalog(ctx context.Context, accountID string, reload bool) (camoufoxnative.PageCatalog, error)
}

PageCatalogProvider 返回账户会话页面载入时目录 RPC 的响应:reload 为 false 时取最近一次载入,账户没有载入过页面时先载入;reload 为 true 时重新载入页面

type PageRunsProtectedTransport added in v0.3.10

type PageRunsProtectedTransport interface {
	// RanBefore 判断账户页面此前运行过 contents 这同一段对话,不记录
	RanBefore(accountID string, contents []Content) bool
}

PageRunsProtectedTransport 是记录账户页面已运行对话的受保护传输

type Part

type Part struct {
	Text                string               `json:"text,omitempty"`
	InlineData          *Blob                `json:"inline_data,omitempty"`
	ExternalMedia       *ExternalMedia       `json:"external_media,omitempty"`
	File                *FileRef             `json:"file,omitempty"`
	Upload              *UploadRef           `json:"upload,omitempty"`
	FunctionCall        *FunctionCall        `json:"function_call,omitempty"`
	FunctionResult      *FunctionResult      `json:"function_result,omitempty"`
	ExecutableCode      *ExecutableCode      `json:"executable_code,omitempty"`
	CodeExecutionResult *CodeExecutionResult `json:"code_execution_result,omitempty"`
	Thought             bool                 `json:"thought,omitempty"`
	ThoughtSignature    string               `json:"thought_signature,omitempty"`
	SpeechMetadata      *SpeechMetadata      `json:"speech_metadata,omitempty"`
	VideoMetadata       *VideoMetadata       `json:"video_metadata,omitempty"`
	// MediaProcessing 为视频处理方式 STATIC 或 AGENTIC
	MediaProcessing string          `json:"media_processing,omitempty"`
	ToolCall        *ServerToolStep `json:"tool_call,omitempty"`
	ToolResponse    *ServerToolStep `json:"tool_response,omitempty"`
	// Transcript 是转录正文附带的说话人和逐词时间
	Transcript *TranscriptMetadata `json:"transcript,omitempty"`
	// DisplayName 是媒体给模型引用的名称
	DisplayName string `json:"display_name,omitempty"`
	// MediaResolution 是该媒体的输入分辨率,取 Gemini API 枚举名
	MediaResolution string `json:"media_resolution,omitempty"`
}

Part 表示规范消息中的一个内容块

func (Part) SignatureOnly added in v0.2.17

func (part Part) SignatureOnly() bool

SignatureOnly 表示 Part 只携带思考签名

type PoolRequestContextProvider

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

PoolRequestContextProvider 从租约账户读取协议上下文

func NewPoolRequestContextProvider

func NewPoolRequestContextProvider(pool *AccountPool) *PoolRequestContextProvider

NewPoolRequestContextProvider 创建账户协议上下文提供者

func (*PoolRequestContextProvider) RequestContext

func (p *PoolRequestContextProvider) RequestContext(_ context.Context, accountID string) (RequestContext, error)

RequestContext 返回账户时区

type PooledService

type PooledService struct {

	// BuildNativeNonstream 让非流式请求优先使用具备资格的 Build 通道
	BuildNativeNonstream bool
	// YouTubeLinks 把 user 文本中的 YouTube 链接作为视频外部媒体发送
	YouTubeLinks bool
	// DiscoverHiddenModels 让同步账户目录时探测官网前端已配置、ListModels 尚未列出的模型
	DiscoverHiddenModels bool
	// StripThoughtSignatures 发送前去掉对话历史中的思考签名
	StripThoughtSignatures bool
	// ContinuationRewrite 改写不接受以 model 轮结尾请求的模型的末尾 assistant 轮
	ContinuationRewrite bool
	// ContinuationPrompt 是改写末尾 assistant 轮时写入系统指令的续写提示词,为空时末尾 assistant 正文作为最后一轮 user
	ContinuationPrompt string
	// contains filtered or unexported fields
}

PooledService 在账户租约内调用协议客户端

func NewPooledService

func NewPooledService(pool *AccountPool, client *Client) *PooledService

NewPooledService 创建多账户协议服务

func (*PooledService) AssistantAccount added in v0.3.0

func (s *PooledService) AssistantAccount(ctx context.Context, request GenerateRequest) string

AssistantAccount 返回 -build 请求的对话可续接的 trajectory 所在账户,没有时返回空

func (*PooledService) CachedModels

func (s *PooledService) CachedModels() []Model

CachedModels 返回启用账户最近同步目录的并集

func (*PooledService) ClearHiddenModels added in v0.3.15

func (s *PooledService) ClearHiddenModels() int

ClearHiddenModels 从内存目录与磁盘目录缓存中移除全部官网隐藏模型,返回发生变化的账户数

func (*PooledService) CopyFileReferencesToLease

func (s *PooledService) CopyFileReferencesToLease(
	ctx context.Context,
	target *AccountLease,
	contents []Content,
) ([]Content, *TemporaryFileCopies, error)

CopyFileReferencesToLease 将文件引用复制到目标账户并返回改写内容

func (*PooledService) CountTokens

func (s *PooledService) CountTokens(ctx context.Context, request TokenCountRequest) (TokenCount, error)

CountTokens 使用支持目标模型的独占账户按客户端给出的对话计数,只有系统指令时以 user 轮计数后还原为系统指令明细

func (*PooledService) CreateDecision added in v0.3.6

func (s *PooledService) CreateDecision(ctx context.Context, request DecisionRequest) (DecisionResult, error)

CreateDecision 以目录中有该模型 createDecision 方法的账户回答决策问题,上游拒绝账户、额度用尽或服务端出错时换到其他账户

func (*PooledService) DeleteFile

func (s *PooledService) DeleteFile(ctx context.Context, fileID string) error

DeleteFile 使用资源创建账户删除 Drive 文件和持久绑定

func (*PooledService) DeleteVideo added in v0.2.8

func (s *PooledService) DeleteVideo(ctx context.Context, operationID string) error

DeleteVideo 删除已结束视频任务的 Drive 结果文件与任务绑定,任务未结束时返回 409

func (*PooledService) DownloadFile

func (s *PooledService) DownloadFile(ctx context.Context, fileID string) (MediaStream, error)

DownloadFile 使用资源创建账户下载 Drive 文件

func (*PooledService) Embed added in v0.2.8

Embed 在支持模型的账户 Build 通道上调用 batchEmbedContents,额度错误写入 build:<模型> 冷却后换账户重试

func (*PooledService) FileMetadata

func (s *PooledService) FileMetadata(ctx context.Context, fileID string) (FileMetadata, error)

FileMetadata 返回公开上传文件的持久元数据

func (*PooledService) Generate

func (s *PooledService) Generate(ctx context.Context, request GenerateRequest) (<-chan Event, error)

Generate 使用支持目标模型的独占账户生成事件流

func (*PooledService) GenerateImage added in v0.2.18

func (s *PooledService) GenerateImage(ctx context.Context, request ImageRequest) ([]GeneratedImage, error)

GenerateImage 以目录中有该模型 predict 方法的账户生成图片,上游拒绝账户、额度用尽或服务端出错时换到其他账户

func (*PooledService) GenerateTitle added in v0.2.15

func (s *PooledService) GenerateTitle(ctx context.Context, request TitleRequest) (string, error)

GenerateTitle 以可调用本次运行模型的账户生成页头标题

func (*PooledService) GenerateVideo

func (s *PooledService) GenerateVideo(ctx context.Context, request VideoRequest) (VideoOperation, error)

GenerateVideo 以经 generateContent 输出视频的模型创建长任务

func (*PooledService) GetGenerateVideoOperation

func (s *PooledService) GetGenerateVideoOperation(ctx context.Context, operationID string) (VideoOperation, error)

GetGenerateVideoOperation 返回视频任务状态:结果视频已绑定时直接返回,否则按本进程的生成状态返回,服务重启前没有生成完成的任务为已结束且没有结果

func (*PooledService) ListFiles added in v0.2.8

func (s *PooledService) ListFiles(ctx context.Context) ([]FileMetadata, error)

ListFiles 返回全部公开上传文件的持久元数据

func (*PooledService) ListVideos added in v0.2.8

func (s *PooledService) ListVideos(ctx context.Context) ([]VideoOperation, error)

ListVideos 刷新全部账户 runtime-state 后返回视频任务的持久元数据,按创建时间从新到旧排列

func (*PooledService) Models

func (s *PooledService) Models(ctx context.Context) ([]Model, error)

Models 刷新可用账户并返回实时模型并集

func (*PooledService) OpenBidi

func (s *PooledService) OpenBidi(ctx context.Context, request BidiRequest) (*BidiSession, error)

OpenBidi 使用支持目标模型的账户创建双向会话

func (*PooledService) ReclaimExpiredResources added in v0.3.1

func (s *PooledService) ReclaimExpiredResources(ctx context.Context) error

ReclaimExpiredResources 删除各账户已到期的资源,没有空闲槽位的账户跳过本轮

func (*PooledService) RefreshAccountModels

func (s *PooledService) RefreshAccountModels(ctx context.Context, accountID string, reload bool) ([]Model, error)

RefreshAccountModels 占用指定账户的一个普通槽位刷新其权益与模型目录,不受账户启用、调度状态与冷却限制;reload 为 true 时重新载入账户页面

func (*PooledService) RefreshAccountState added in v0.2.11

func (s *PooledService) RefreshAccountState(ctx context.Context, accountID string, wait bool) (AccountRefresh, error)

RefreshAccountState 重新载入账户页面读取权益与模型目录,登录失效时标记账户需要登录,因上游要求验证而受限的账户在常驻 Worker 的页面上读取目录后再发一次生成请求核对验证状态;wait 为 true 时等待该账户的一个普通槽位且不受调度状态限制,否则只用就绪账户的空闲槽位

func (*PooledService) RefreshBuildCatalog added in v0.3.15

func (s *PooledService) RefreshBuildCatalog(ctx context.Context, accountID string) (bool, error)

RefreshBuildCatalog 为单个账户拉取并保存 Build 通道模型目录

func (*PooledService) SetRequestOptions added in v0.3.15

func (s *PooledService) SetRequestOptions(opts RequestOptions)

SetRequestOptions 原子替换后续请求与目录同步使用的行为选项,不中断进行中的请求

func (*PooledService) Transcribe

Transcribe 在同一账户租约内完成上传与生成

func (*PooledService) UploadFile

func (s *PooledService) UploadFile(ctx context.Context, request UploadRequest) (FileRef, error)

UploadFile 使用一个独占账户完成上传并保存资源绑定

func (*PooledService) UploadInlineMediaToLease

func (s *PooledService) UploadInlineMediaToLease(
	ctx context.Context,
	target *AccountLease,
	contents []Content,
	temporary *TemporaryFileCopies,
	keepImages bool,
) ([]Content, *TemporaryFileCopies, error)

UploadInlineMediaToLease 把内联附件改写为目标账户 Drive 文件的引用 keepImages 为真时 CreateInteractionStream 可内联的图片保持内联 同一账户已上传过的相同内容直接引用;闲置超过 inlineMediaIdle 的旧文件在本次请求结束时删除 Drive 存储空间已满时没有上传成功的附件保持内联,keepImages 为真时只接受内联图片,仍返回上传错误

func (*PooledService) ValidateGenerateRequest added in v0.2.6

func (s *PooledService) ValidateGenerateRequest(request GenerateRequest) error

ValidateGenerateRequest 在选择账户前校验与上游通道无关的生成参数

func (*PooledService) VerifyAccount added in v0.3.14

func (s *PooledService) VerifyAccount(ctx context.Context, accountID string) error

VerifyAccount 占用指定账户的一个普通槽位同步目录并发一次最小生成请求核对验证状态,正常时解除受限、上游要求验证时标为需要验证

func (*PooledService) VideoFrameTokens added in v0.3.2

func (s *PooledService) VideoFrameTokens(ctx context.Context, request VideoFramesRequest) (int64, error)

VideoFrameTokens 以视频文件所属账户统计按视频设置抽帧后的 token 数,与官网视频附件显示的 token 数相同

type PreparedProtectedRequest

type PreparedProtectedRequest struct {
	Body       []byte
	ProofAt    int
	Headers    http.Header
	Proof      string
	PagePrompt string
}

PreparedProtectedRequest 表示已取得 proof 的请求:Body 为原正文,发送时在 ProofAt 处写入 Proof;PagePrompt 为页面输入框中的提示词,由页面界面运行的请求 proof 为空

func (PreparedProtectedRequest) Payload added in v0.3.11

func (prepared PreparedProtectedRequest) Payload() []byte

Payload 返回写入 proof 后的完整正文

type PromptFeedbackError

type PromptFeedbackError struct {
	Reason        string
	Message       string
	SafetyRatings []SafetyRating
	// Usage 是拦截帧中上游计入的输入用量
	Usage *Usage
	Raw   json.RawMessage
}

PromptFeedbackError 表示上游拒绝当前输入且没有返回候选

func (*PromptFeedbackError) Error

func (e *PromptFeedbackError) Error() string

Error 返回上游输入拒绝原因

func (*PromptFeedbackError) InputBlocked added in v0.3.9

func (e *PromptFeedbackError) InputBlocked() bool

InputBlocked 表示上游按输入本身(安全设置、屏蔽词、禁止内容)拦截请求,同一输入重发仍被拦截

func (*PromptFeedbackError) Unwrap

func (e *PromptFeedbackError) Unwrap() error

Unwrap 将输入拒绝映射为无效请求

type ProtectedPreparer

type ProtectedPreparer interface {
	Prepare(context.Context, ProtectedRequest) (PreparedProtectedRequest, error)
	BrowserStorageState(context.Context) (StorageState, error)
	SendProtected(context.Context, ProtectedRequest) (*RPCResponse, error)
}

ProtectedPreparer 为一次请求写入 fresh WAA proof 并以账户固定指纹发送

type ProtectedPreparerProvider

type ProtectedPreparerProvider interface {
	Worker(context.Context, string, string) (ProtectedPreparer, error)
}

ProtectedPreparerProvider 按账户返回 lazy WAA preparer

type ProtectedRequest

type ProtectedRequest struct {
	URL        string
	Headers    http.Header
	Body       []byte
	ProofAt    int
	Prompt     string
	PagePrompt string
	Proof      string
	// Digest 是直接作为 proof 摘要的 binding,为空时取 Prompt 的 SHA-256
	Digest string
}

ProtectedRequest 表示需要 WAA 保护的 AI Studio 请求,Proof 非空时写入该 proof 并直接发送;ProofAt 是编码 Body 时给出的 WAA proof 字段占位 null 的起始字节

type ProtectedTransport

type ProtectedTransport interface {
	DoProtected(context.Context, GenerateRequest, RPCRequest) (*RPCResponse, error)
}

ProtectedTransport 原子完成 fresh WAA proof、field 5 写入和同 context 发送

type ProtocolEvidenceError

type ProtocolEvidenceError struct {
	Method string
	Path   string
	Detail string
	Raw    json.RawMessage
}

ProtocolEvidenceError 保存无法解释的协议位置和原始值

func (*ProtocolEvidenceError) Error

func (e *ProtocolEvidenceError) Error() string

Error 返回协议证据错误

type ProtocolHeaderProvider

type ProtocolHeaderProvider interface {
	ProtocolHeaders(context.Context, string) (http.Header, error)
}

ProtocolHeaderProvider 按账户提供官方运行时发现的动态公共头

type ProtocolHeaderProviderFunc

type ProtocolHeaderProviderFunc func(context.Context, string) (http.Header, error)

ProtocolHeaderProviderFunc 将函数适配为 ProtocolHeaderProvider

func (ProtocolHeaderProviderFunc) ProtocolHeaders

func (f ProtocolHeaderProviderFunc) ProtocolHeaders(ctx context.Context, accountID string) (http.Header, error)

ProtocolHeaders 调用动态公共头函数

type ProxyPool added in v0.2.12

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

ProxyPool 把未固定代理的账户按绑定数分配到代理池,代理不可用时改绑到其他可用代理

func NewProxyPool added in v0.2.12

func NewProxyPool(pool *AccountPool, proxies []string) *ProxyPool

NewProxyPool 创建代理池,proxies 为空时账户使用系统代理或直连

func (*ProxyPool) Assign added in v0.2.12

func (p *ProxyPool) Assign() ([]string, error)

Assign 为未固定代理的账户绑定代理:保留指向可用代理的已有绑定,其余账户选绑定数最少的可用代理并写入运行状态,返回绑定变化的账户

func (*ProxyPool) Available added in v0.2.12

func (p *ProxyPool) Available(proxy string) bool

Available 判断代理是否在当前参与分配的代理中

func (*ProxyPool) Binding added in v0.2.12

func (p *ProxyPool) Binding(accountID string) string

Binding 返回账户当前绑定的代理池代理,账户固定代理或未绑定时返回空字符串

func (*ProxyPool) Next added in v0.2.12

func (p *ProxyPool) Next() string

Next 返回下一个新账户将绑定的代理,代理池为空时返回空字符串

func (*ProxyPool) Probe added in v0.2.12

func (p *ProxyPool) Probe(ctx context.Context, check func(context.Context, string) error) ([]string, error)

Probe 用 check 逐个检测代理,失败的代理标为不可用,恢复的代理重新参与分配,返回绑定变化的账户

func (*ProxyPool) ReportFailure added in v0.2.12

func (p *ProxyPool) ReportFailure(proxy string, err error) ([]string, error)

ReportFailure 记录经 proxy 发出的请求的网络错误;连续达到阈值且存在其他可用代理时把该代理标为不可用并改绑,返回绑定变化的账户

func (*ProxyPool) ReportSuccess added in v0.2.12

func (p *ProxyPool) ReportSuccess(proxy string)

ReportSuccess 清零 proxy 的连续网络错误

func (*ProxyPool) SetProxies added in v0.3.15

func (p *ProxyPool) SetProxies(previousGlobal string, proxies []string) ([]string, error)

SetProxies 热替换代理池条目并重新分配未固定代理的账户:保留仍在池中代理的健康状态与已有绑定,切回直连时清除账户的代理池绑定;返回实际出口发生变化的账户 ID

func (*ProxyPool) Status added in v0.2.12

func (p *ProxyPool) Status() []ProxyStatus

Status 返回各代理的可用性与当前绑定账户数

type ProxyStatus added in v0.2.12

type ProxyStatus struct {
	Proxy     string     `json:"proxy"`
	Available bool       `json:"available"`
	Accounts  int        `json:"accounts"`
	CheckedAt *time.Time `json:"checked_at,omitempty"`
	Error     string     `json:"error,omitempty"`
}

ProxyStatus 表示代理池中一个代理的可用性与绑定账户数

type QuotaCooldown

type QuotaCooldown struct {
	Until    time.Time
	Global   bool
	Kind     string
	Reason   string
	Escalate bool
	// RequestSize 是被拒请求输入正文的字节数,0 表示未知
	RequestSize int64
}

QuotaCooldown 表示上游额度限制对应的调度冷却

func AccountRejectionCooldown added in v0.3.7

func AccountRejectionCooldown(err error) (QuotaCooldown, bool)

AccountRejectionCooldown 返回上游以 403、协议错误码 7 拒绝账户且官网不跳转拒绝页时的冷却:账户在该模型上自上次成功后第一次被拒只记下不冷却,再被拒时以 planLimitBackoff 递增

func BuildRejectionCooldown added in v0.2.12

func BuildRejectionCooldown(err error) (QuotaCooldown, bool)

BuildRejectionCooldown 返回 Build 代理以参数错误拒绝、同账户 Playground 完成的请求对应的 Build 递增冷却

func QuotaCooldownForError

func QuotaCooldownForError(err error, now time.Time) (QuotaCooldown, bool)

QuotaCooldownForError 解析上游分钟或每日额度限制

type RPCError

type RPCError struct {
	Method     string
	StatusCode int
	Code       int64
	Message    string
	Metadata   map[string]string
	RetryDelay time.Duration
	// PerUserQuota 表示写代码助手步骤失败带每用户额度标记
	PerUserQuota bool
}

RPCError 保存上游状态和协议错误码

func DecodeRPCError added in v0.1.1

func DecodeRPCError(method string, statusCode int, raw []byte) *RPCError

DecodeRPCError 解析独立状态和流式封装中的上游错误

func (*RPCError) ContextOverflow added in v0.2.11

func (e *RPCError) ContextOverflow() bool

ContextOverflow 返回错误是否为上游报告的输入 token 超过模型上限

func (*RPCError) Error

func (e *RPCError) Error() string

Error 返回结构化上游错误

func (*RPCError) HTTPStatus

func (e *RPCError) HTTPStatus() int

HTTPStatus 返回上游 HTTP 状态

func (*RPCError) RetryAt added in v0.2.11

func (e *RPCError) RetryAt(now time.Time) time.Time

RetryAt 返回上游给出的可重试时刻,没有重试时长时返回零值

func (*RPCError) StatusError added in v0.3.7

func (e *RPCError) StatusError() string

StatusError 以 gRPC 状态名代替 HTTP 状态码写出 401 或 403 的上游方法、协议错误码与原因

func (*RPCError) Unwrap added in v0.2.14

func (e *RPCError) Unwrap() error

Unwrap 把官网会跳转拒绝页的错误映射为对应的 camoufoxnative.AccessDenial

type RPCRequest

type RPCRequest struct {
	Method    string
	URL       string
	AccountID string
	RequestID string
	Header    http.Header
	Body      []byte
	// ProofAt 是受保护请求编码 Body 时给出的 WAA proof 字段占位 null 的起始字节
	ProofAt   int
	Streaming bool
}

RPCRequest 描述交给认证传输层的单次 MakerSuite 请求

type RPCResponse

type RPCResponse struct {
	StatusCode int
	Header     http.Header
	Body       io.ReadCloser
	Proof      string
}

RPCResponse 描述认证传输层返回的响应头和实时正文,Proof 为受保护请求写入的 WAA proof

type RPCTransport

type RPCTransport interface {
	Do(context.Context, RPCRequest) (*RPCResponse, error)
}

RPCTransport 负责认证、账户租约、Cookie 写回和真实网络发送

type ReplyToolObserver added in v0.3.15

type ReplyToolObserver struct {
	OnActive       func(enabled bool)
	OnCall         func()
	OnContinuation func()
}

ReplyToolObserver 接收回复工具本次尝试的实际启用状态、每次成功解包 final 与每次 more=true 自动续接时的回调

type RequestContext

type RequestContext struct {
	Timezone string
}

RequestContext 保存账户运行时提供的协议上下文

type RequestContextProvider

type RequestContextProvider interface {
	RequestContext(context.Context, string) (RequestContext, error)
}

RequestContextProvider 按账户返回当前协议上下文

type RequestOptions added in v0.3.15

type RequestOptions struct {
	BuildNativeNonstream   bool
	YouTubeLinks           bool
	DiscoverHiddenModels   bool
	StripThoughtSignatures bool
	ContinuationRewrite    bool
	ContinuationPrompt     string
}

RequestOptions 保存单次请求与目录同步可热替换的行为选项

type RequestPhase

type RequestPhase string

RequestPhase 表示受保护请求的当前准备阶段,Camoufox 界面运行在页面发出 GenerateContent 之前以 camoufoxnative.GenerateStep 的步骤说明为阶段

const (
	// RequestPhasePreparingWAA 表示正在生成 fresh WAA proof
	RequestPhasePreparingWAA RequestPhase = "preparing_waa"
	// RequestPhaseSendingUpstream 表示正在等待 AI Studio 响应头
	RequestPhaseSendingUpstream RequestPhase = "sending_upstream"
	// RequestPhaseStreaming 表示 AI Studio 已经返回流式响应
	RequestPhaseStreaming RequestPhase = "streaming"
)

type ResourceBinding

type ResourceBinding struct {
	Kind      string                 `json:"kind,omitempty"`
	Name      string                 `json:"name,omitempty"`
	MIME      string                 `json:"mime,omitempty"`
	Size      int64                  `json:"size,omitempty"`
	Purpose   string                 `json:"purpose,omitempty"`
	CreatedAt time.Time              `json:"created_at"`
	Video     *VideoResourceMetadata `json:"video,omitempty"`
	// Alias 是客户端上传时指定的公开文件名
	Alias string `json:"alias,omitempty"`
	// SHA256 是文件内容的 SHA-256 摘要,Base64 编码
	SHA256 string `json:"sha256,omitempty"`
	// VideoDuration 是视频文件的时长
	VideoDuration time.Duration `json:"video_duration,omitempty"`
	// UsedAt 是内联附件最近一次被请求引用的时间
	UsedAt time.Time `json:"used_at,omitzero"`
	// DisplayName 是内联附件在请求中给出的文件名
	DisplayName string `json:"display_name,omitempty"`
	// ExpiresAt 是上传文件的到期时间,零值表示不过期
	ExpiresAt time.Time `json:"expires_at,omitzero"`
}

ResourceBinding 记录上游资源的创建账户

type ResponseModality

type ResponseModality string

ResponseModality 表示模型输出模态

const (
	// ResponseModalityText 表示文本输出
	ResponseModalityText ResponseModality = "TEXT"
	// ResponseModalityImage 表示图片输出
	ResponseModalityImage ResponseModality = "IMAGE"
	// ResponseModalityAudio 表示音频输出
	ResponseModalityAudio ResponseModality = "AUDIO"
)

func EffectiveResponseModalities added in v0.2.8

func EffectiveResponseModalities(modalities []ResponseModality, model Model) []ResponseModality

EffectiveResponseModalities 返回对模型实际生效的输出模态:未指定时为媒体模型的默认模态,指定时去掉模型不能生成的模态,与模型能力没有交集时保持原样

type ResponseReadError added in v0.3.14

type ResponseReadError struct {
	Err error
}

ResponseReadError 表示收到上游非 200 响应头后读取错误响应体失败

func (*ResponseReadError) Error added in v0.3.14

func (e *ResponseReadError) Error() string

Error 返回错误文本

func (*ResponseReadError) Unwrap added in v0.3.14

func (e *ResponseReadError) Unwrap() error

Unwrap 返回底层读取错误

type RetrievalConfig added in v0.2.17

type RetrievalConfig struct {
	Latitude     *float64 `json:"latitude,omitempty"`
	Longitude    *float64 `json:"longitude,omitempty"`
	LanguageCode string   `json:"language_code,omitempty"`
}

RetrievalConfig 是 toolConfig.retrievalConfig 的用户坐标与语言代码

type Role

type Role string

Role 表示规范消息角色

const (
	// RoleUser 表示用户消息
	RoleUser Role = "user"
	// RoleAssistant 表示模型消息
	RoleAssistant Role = "assistant"
	// RoleTool 表示工具结果消息
	RoleTool Role = "tool"
)

type SafetyRating added in v0.2.17

type SafetyRating struct {
	Category    string `json:"category"`
	Probability string `json:"probability"`
	Blocked     bool   `json:"blocked,omitempty"`
}

SafetyRating 是候选或输入在一个安全类别上的评级,取值为 Gemini API 枚举名

type SafetySetting added in v0.2.6

type SafetySetting struct {
	Category  string `json:"category"`
	Threshold string `json:"threshold"`
}

SafetySetting 表示一个安全类别的拦截阈值,取 Gemini API 枚举名

type SearchEntryPoint

type SearchEntryPoint struct {
	RenderedContent string `json:"rendered_content,omitempty"`
	SDKBlob         string `json:"sdk_blob,omitempty"`
}

SearchEntryPoint 表示 Google Search 返回的搜索入口

type ServerToolStep added in v0.2.17

type ServerToolStep struct {
	ID   string          `json:"id,omitempty"`
	Type string          `json:"type"`
	Name string          `json:"name,omitempty"`
	Data json.RawMessage `json:"data,omitempty"`
}

ServerToolStep 是上游服务端工具的一次调用或其结果,Type 为 Gemini API ToolType 枚举名,Data 为调用参数或结果

type Service

type Service interface {
	Models(context.Context) ([]Model, error)
	CountTokens(context.Context, TokenCountRequest) (TokenCount, error)
	Generate(context.Context, GenerateRequest) (<-chan Event, error)
}

Service 定义公开协议适配器依赖的最小能力

type Signer

type Signer struct{}

Signer 为 AI Studio 请求生成三段 SAPISID 授权头

func NewSigner

func NewSigner() *Signer

NewSigner 创建 AI Studio 官方来源的签名器

func (*Signer) Authorization

func (s *Signer) Authorization(state StorageState) (string, error)

Authorization 使用当前时间生成授权头

func (*Signer) AuthorizationAt

func (s *Signer) AuthorizationAt(state StorageState, now time.Time) (string, error)

AuthorizationAt 使用指定时间生成授权头

func (*Signer) OriginHashes added in v0.3.8

func (s *Signer) OriginHashes(state StorageState) (string, error)

OriginHashes 返回不带时间戳的三段 SAPISID 摘要,官网 play.google.com/log 上报以它作 auth 参数与 Authorization 头

type SpeakerVoiceConfig

type SpeakerVoiceConfig struct {
	Speaker   string `json:"speaker"`
	VoiceName string `json:"voice_name"`
	// Voice 是 VoiceConfig.voice 的说话人标识,取预置音色名或已存音色 ID
	Voice string `json:"voice,omitempty"`
}

SpeakerVoiceConfig 表示多说话人的声音选择

type SpeechConfig

type SpeechConfig struct {
	VoiceName string               `json:"voice_name,omitempty"`
	Voice     string               `json:"voice,omitempty"`
	Speakers  []SpeakerVoiceConfig `json:"speakers,omitempty"`
	// LanguageCode 是 BCP-47 语言代码
	LanguageCode string `json:"language_code,omitempty"`
	// Mode 表示多说话人朗读模式 VERBATIM 或 CONVERSATIONAL
	Mode string `json:"mode,omitempty"`
}

SpeechConfig 表示语音生成参数

type SpeechMetadata added in v0.2.0

type SpeechMetadata struct {
	Speaker string `json:"speaker,omitempty"`
	Style   string `json:"style,omitempty"`
}

SpeechMetadata 表示语音文本分段的说话人与风格

type StateCookie

type StateCookie struct {
	Name         string  `json:"name"`
	Value        string  `json:"value"`
	Domain       string  `json:"domain"`
	Path         string  `json:"path"`
	Expires      float64 `json:"expires"`
	HTTPOnly     bool    `json:"httpOnly"`
	Secure       bool    `json:"secure"`
	SameSite     string  `json:"sameSite"`
	PartitionKey string  `json:"partitionKey,omitempty"`
}

StateCookie 表示 Playwright storage state 中的 Cookie

type StaticFetcher added in v0.3.7

type StaticFetcher interface {
	FetchStatic(ctx context.Context, accountID string, address string) ([]byte, error)
}

StaticFetcher 经账户出口读取官网静态资源

type StorageItem

type StorageItem struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

StorageItem 表示浏览器本地存储项

type StorageOrigin

type StorageOrigin struct {
	Origin       string        `json:"origin"`
	LocalStorage []StorageItem `json:"localStorage"`
}

StorageOrigin 表示 Playwright storage state 中的站点数据

type StorageState

type StorageState struct {
	Cookies []StateCookie   `json:"cookies"`
	Origins []StorageOrigin `json:"origins"`
	// contains filtered or unexported fields
}

StorageState 表示可原样写回的 Playwright storage state

func LoadStorageState

func LoadStorageState(filePath string) (StorageState, error)

LoadStorageState 读取并校验 Playwright storage state

func ParseCookieText added in v0.2.14

func ParseCookieText(input string) (StorageState, error)

ParseCookieText 把 Cookie 请求头、浏览器扩展导出的 JSON 或 Netscape cookies.txt 转为 storage state,只保留 google.com 及其子域的 Cookie

func (StorageState) AuthExtension

func (s StorageState) AuthExtension() (AuthExtension, bool, error)

AuthExtension 返回 aistudio2api 认证扩展

func (StorageState) BoundCookieLifetime added in v0.3.3

func (s StorageState) BoundCookieLifetime(session BoundSession, now time.Time) time.Duration

BoundCookieLifetime 按 Chromium MinimumBoundCookieLifetime 返回 DBSC 会话绑定 Cookie 中最早到期者的剩余时间,缺少或已到期时为 0

func (StorageState) CookieHeader

func (s StorageState) CookieHeader(targetURL string, now time.Time) (string, error)

CookieHeader 为目标 URL 构造当前有效的 Cookie 请求头

func (StorageState) CookieValue

func (s StorageState) CookieValue(name string, targetURL string, now time.Time) (string, bool)

CookieValue 返回目标 URL 下最具体的同名 Cookie

func (StorageState) DeviceBoundSession added in v0.3.14

func (s StorageState) DeviceBoundSession() bool

DeviceBoundSession 表示会话带 __Secure-1PSIDRTS 且缺少本地 Chrome OAuth 续签材料,属于约 2 小时内失效的设备绑定副本

func (StorageState) HasBoundCookie added in v0.3.14

func (s StorageState) HasBoundCookie() bool

HasBoundCookie 表示认证状态包含设备绑定的 __Secure-1PSIDRTS Cookie

func (StorageState) MarshalJSON

func (s StorageState) MarshalJSON() ([]byte, error)

MarshalJSON 保留 storage state 的扩展根字段

func (*StorageState) MergeSetCookieHeaders

func (s *StorageState) MergeSetCookieHeaders(headers []string, sourceURL string, now time.Time) error

MergeSetCookieHeaders 将响应轮换的 Cookie 合并到 storage state,替换的 Cookie 保留原有位置

func (*StorageState) SetAuthExtension

func (s *StorageState) SetAuthExtension(extension AuthExtension)

SetAuthExtension 写入 aistudio2api 认证扩展

func (*StorageState) UnmarshalJSON

func (s *StorageState) UnmarshalJSON(data []byte) error

UnmarshalJSON 解析 storage state 并保存扩展根字段

func (StorageState) Validate

func (s StorageState) Validate() error

Validate 校验 storage state 的浏览器字段

type StreamInterruptedError added in v0.2.13

type StreamInterruptedError struct {
	Method string
	Frames int
	Err    error
}

StreamInterruptedError 表示上游生成流在完成帧之前中断或结束

func (*StreamInterruptedError) Error added in v0.2.13

func (e *StreamInterruptedError) Error() string

Error 返回中断前已接收的帧数与读取错误

func (*StreamInterruptedError) Unwrap added in v0.2.13

func (e *StreamInterruptedError) Unwrap() error

Unwrap 返回读取错误

type TemporaryFileCopies

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

TemporaryFileCopies 保存一次请求创建的临时 Drive 文件

func (*TemporaryFileCopies) Cleanup

func (copies *TemporaryFileCopies) Cleanup() error

Cleanup 在目标账户租约释放前删除全部临时 Drive 副本

func (*TemporaryFileCopies) Count

func (copies *TemporaryFileCopies) Count() int

Count 返回本次请求创建的临时文件数

func (*TemporaryFileCopies) ForgetMissingInlineMedia added in v0.2.18

func (copies *TemporaryFileCopies) ForgetMissingInlineMedia(ctx context.Context, cause error) (bool, error)

ForgetMissingInlineMedia 在生成请求返回 404 时查询本次复用的内联附件文件,解除 Drive 中已不存在的文件的绑定,返回是否有复用的文件已不存在

func (*TemporaryFileCopies) SourceAccountIDs

func (copies *TemporaryFileCopies) SourceAccountIDs() []string

SourceAccountIDs 返回临时文件的来源账户

type ThinkingBudget added in v0.2.14

type ThinkingBudget struct {
	Default    *int64 `json:"default,omitempty"`
	Max        *int64 `json:"max,omitempty"`
	Min        *int64 `json:"min,omitempty"`
	CanDisable *bool  `json:"can_disable,omitempty"`
}

ThinkingBudget 是 ListModels field 72 的思考预算配置

type TitleProtectedTransport added in v0.2.15

type TitleProtectedTransport interface {
	DoProtectedTitle(context.Context, TitleRequest, RPCRequest) (*RPCResponse, error)
}

TitleProtectedTransport 原子完成 GenerateTitle fresh WAA proof、field 3 写入和同 context 发送

type TitleRequest added in v0.2.15

type TitleRequest struct {
	Model  string
	Prompt string
	Answer string
}

TitleRequest 是试用页按提示词与回答生成页头标题的请求,Model 为本次运行的模型

type TitleService added in v0.2.15

type TitleService interface {
	GenerateTitle(context.Context, TitleRequest) (string, error)
}

TitleService 生成试用页页头标题

type TokenCount

type TokenCount struct {
	InputTokens int64 `json:"input_tokens"`
	// PromptTokensDetails 是按模态细分的输入 token 数
	PromptTokensDetails []ModalityTokenCount `json:"prompt_tokens_details,omitempty"`
	// System 是系统指令各 Part 的 token 数,上游未给出时为 nil
	System *ContentTokens `json:"system,omitempty"`
	// Contents 是各 content 的逐 Part 与角色 token 数
	Contents []ContentTokens `json:"contents,omitempty"`
	// Tools 是各工具的 token 数
	Tools []ToolTokens `json:"tools,omitempty"`
}

TokenCount 表示上游返回的权威计数

func DecodeBuildCountTokensResponse added in v0.2.17

func DecodeBuildCountTokensResponse(source io.Reader) (TokenCount, error)

DecodeBuildCountTokensResponse 解码 ProxyUnaryCall 返回的 CountTokensResponse

func ParseTokenCount

func ParseTokenCount(source io.Reader) (TokenCount, error)

ParseTokenCount 解码 CountTokens field 1

type TokenCountRequest

type TokenCountRequest struct {
	Model    string    `json:"model"`
	System   []string  `json:"system,omitempty"`
	Contents []Content `json:"contents"`
	Tools    Tools     `json:"tools,omitempty"`
	// MediaResolution 为请求级输入媒体分辨率,取 Gemini API 枚举名
	MediaResolution string `json:"media_resolution,omitempty"`
}

TokenCountRequest 表示计数请求

type ToolConfig

type ToolConfig struct {
	Mode                 string   `json:"mode,omitempty"`
	AllowedFunctionNames []string `json:"allowed_function_names,omitempty"`
	ParallelCalls        *bool    `json:"parallel_calls,omitempty"`
	// ServerSideInvocations 要求响应包含服务端工具的调用与结果 Part
	ServerSideInvocations bool `json:"server_side_invocations,omitempty"`
	// Retrieval 是 Google 工具使用的用户位置与语言
	Retrieval *RetrievalConfig `json:"retrieval,omitempty"`
}

ToolConfig 表示工具启用策略

type ToolTokens added in v0.2.17

type ToolTokens struct {
	FunctionDeclarationTokens []int64 `json:"functionDeclarationTokens,omitempty"`
}

ToolTokens 是一个工具的逐函数声明 token 数

type Tools

type Tools struct {
	Functions    []FunctionDeclaration `json:"functions,omitempty"`
	Google       []string              `json:"google,omitempty"`
	GoogleSearch *GoogleSearchOptions  `json:"google_search,omitempty"`
	URLContext   *URLContextOptions    `json:"url_context,omitempty"`
	// MapsWidget 要求 Google Maps 在来源信息中返回 widget context token
	MapsWidget  bool         `json:"maps_widget,omitempty"`
	ComputerUse *ComputerUse `json:"computer_use,omitempty"`
	MCPServers  []MCPServer  `json:"mcp_servers,omitempty"`
	// FileSearch 是 Gemini API fileSearch 工具的原始设置
	FileSearch json.RawMessage `json:"file_search,omitempty"`
	ToolConfig ToolConfig      `json:"tool_config,omitempty"`
	// Explicit 表示请求带有工具列表字段,agent 只使用列出的工具,空列表时不使用工具
	Explicit bool `json:"-"`
}

Tools 表示一次请求启用的工具

type TranscriptDuration

type TranscriptDuration struct {
	Seconds int64 `json:"seconds"`
	Nanos   int64 `json:"nanos,omitempty"`
}

TranscriptDuration 表示转录时间值

type TranscriptMetadata

type TranscriptMetadata struct {
	Text    string           `json:"text"`
	Speaker string           `json:"speaker,omitempty"`
	Words   []TranscriptWord `json:"words,omitempty"`
}

TranscriptMetadata 表示转录正文附带的说话人和逐词时间

type TranscriptWord added in v0.2.17

type TranscriptWord struct {
	Word  string             `json:"word"`
	Start TranscriptDuration `json:"start"`
	End   TranscriptDuration `json:"end"`
}

TranscriptWord 是转录中的一个词与起止时间

type TranscriptionConfig

type TranscriptionConfig struct {
	WordTimestamps     bool     `json:"word_timestamps,omitempty"`
	SpeakerLabels      bool     `json:"speaker_labels,omitempty"`
	CustomVocabulary   []string `json:"custom_vocabulary,omitempty"`
	LanguageCodes      []string `json:"language_codes,omitempty"`
	SmartTranscription bool     `json:"smart_transcription,omitempty"`
	// AdaptationPhrases 是提高识别率的短语
	AdaptationPhrases []string `json:"adaptation_phrases,omitempty"`
	// LanguageHints 是音频中可能出现的语言代码
	LanguageHints []string `json:"language_hints,omitempty"`
	// LanguageAuto 要求模型自动检测语言
	LanguageAuto bool `json:"language_auto,omitempty"`
}

TranscriptionConfig 表示音频转录参数

type TranscriptionRequest

type TranscriptionRequest struct {
	ID                    string
	Model                 string
	Name                  string
	MIME                  string
	Size                  int64
	Reader                io.ReadSeeker
	Config                GenerationConfig
	CandidateAccountIDs   []string
	RecoverWAARuntime     func(context.Context, string, error) (bool, error)
	ObserveAccountFailure func(string, error)
	// Emit 不为空时按到达顺序接收每个正文事件,已交出正文的请求失败后不再换账户重试
	Emit func(Event) error
}

TranscriptionRequest 表示一次音频上传与转录请求

type TranscriptionResult

type TranscriptionResult struct {
	Text          string
	Segments      []TranscriptMetadata
	Usage         Usage
	FinishReason  string
	ProviderModel string
	FirstEvent    time.Duration
	FirstContent  time.Duration
	// contains filtered or unexported fields
}

TranscriptionResult 表示完整转录及其上游元数据

type TranscriptionService

type TranscriptionService interface {
	Transcribe(context.Context, TranscriptionRequest) (TranscriptionResult, error)
}

TranscriptionService 定义音频转录公开端点所需能力

type URLContextOptions added in v0.2.18

type URLContextOptions struct {
	AllowedDomains []string `json:"allowed_domains,omitempty"`
	BlockedDomains []string `json:"blocked_domains,omitempty"`
}

URLContextOptions 表示 URL Context 可读取与不可读取的域名

type URLMetadata added in v0.2.14

type URLMetadata struct {
	RetrievedURL string `json:"retrieved_url"`
	Status       string `json:"status"`
}

URLMetadata 表示 URL context 工具读取的一个网址与读取结果

type UnverifiedProtocolError

type UnverifiedProtocolError struct {
	Feature string
}

UnverifiedProtocolError 表示请求使用了尚未验证的协议能力

func (*UnverifiedProtocolError) Error

func (e *UnverifiedProtocolError) Error() string

Error 返回未验证协议能力的说明

type UploadFields added in v0.3.1

type UploadFields struct {
	Purpose      string
	ExpiresAfter time.Duration
}

UploadFields 是上传请求中可以位于文件内容之后的字段

type UploadRef added in v0.2.13

type UploadRef struct {
	MIME string `json:"mime"`
	Path string `json:"path"`
	Name string `json:"name"`
	Size int64  `json:"size"`
}

UploadRef 表示经 AI Studio /_/upload 上传的附件引用

type UploadRequest

type UploadRequest struct {
	AccountID string
	// Alias 是客户端指定的公开文件名
	Alias   string
	Name    string
	MIME    string
	Purpose string
	Size    int64
	MaxSize int64
	Reader  io.Reader
	// ExpiresAfter 是文件自上传起的有效期,为 0 时不过期
	ExpiresAfter time.Duration
	// ResolveFields 在文件内容上传后返回最终的用途与有效期,非空时取代 Purpose 与 ExpiresAfter
	ResolveFields func(context.Context) (UploadFields, error)
	// Folder 是 GetAppFolder 返回的应用文件夹 ID,已知长度的上传放入该文件夹
	Folder string
}

UploadRequest 表示一次 Drive 文件上传

type Usage

type Usage struct {
	InputTokens         int64 `json:"input_tokens"`
	CachedTokens        int64 `json:"cached_tokens,omitempty"`
	OutputTokens        int64 `json:"output_tokens"`
	ReasoningTokens     int64 `json:"reasoning_tokens,omitempty"`
	ToolTokens          int64 `json:"tool_tokens,omitempty"`
	TotalTokens         int64 `json:"total_tokens"`
	OutputTokensMissing bool  `json:"-"`
	// Details 是上游按模态细分的用量与服务等级
	Details *UsageDetails `json:"-"`
}

Usage 表示一次生成的 token 用量,CachedTokens 是 InputTokens 中命中上游缓存的部分

type UsageDetails added in v0.2.17

type UsageDetails struct {
	PromptTokensDetails        []ModalityTokenCount `json:"promptTokensDetails,omitempty"`
	CacheTokensDetails         []ModalityTokenCount `json:"cacheTokensDetails,omitempty"`
	CandidatesTokensDetails    []ModalityTokenCount `json:"candidatesTokensDetails,omitempty"`
	ToolUsePromptTokensDetails []ModalityTokenCount `json:"toolUsePromptTokensDetails,omitempty"`
	ServiceTier                string               `json:"serviceTier,omitempty"`
	// BilledToolCalls、ToolCallStats、ModelInvocationTokenCounts、RawPromptTokenCount 与 NonGroundingModelInvocationTokenCounts 是 Gemini API 输出但不在公开定义中的用量字段
	BilledToolCalls                        json.RawMessage `json:"billedToolCalls,omitempty"`
	ToolCallStats                          json.RawMessage `json:"toolCallStats,omitempty"`
	ModelInvocationTokenCounts             json.RawMessage `json:"modelInvocationTokenCounts,omitempty"`
	RawPromptTokenCount                    int64           `json:"rawPromptTokenCount,omitempty"`
	NonGroundingModelInvocationTokenCounts json.RawMessage `json:"nonGroundingModelInvocationTokenCounts,omitempty"`
}

UsageDetails 是 Gemini API usageMetadata 的模态细分与服务等级

type VideoConfig added in v0.2.14

type VideoConfig struct {
	AspectRatio     string `json:"aspect_ratio,omitempty"`
	DurationSeconds int64  `json:"duration_seconds,omitempty"`
	Resolution      string `json:"resolution,omitempty"`
	Task            string `json:"task,omitempty"`
}

VideoConfig 是 Omni 视频输出设置:宽高比、时长秒数、分辨率与任务,未设置的项使用模型默认值

type VideoFrameService added in v0.3.2

type VideoFrameService interface {
	VideoFrameTokens(context.Context, VideoFramesRequest) (int64, error)
}

VideoFrameService 统计视频文件按视频设置抽帧后的 token 数

type VideoFramesRequest added in v0.3.2

type VideoFramesRequest struct {
	Model         string
	FileID        string
	VideoMetadata *VideoMetadata
}

VideoFramesRequest 是按 Drive 视频文件抽帧并统计 token 数的请求,VideoMetadata 为视频设置的截取与帧率

type VideoImage

type VideoImage struct {
	InlineData *Blob
	File       *FileRef
}

VideoImage 表示视频起始帧或参考图

type VideoMetadata added in v0.2.17

type VideoMetadata struct {
	StartOffset string   `json:"start_offset,omitempty"`
	EndOffset   string   `json:"end_offset,omitempty"`
	FPS         *float64 `json:"fps,omitempty"`
}

VideoMetadata 是视频 Part 的截取起止与采样帧率,起止为 Duration 字符串

type VideoOperation

type VideoOperation struct {
	ID        string
	Done      bool
	File      *FileRef
	Model     string
	Seconds   string
	Size      string
	CreatedAt time.Time
	// Prompt 是创建任务时的提示词
	Prompt string
	// CompletedAt 是结果视频登记时的 Unix 秒数,未完成时为 0
	CompletedAt int64
	// ExpiresAt 是结果视频到期删除的 Unix 秒数,没有结果视频时为 0
	ExpiresAt int64
	// Missing 为结果已无法得到的已结束任务的说明
	Missing string
	// Failure 为视频生成失败的错误
	Failure error
}

VideoOperation 表示视频长任务状态

type VideoRequest

type VideoRequest struct {
	Model           string
	Prompt          string
	AspectRatio     string
	DurationSeconds int
	Resolution      string
	AccountID       string
	NegativePrompt  string
	StartImage      *VideoImage
	LastImage       *VideoImage
	ReferenceImages []*VideoImage
	// TaskContext 返回后台视频任务的上下文:生成服务停止时取消,期限从任务开始计算
	TaskContext func() (context.Context, context.CancelFunc, error)
}

VideoRequest 表示一次生成一个视频的长任务请求

type VideoResourceMetadata

type VideoResourceMetadata struct {
	Model   string `json:"model"`
	Seconds string `json:"seconds"`
	Size    string `json:"size"`
	File    string `json:"file,omitempty"`
	// Prompt 是创建任务时的提示词
	Prompt string `json:"prompt,omitempty"`
	// CompletedAt 是结果视频登记时的 Unix 秒数
	CompletedAt int64 `json:"completed_at,omitempty"`
}

VideoResourceMetadata 保存 OpenAI 视频对象的持久字段与可下载的结果文件

type VideoService

type VideoService interface {
	GenerateVideo(context.Context, VideoRequest) (VideoOperation, error)
	GetGenerateVideoOperation(context.Context, string) (VideoOperation, error)
	DownloadFile(context.Context, string) (MediaStream, error)
	ListVideos(context.Context) ([]VideoOperation, error)
	DeleteVideo(context.Context, string) error
}

VideoService 定义长任务视频适配器依赖的能力

type VoiceDetail added in v0.2.14

type VoiceDetail struct {
	Name         string   `json:"name"`
	SampleURL    string   `json:"sample_url,omitempty"`
	Pitch        string   `json:"pitch,omitempty"`
	Descriptions []string `json:"descriptions,omitempty"`
	Locale       string   `json:"locale,omitempty"`
	Accent       string   `json:"accent,omitempty"`
	Gender       string   `json:"gender,omitempty"`
	Trait        string   `json:"trait,omitempty"`
	UseCase      string   `json:"use_case,omitempty"`
}

VoiceDetail 是一个音色的试听地址、音高、描述、口音、性别、特质与用途

type WeightedPrompt added in v0.2.8

type WeightedPrompt struct {
	Text   string  `json:"text"`
	Weight float64 `json:"weight"`
}

WeightedPrompt 表示实时音乐的一条加权提示词

type WorkerPhase

type WorkerPhase string

WorkerPhase 表示账户 runtime 当前阶段

const (
	// WorkerReady 表示 runtime 可以接受请求
	WorkerReady WorkerPhase = "ready"
	// WorkerBusy 表示 runtime 正在处理受保护请求
	WorkerBusy WorkerPhase = "busy"
	// WorkerClosing 表示 runtime 正在关闭
	WorkerClosing WorkerPhase = "closing"
	// WorkerClosed 表示 runtime 已关闭
	WorkerClosed WorkerPhase = "closed"
	// WorkerFailed 表示 runtime 已失效
	WorkerFailed WorkerPhase = "failed"
)

type WorkerProtectedTransport

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

WorkerProtectedTransport 将 fresh proof 交给同租约 HTTP 传输

func NewWorkerProtectedTransport

func NewWorkerProtectedTransport(options WorkerProtectedTransportOptions) *WorkerProtectedTransport

NewWorkerProtectedTransport 创建基于 lazy WAA preparer 的受保护传输

func (*WorkerProtectedTransport) DoProtected

func (t *WorkerProtectedTransport) DoProtected(ctx context.Context, request GenerateRequest, rpc RPCRequest) (*RPCResponse, error)

DoProtected 写入 fresh proof 后经账户的 WAA 运行时发送 GenerateContent、Build 代理或写代码助手请求,binding 与写入页面输入框的提示词取自关联函数结果后的 contents,页面提示词为最后一个轮次的文本;账户页面再次运行同一对话的 GenerateContent 按官网 Rerun 不写入提示词

func (*WorkerProtectedTransport) DoProtectedApplet added in v0.3.8

func (t *WorkerProtectedTransport) DoProtectedApplet(ctx context.Context, request AppletProtectedRequest, rpc RPCRequest) (*RPCResponse, error)

DoProtectedApplet 写入 fresh proof 后经账户的 WAA 运行时发送 Build 应用与云项目 RPC,页面输入框为空

func (*WorkerProtectedTransport) DoProtectedBuild added in v0.2.8

func (t *WorkerProtectedTransport) DoProtectedBuild(ctx context.Context, selection AccountSelection, page string, rpc RPCRequest) (*RPCResponse, error)

DoProtectedBuild 把 page 写入页面提示词并写入 fresh proof 后通过账户 Worker 发送 Build 代理请求,binding 为路径与请求体

func (*WorkerProtectedTransport) DoProtectedDecision added in v0.3.6

func (t *WorkerProtectedTransport) DoProtectedDecision(ctx context.Context, request DecisionRequest, rpc RPCRequest) (*RPCResponse, error)

DoProtectedDecision 写入 CreateDecision fresh proof 后经账户的 WAA 运行时发送,binding 为输入各块以空格连接,页面输入框为空

func (*WorkerProtectedTransport) DoProtectedImage added in v0.2.18

func (t *WorkerProtectedTransport) DoProtectedImage(ctx context.Context, request ImageRequest, rpc RPCRequest) (*RPCResponse, error)

DoProtectedImage 写入 GenerateImage fresh proof 后经 Worker 页面发送请求,binding 与页面输入框均为提示词

func (*WorkerProtectedTransport) DoProtectedTitle added in v0.2.15

func (t *WorkerProtectedTransport) DoProtectedTitle(ctx context.Context, request TitleRequest, rpc RPCRequest) (*RPCResponse, error)

DoProtectedTitle 写入 GenerateTitle fresh proof 后经 Worker 页面发送请求,binding 为提示词与回答以空格连接,页面输入框为空

func (*WorkerProtectedTransport) OpenBidiProtected

func (t *WorkerProtectedTransport) OpenBidiProtected(
	ctx context.Context,
	request BidiRequest,
	runtime RequestContext,
	lease *AccountLease,
	release func() error,
) (*BidiSession, error)

OpenBidiProtected 使用当前租约建立 WebChannel 会话

func (*WorkerProtectedTransport) RanBefore added in v0.3.10

func (t *WorkerProtectedTransport) RanBefore(accountID string, contents []Content) bool

RanBefore 判断账户页面此前运行过 contents 这同一段对话,不记录

func (*WorkerProtectedTransport) SetSetupTimeout added in v0.3.15

func (t *WorkerProtectedTransport) SetSetupTimeout(timeout time.Duration)

SetSetupTimeout 更新后续实时会话建连使用的初始化超时

type WorkerProtectedTransportOptions

type WorkerProtectedTransportOptions struct {
	Transport    *MakerSuiteHTTPTransport
	Workers      ProtectedPreparerProvider
	SetupTimeout time.Duration
}

WorkerProtectedTransportOptions 定义受保护请求的 proof 与 HTTP 依赖

type WorkerState

type WorkerState struct {
	AccountID string
	Phase     WorkerPhase
	PID       int
	RuntimeID string
	PageURL   string
}

WorkerState 表示账户 runtime 的可观察状态

Jump to

Keyboard shortcuts

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