aistudio

package
v0.2.17 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 67 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 DefaultTranscriptionModel = "gemini-3.5-transcribe"

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("账户不存在")
	// 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

Functions

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 ContextWithAccountLease

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

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

func ContextWithAccountSelectionObserver

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

ContextWithAccountSelectionObserver 观察请求最终选择的账户

func ContextWithRequestPhaseObserver

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

ContextWithRequestPhaseObserver 记录受保护请求阶段

func ContextWithStreamActivityObserver

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

ContextWithStreamActivityObserver 记录上游响应体实际到达的字节

func ContextWithUpstreamModeObserver added in v0.2.2

func ContextWithUpstreamModeObserver(ctx context.Context, observer func(string, string, 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 响应:field 1 为消息列表,其后可带 google.rpc 状态

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 DefaultAccountLocale

func DefaultAccountLocale() string

DefaultAccountLocale 返回当前用户的系统语言

func DefaultAccountTimezone

func DefaultAccountTimezone() string

DefaultAccountTimezone 返回当前用户的 IANA 时区

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, applet string, requestID string) ([]byte, error)

EncodeAssistantRequest 编码 CodeAssistantOffline:field 1 对话轮、6 模式、8 模型、9 自定义指令、12 应用、14 框架、16、19 思考配置、29 请求 ID,field 2 由 WAA proof 写入

func EncodeBidiMediaEndRequest

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

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

func EncodeBidiMediaRequest

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

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

func EncodeBidiSetupRequest

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

EncodeBidiSetupRequest 编码 Live 或 Robotics 的已验证 setup 帧

func EncodeBidiTextRequest

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

EncodeBidiTextRequest 编码官网文本输入帧

func EncodeBidiToolResponseRequest

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

EncodeBidiToolResponseRequest 编码官网函数响应帧

func EncodeBuildBidiSetup added in v0.2.8

func EncodeBuildBidiSetup(request BidiRequest) ([]byte, 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, error)

EncodeBuildProxyRequest 编码代理请求:ProxyStreamedCall 为 [路径, 请求体, WAA proof],ProxyUnaryCall 追加 HTTP 方法

func EncodeCountTokensRequest

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

EncodeCountTokensRequest 编码 CountTokens 请求

func EncodeGenerateContentRequest

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

EncodeGenerateContentRequest 编码 GenerateContent 数组

func EncodeGenerateVideoRequest

func EncodeGenerateVideoRequest(request VideoRequest) ([]byte, error)

EncodeGenerateVideoRequest 编码当前网页 GenerateVideo 数组协议,提示词为空时提示词位与官网一样为 null

func EncodeGetGenerateVideoOperationRequest

func EncodeGetGenerateVideoOperationRequest(operationID string) ([]byte, error)

EncodeGetGenerateVideoOperationRequest 编码当前网页轮询数组协议

func EncodeGetInteractionStreamRequest added in v0.2.14

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

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

func IsVideoModel added in v0.2.15

func IsVideoModel(model Model) bool

IsVideoModel 表示模型能完成视频长任务:目录提供 predictLongRunning,或经 generateContent 输出视频(如 Omni)

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

func SignAuthorization(cookies []StateCookie, origin string, timestamp int64) (string, error)

SignAuthorization 为指定来源和时间生成三段授权头

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 WriteStorageState

func WriteStorageState(filePath string, state StorageState) error

WriteStorageState 原子写回 Playwright storage state

Types

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
	Active        int
	AvailableSlot int
}

AccountCandidateState 表示账户候选的实时调度指标

type AccountConfig

type AccountConfig struct {
	Label    string `json:"label"`
	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) AuthGeneration added in v0.2.17

func (l *AccountLease) AuthGeneration() uint64

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

func (*AccountLease) BeginAuthRefresh

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

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

func (*AccountLease) BindFileResource

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

BindFileResource 保存上传文件的账户绑定与公开元数据,metadata 提供大小、用途、公开文件名、摘要与视频时长

func (*AccountLease) BindResource

func (l *AccountLease) BindResource(resourceID string, kind string) error

BindResource 将资源固定到当前租约账户

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

func (l *AccountLease) MarkAuthenticationRequired(reason string) error

MarkAuthenticationRequired 保存当前租约确认的认证失败状态

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

func (l *AccountLease) ModelAccessGeneration() uint64

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

func (*AccountLease) RefreshStorageState

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

RefreshStorageState 为 generation 下失效的认证提交一次新认证,generation 之后已有提交时直接复用

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 替换账户最新持久状态

func (*AccountLease) ReplaceResource

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

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

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 之后已经提交的新认证

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

func (p *AccountPool) Acquire(ctx context.Context, model string) (*AccountLease, error)

Acquire 为模型轮询获取一个账户槽位

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

func (p *AccountPool) BindResource(resourceID string, accountID string) error

BindResource 将资源 ID 固定到创建账户

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 初始化模型

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) 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) 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) EnabledAccounts added in v0.1.6

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

EnabledAccounts 返回已启用账户 ID 与其中 ready 或 busy 的账户数量

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) InteractionAgentModel added in v0.2.17

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

InteractionAgentModel 判断模型是否为经 CreateInteraction 后台任务生成的 Interactions 代理模型,如 Deep Research

func (*AccountPool) ListFiles added in v0.2.8

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

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

func (*AccountPool) ListVideos added in v0.2.8

func (p *AccountPool) ListVideos(ctx context.Context) ([]VideoOperation, error)

ListVideos 刷新全部账户 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, error)

MarkQuotaCooldownIfGeneration 保存当前目录版本下的额度冷却,返回实际生效的冷却期限;递增冷却被较新结果跳过时返回零值

func (*AccountPool) MarkReady

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

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

func (*AccountPool) MarkUnavailable

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

MarkUnavailable 将账户标记为初始化或运行失败

func (*AccountPool) ModelAccessGeneration

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

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

func (*AccountPool) ModelRequiresSubscription added in v0.2.11

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

ModelRequiresSubscription 判断账户实时目录中的模型是否只对 Pro 或 Ultra 权益开放

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) []string

PreferWarmPool 按权益分层轮选初始热账户

func (*AccountPool) PublicModels added in v0.2.10

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

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

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) 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) SetModelChannels added in v0.2.14

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

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

func (*AccountPool) SetPerAccountConcurrency added in v0.2.11

func (p *AccountPool) SetPerAccountConcurrency(limit int)

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

func (*AccountPool) SetRoutingStrategy

func (p *AccountPool) SetRoutingStrategy(strategy string)

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

func (*AccountPool) SetUpstreamChannels added in v0.2.0

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

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

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

func (p *AccountPool) UnbindResource(resourceID string) error

UnbindResource 删除终态资源的账户映射

func (*AccountPool) VideoMethod added in v0.2.15

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

VideoMethod 返回模型创建视频任务所用的上游方法:经 generateContent 输出视频的模型为 generateContent,其余为 predictLongRunning

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
	PlaygroundOnly    bool
	BuildOnly         bool
	Channel           Channel
	PreferredChannel  Channel
	// 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"
	// AccountUnavailable 表示账户初始化或运行失败
	AccountUnavailable AccountState = "unavailable"
	// AccountDisabled 表示账户已停用
	AccountDisabled AccountState = "disabled"
)

type AccountStatus

type AccountStatus struct {
	ID          string                   `json:"id"`
	Label       string                   `json:"label"`
	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"`
}

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

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

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

Load 扫描账户目录并恢复冷却与资源粘性

type AccountsNotReadyError added in v0.1.5

type AccountsNotReadyError struct {
	Reasons []string
}

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 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 返回额度耗尽对应的公开状态码

func (*AllCoolingError) RetryAt added in v0.2.11

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

RetryAt 返回最早恢复的时刻

type AssistantStreamDecoder added in v0.2.13

type AssistantStreamDecoder struct {
	// 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, [步骤...], 应用 ID]:步骤 field 1 为对话轮、6 为失败原因、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"`
}

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 (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 表示内联二进制内容

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"`
	Publisher string `json:"publisher,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, error)

NewClient 创建协议客户端

func (*Client) BenefitTierForAccount

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

BenefitTierForAccount 读取并缓存指定账户的官网权益等级

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

func (c *Client) CountTokens(ctx context.Context, request TokenCountRequest) (TokenCount, error)

func (*Client) CountTokensForAccount

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

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

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) EnsureTermsAccepted added in v0.2.14

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

EnsureTermsAccepted 读取账户的官网日志上下文,账户尚未同意 AI Studio 条款时按官网条款对话框或 onboarding 表单发送 AcceptTerms

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

func (c *Client) GenerateVideo(ctx context.Context, request VideoRequest) (VideoOperation, error)

GenerateVideo 创建 Veo 长任务

func (*Client) GetGenerateVideoOperation

func (c *Client) GetGenerateVideoOperation(ctx context.Context, accountID string, operationID string) (VideoOperation, error)

GetGenerateVideoOperation 读取 Veo 长任务当前状态

func (*Client) Models

func (c *Client) Models(ctx context.Context) ([]Model, error)

func (*Client) ModelsForAccount

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

ModelsForAccount 读取指定账户的实时模型目录

func (*Client) UploadFile

func (c *Client) UploadFile(ctx context.Context, request UploadRequest) (FileRef, error)

UploadFile 上传文件并返回可用于 GenerateContent 的 Drive 引用

type ClientOptions

type ClientOptions struct {
	Transport       RPCTransport
	Protected       ProtectedTransport
	ContextProvider RequestContextProvider
}

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 EncodeCreateInteractionRequest added in v0.2.14

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

EncodeCreateInteractionRequest 编码官网后台 agent 的 CreateInteraction 请求并返回参与 WAA 绑定的文本内容

func EncodeCreateInteractionStreamRequest added in v0.2.0

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

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

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 CooldownState

type CooldownState struct {
	Until  time.Time `json:"until"`
	Reason string    `json:"reason,omitempty"`
	Level  int       `json:"level,omitempty"`
}

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

func (CooldownState) Active

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

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

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
	CopyDrive(context.Context, string, string, string, string) (string, error)
}

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

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 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"`
	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"`
	// FrameUsage 是事件所在上游帧给出的累计用量
	FrameUsage *Usage `json:"frame_usage,omitempty"`
	// FinishFrame 表示事件来自带结束原因的上游帧
	FinishFrame bool  `json:"finish_frame,omitempty"`
	Err         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
}

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"`
	// ImageRoute 内部标记:图像生成模型(由模型目录能力推导)
	ImageRoute bool `json:"-"`
	// Unary 标记单次非流式请求(在 Build 代理中使用 ProxyUnaryCall)
	Unary bool `json:"-"`
	// Background 标记没有客户端等待首事件的后台任务
	Background bool `json:"-"`
	// Truncate 在生成前按模型上下文窗口移除最早的完整轮次
	Truncate bool `json:"-"`
	// contains filtered or unexported fields
}

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

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
	// 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 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 IsolatedLoginDriver

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

IsolatedLoginDriver 定义独立浏览器登录

type IsolatedLoginRequest

type IsolatedLoginRequest struct {
	AccountID string
	Directory string
	Proxy     string
	Locale    string
	Timezone  string
	View      *camoufoxnative.LiveView
}

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

type IsolatedLoginResult

type IsolatedLoginResult struct {
	StorageState StorageState
	Email        string
	VerifiedAt   time.Time
	DriveError   string
	CloseError   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"`
}

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) CopyDrive added in v0.2.14

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

CopyDrive 通过当前账户固定出口复制 Drive 文件并返回副本 ID

func (*MakerSuiteHTTPTransport) DeleteDrive

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

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

func (*MakerSuiteHTTPTransport) Do

Do 发送普通 MakerSuite RPC 并让响应 body 持有租约

func (*MakerSuiteHTTPTransport) DownloadDrive

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

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

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

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

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
}

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, timeout time.Duration) (*NativeLoginDriver, error)

NewNativeLoginDriver 创建纯 Go Camoufox 登录驱动

func (*NativeLoginDriver) Login

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

type NativeWorker

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

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

func NewGoWorker added in v0.2.0

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

NewGoWorker 启动单个账户的纯 Go WAA runtime,不启动浏览器

func NewNativeWorker

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

NewNativeWorker 启动单个账户的 Camoufox 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) Prepare

Prepare 生成 fresh proof 并写入请求指定的 WAA field

func (*NativeWorker) ProtocolHeaders

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

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

func (*NativeWorker) SendProtected

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

SendProtected 经账户 WAA runtime 流式发送已准备的请求,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
}

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 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, error)

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
	// contains filtered or unexported fields
}

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

func NewPooledService

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

NewPooledService 创建多账户协议服务

func (*PooledService) CachedModels

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

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

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 使用支持目标模型的独占账户计数

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) 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 使用一个独占账户创建任务并保存 operation 绑定

func (*PooledService) GetGenerateVideoOperation

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

GetGenerateVideoOperation 使用 operation 创建账户轮询,首次完成时把临时结果文件复制为账户 Drive 中的视频并绑定,此后直接返回该视频;Omni 任务按本进程的生成状态返回

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 返回全部视频任务的持久元数据

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

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

RefreshAccountModels 占用指定账户的一个普通槽位刷新其权益与模型目录,不受账户启用、调度状态与冷却限制

func (*PooledService) RefreshAccountState added in v0.2.11

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

RefreshAccountState 读取账户权益与模型目录,登录失效时标记账户需要登录;wait 为 true 时等待独占租约,否则只用就绪账户的空闲槽位

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,
) ([]Content, *TemporaryFileCopies, error)

UploadInlineMediaToLease 把内联附件改写为目标账户 Drive 文件的引用,同一账户已上传过的相同内容直接引用,闲置超过 inlineMediaIdle 的旧文件在本次请求结束时删除

func (*PooledService) ValidateGenerateRequest added in v0.2.6

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

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

type PreparedProtectedRequest

type PreparedProtectedRequest struct {
	Body    []byte
	Headers http.Header
}

PreparedProtectedRequest 表示已写入 fresh proof 的请求

type PromptFeedbackError

type PromptFeedbackError struct {
	Reason        string
	Message       string
	SafetyRatings []SafetyRating
	Raw           json.RawMessage
}

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

func (*PromptFeedbackError) Error

func (e *PromptFeedbackError) Error() string

Error 返回上游输入拒绝原因

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 ProtectedPreparerProviderFunc

type ProtectedPreparerProviderFunc func(context.Context, string, string) (ProtectedPreparer, error)

ProtectedPreparerProviderFunc 将函数适配为 ProtectedPreparerProvider

func (ProtectedPreparerProviderFunc) Worker

func (f ProtectedPreparerProviderFunc) Worker(ctx context.Context, accountID string, modelID string) (ProtectedPreparer, error)

Worker 返回账户的 lazy WAA preparer

type ProtectedRequest

type ProtectedRequest struct {
	URL        string
	Headers    http.Header
	Body       []byte
	Prompt     string
	PagePrompt string
	ProofField int
}

ProtectedRequest 表示需要 WAA 保护的 AI Studio 请求

type ProtectedTransport

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

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

type ProtectedTransportFunc

type ProtectedTransportFunc func(context.Context, GenerateRequest, RPCRequest) (*RPCResponse, error)

ProtectedTransportFunc 将函数适配为 ProtectedTransport

func (ProtectedTransportFunc) DoProtected

func (f ProtectedTransportFunc) DoProtected(ctx context.Context, request GenerateRequest, rpc RPCRequest) (*RPCResponse, error)

DoProtected 调用受保护传输函数

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

QuotaCooldown 表示上游额度限制对应的调度冷却

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
}

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) Unwrap added in v0.2.14

func (e *RPCError) Unwrap() error

Unwrap 把地区或账户不受支持的错误映射为 camoufoxnative.ErrRegionNotSupported

type RPCRequest

type RPCRequest struct {
	Method    string
	URL       string
	AccountID string
	RequestID string
	Header    http.Header
	Body      []byte
	Streaming bool
}

RPCRequest 描述交给认证传输层的单次 MakerSuite 请求

type RPCResponse

type RPCResponse struct {
	StatusCode int
	Header     http.Header
	Body       io.ReadCloser
}

RPCResponse 描述认证传输层返回的响应头和实时正文

type RPCTransport

type RPCTransport interface {
	Do(context.Context, RPCRequest) (*RPCResponse, error)
}

RPCTransport 负责认证、账户租约、Cookie 写回和真实网络发送

type RequestContext

type RequestContext struct {
	Timezone string
}

RequestContext 保存账户运行时提供的协议上下文

type RequestContextProvider

type RequestContextProvider interface {
	RequestContext(context.Context, string) (RequestContext, error)
}

RequestContextProvider 按账户返回当前协议上下文

type RequestPhase

type RequestPhase string

RequestPhase 表示受保护请求的当前准备阶段

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

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 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 {
	// contains filtered or unexported fields
}

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

func (s *Signer) Sign(state StorageState) (string, error)

Sign 使用当前时间生成授权头

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

func (*StorageState) SetAuthExtension

func (s *StorageState) SetAuthExtension(extension AuthExtension) error

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

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

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 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 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
	ResolvePurpose func(context.Context) (string, error)
}

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 VideoImage

type VideoImage struct {
	InlineData *Blob
	File       *FileRef
}

VideoImage 表示 Veo 帧图片

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

	// Missing 为上游已找不到该任务时的上游错误说明
	Missing string
	// Failure 为 Omni 视频任务生成失败的错误
	Failure error
	// contains filtered or unexported fields
}

VideoOperation 表示 Veo 私有长任务状态

func ParseVideoOperation

func ParseVideoOperation(source io.Reader, method string) (VideoOperation, error)

ParseVideoOperation 解码 GenerateVideo 与轮询返回的 operation

func (VideoOperation) ModelAccessCheckedAt

func (operation VideoOperation) ModelAccessCheckedAt() time.Time

ModelAccessCheckedAt 返回上游接受视频任务的资格时间

type VideoProtectedTransport

type VideoProtectedTransport interface {
	DoProtectedVideo(context.Context, VideoRequest, RPCRequest) (*RPCResponse, error)
}

VideoProtectedTransport 原子完成 Veo fresh WAA proof、field 8 写入和同 context 发送

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
	RecoverWAARuntime func(context.Context, string, error) (bool, error)
	// TaskContext 返回后台视频任务的上下文:生成服务停止时取消,期限从任务开始计算
	TaskContext func() (context.Context, context.CancelFunc, error)
}

VideoRequest 表示一次生成一个视频的 Veo 长任务请求

type VideoResourceMetadata

type VideoResourceMetadata struct {
	Model   string `json:"model"`
	Seconds string `json:"seconds"`
	Size    string `json:"size"`
	File    string `json:"file,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 (
	// WorkerStarting 表示 runtime 进程正在启动
	WorkerStarting WorkerPhase = "starting"
	// WorkerBootstrapping 表示官方页面正在初始化 WAA
	WorkerBootstrapping WorkerPhase = "bootstrapping"
	// 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, error)

NewWorkerProtectedTransport 创建基于 lazy WAA preparer 的受保护传输

func (*WorkerProtectedTransport) DoProtected

func (t *WorkerProtectedTransport) DoProtected(ctx context.Context, request GenerateRequest, rpc RPCRequest) (*RPCResponse, error)

DoProtected 写入 fresh proof 后通过 Camoufox 发送 GenerateContent、Build 代理或写代码助手请求,写入页面输入框的提示词为最后一个轮次的文本

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

func (t *WorkerProtectedTransport) DoProtectedVideo(ctx context.Context, request VideoRequest, rpc RPCRequest) (*RPCResponse, error)

DoProtectedVideo 写入 Veo fresh proof 后经 Worker 页面发送请求,页面输入框的提示词为视频提示词

func (*WorkerProtectedTransport) OpenBidiProtected

func (t *WorkerProtectedTransport) OpenBidiProtected(
	ctx context.Context,
	request BidiRequest,
	runtime RequestContext,
	lease *AccountLease,
	release func() error,
) (*BidiSession, error)

OpenBidiProtected 使用当前租约建立 WebChannel 会话

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
	RequestCount uint64
	LastError    string
}

WorkerState 表示账户 runtime 的可观察状态

Jump to

Keyboard shortcuts

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