Documentation
¶
Index ¶
- Constants
- Variables
- func AddAccessLogAttempt(ctx context.Context, attempt RequestAttempt)
- func AddAccessLogProof(ctx context.Context, timing ProofTiming)
- func DetachAccessLog(ctx context.Context)
- func EncodeUsageCursor(cursor UsageCursor) string
- func LookupPublicModel(models []aistudio.Model, id string) (aistudio.Model, bool)
- func MarkAccessLogScheduled(ctx context.Context)
- func NewHandler(service aistudio.Service, config Config) http.Handler
- func ReportTaskStep(ctx context.Context, step string)
- func ResetAccessLogFirstOutput(ctx context.Context)
- func SetAccessLogChannel(ctx context.Context, channel string)
- func SetAccessLogError(ctx context.Context, err error)
- func SetAccessLogFinishReason(ctx context.Context, reason string)
- func SetAccessLogFirstEvent(ctx context.Context, firstEvent time.Duration, firstOutput int64)
- func SetAccessLogGenerationConfig(ctx context.Context, config aistudio.GenerationConfig)
- func SetAccessLogGenerationInput(ctx context.Context, request aistudio.GenerateRequest)
- func SetAccessLogGenerationResult(ctx context.Context, usage *aistudio.Usage, toolCalls int)
- func SetAccessLogTarget(ctx context.Context, model string, account string)
- func SetAccessLogTrailingError(ctx context.Context, err error)
- func SetAccessLogUpstreamBytes(ctx context.Context, bytes int64)
- func StartAccessLog(ctx context.Context)
- func TaskLabel(ctx context.Context) string
- type AccessLog
- type AccountCreateInput
- type AccountExit
- type AccountInput
- type AccountStateInput
- type AccountTask
- type AccountTaskItem
- type AdminAccount
- type AdminAccountCounts
- type AdminAccountRefresh
- type AdminCooldown
- type AdminEvent
- type AdminLog
- type AdminProxy
- type AdminRequest
- type AdminService
- type AdminStatus
- type ChromeImportInput
- type ChromeImportProfile
- type Config
- type CookieBrowser
- type CookieImportInput
- type FirstEventLatency
- type InvalidConfigValue
- type LogField
- type LogStage
- type PairingAccountResult
- type PairingRenewalInput
- type PairingToken
- type Prompt
- type PromptStore
- type PromptSummary
- type ProofPhasesMS
- type ProofTiming
- type RequestAttempt
- type RequestBody
- type RequestLedger
- type RequestLog
- type RequestLogProofPhases
- type RequestLogUsage
- type ResponseModes
- type RuntimeConfig
- type SavedState
- type StateNode
- type StateStore
- type SystemInstructionPreset
- type UpdateProgress
- type UpdateService
- type UpdateStatus
- type UsageBucket
- type UsageCursor
- type UsageFilters
- type UsageGroup
- type UsageLatency
- type UsagePair
- type UsageQuery
- type UsageRecent
- type UsageRecord
- type UsageRecordPage
- type UsageRecordQuery
- type UsageReport
- type UsageSeries
- type UsageStats
Constants ¶
const ( TaskStepLogin = "login" TaskStepReading = "reading" TaskStepChecking = "checking" TaskStepSaving = "saving" )
账户任务中一个账户的步骤:等待在浏览器中登录、读取浏览器里的登录状态、检查 AI Studio 访问、保存账户
Variables ¶
var ErrInvalidPageToken = errors.New("invalid page_token")
ErrInvalidPageToken 表示对话列表的翻页令牌无法解析
var ErrPromptNotFound = errors.New("prompt not found")
ErrPromptNotFound 表示对话不存在
var ErrRequestBodyNotFound = errors.New("请求正文不存在")
ErrRequestBodyNotFound 表示请求没有保存正文
var UsageDimensions = []string{"model", "account", "channel", "protocol", "state"}
UsageDimensions 是用量可筛选与分组的维度
Functions ¶
func AddAccessLogAttempt ¶ added in v0.2.6
func AddAccessLogAttempt(ctx context.Context, attempt RequestAttempt)
AddAccessLogAttempt 追加一次未成功的上游尝试
func AddAccessLogProof ¶ added in v0.2.6
func AddAccessLogProof(ctx context.Context, timing ProofTiming)
AddAccessLogProof 累计请求等待并生成 WAA proof 的总耗时与分项
func DetachAccessLog ¶ added in v0.2.11
DetachAccessLog 标记请求的生成不随客户端连接关闭而结束,访问日志的状态按生成结果记录
func EncodeUsageCursor ¶ added in v0.2.6
func EncodeUsageCursor(cursor UsageCursor) string
EncodeUsageCursor 将分页位置编码为 URL 安全的字符串
func LookupPublicModel ¶ added in v0.2.11
LookupPublicModel 按正式 ID 优先于别名解析同一实时目录
func MarkAccessLogScheduled ¶ added in v0.2.6
MarkAccessLogScheduled 记录请求从进入服务到取得本次执行账户的排队时间
func NewHandler ¶
NewHandler 创建公开 API 路由
func ReportTaskStep ¶ added in v0.3.13
ReportTaskStep 把账户进入的步骤显示到它所在的账户任务,ctx 不属于账户任务时不做任何事
func ResetAccessLogFirstOutput ¶ added in v0.3.7
ResetAccessLogFirstOutput 在上游从头重新生成时清零首帧已累计的 token 数,重新生成的输出都在首个事件之后到达
func SetAccessLogChannel ¶ added in v0.2.0
SetAccessLogChannel 写入请求实际使用的上游通道
func SetAccessLogError ¶
SetAccessLogError 写入请求最终错误
func SetAccessLogFinishReason ¶
SetAccessLogFinishReason 写入生成请求的上游终止原因
func SetAccessLogFirstEvent ¶
SetAccessLogFirstEvent 写入首个上游语义事件耗时与该事件所在帧已累计的思考与回复 token 数
func SetAccessLogGenerationConfig ¶
func SetAccessLogGenerationConfig(ctx context.Context, config aistudio.GenerationConfig)
SetAccessLogGenerationConfig 写入生成请求采用的参数
func SetAccessLogGenerationInput ¶
func SetAccessLogGenerationInput(ctx context.Context, request aistudio.GenerateRequest)
SetAccessLogGenerationInput 写入生成请求输入摘要
func SetAccessLogGenerationResult ¶
SetAccessLogGenerationResult 写入生成流的完成摘要
func SetAccessLogTarget ¶
SetAccessLogTarget 写入请求实际使用的模型与账户
func SetAccessLogTrailingError ¶ added in v0.3.7
SetAccessLogTrailingError 写入函数调用之后上游结束生成的错误,请求仍按正常完成记录
func SetAccessLogUpstreamBytes ¶
SetAccessLogUpstreamBytes 写入上游响应体字节数
Types ¶
type AccessLog ¶
type AccessLog struct {
Status int
Latency time.Duration
FirstEvent time.Duration
FirstOutput int64
TrailingError string
QueueWait time.Duration
Proof ProofTiming
UpstreamBytes int64
Usage *aistudio.Usage
ToolCalls int
InputMessages int
InputTextChars int
InputMedia int
InputMediaBytes int64
InputFiles int
Temperature string
TopP string
Thinking string
MaxOutputTokens string
RequestID string
Method string
Path string
Model string
Account string
Channel string
FinishReason string
Error string
Canceled bool
Generation bool
Attempts []RequestAttempt
Authorized bool
}
AccessLog 表示一次公开 API 请求的最终访问记录
type AccountCreateInput ¶
type AccountCreateInput struct {
Proxy string `json:"proxy"`
Locale string `json:"locale"`
Timezone string `json:"timezone"`
}
AccountCreateInput 表示浏览器登录的账户环境
type AccountExit ¶ added in v0.3.8
type AccountExit struct {
Proxy string `json:"proxy"`
IP string `json:"ip,omitempty"`
Country string `json:"country,omitempty"`
Timezone string `json:"timezone,omitempty"`
Locale string `json:"locale,omitempty"`
Error string `json:"error,omitempty"`
}
AccountExit 表示一个账户出口代理的公网 IP 与按 IP 定位的国家、时区和语言,Proxy 为空时是直连,查询失败时 Error 为原因
type AccountInput ¶
type AccountInput struct {
Label string `json:"label"`
Enabled bool `json:"enabled"`
Proxy string `json:"proxy"`
Locale string `json:"locale"`
Timezone string `json:"timezone"`
}
AccountInput 表示已有账户配置
type AccountStateInput ¶ added in v0.2.6
type AccountStateInput struct {
Label string `json:"label"`
Proxy string `json:"-"`
Locale string `json:"locale"`
Timezone string `json:"timezone"`
AuthUser int `json:"auth_user"`
StorageState aistudio.StorageState `json:"storage_state"`
Fingerprint json.RawMessage `json:"fingerprint,omitempty"`
// RenewalToken 是配对上传为该账户签发的续签凭据,只由服务端设置
RenewalToken string `json:"-"`
}
AccountStateInput 是远程配对上传或管理端 Cookie 导入的账户认证状态与 Camoufox 指纹
type AccountTask ¶ added in v0.3.0
type AccountTask struct {
ID string `json:"id"`
Kind string `json:"kind"`
View string `json:"view,omitempty"`
State string `json:"state"`
Items []AccountTaskItem `json:"items"`
StartedAt time.Time `json:"started_at"`
}
AccountTask 是在服务端运行的添加或重新登录账户任务,管理页关闭或刷新后继续运行,结束后保留到用户关闭
type AccountTaskItem ¶ added in v0.3.0
type AccountTaskItem struct {
Label string `json:"label"`
State string `json:"state"`
Step string `json:"step,omitempty"`
Code string `json:"code,omitempty"`
Error string `json:"error,omitempty"`
}
AccountTaskItem 是任务中的一个账户,Label 为邮箱,浏览器登录完成前为空;Step 是处理中的账户当前的步骤
type AdminAccount ¶
type AdminAccount struct {
ID string `json:"id"`
Label string `json:"label"`
Enabled bool `json:"enabled"`
State string `json:"state"`
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"`
Message string `json:"message"`
// PairingRenewedAt 是远程配对账户最近一次由原电脑续签的时间,没有经配对续签时省略
PairingRenewedAt *time.Time `json:"pairing_renewed_at,omitempty"`
// Transition 是账户正在进行的后台操作,没有时省略
// draining 为停用后等待在途请求结束并关闭 Worker,syncing 为启用、添加、导入或重新登录后同步模型目录,saving 为保存配置或登录状态,refreshing 为立即刷新
Transition string `json:"transition,omitempty"`
// TransitionStep 是后台操作当前的步骤,操作没有分步时省略
// waiting 为等该账户的在途请求结束,catalog 为读取权益与模型目录,verifying 为发一次生成请求核对验证状态
TransitionStep string `json:"transition_step,omitempty"`
// TransitionIndex 与 TransitionTotal 是立即刷新当前步骤的序号与步数,其他操作省略
TransitionIndex int `json:"transition_index,omitempty"`
TransitionTotal int `json:"transition_total,omitempty"`
// TransitionSince 是进入当前操作或步骤的时刻,没有后台操作时省略
TransitionSince *time.Time `json:"transition_since,omitempty"`
// ActiveRequests 是账户上进行中的请求数
ActiveRequests int `json:"active_requests"`
// CatalogError 是已有模型目录的账户最近一次目录同步失败的原因,下一次同步成功后省略
CatalogError string `json:"catalog_error,omitempty"`
}
AdminAccount 表示管理端账户摘要
type AdminAccountCounts ¶
type AdminAccountCounts struct {
Total int `json:"total"`
Ready int `json:"ready"`
Busy int `json:"busy"`
Cooldown int `json:"cooldown"`
AuthRequired int `json:"auth_required"`
}
AdminAccountCounts 表示账户状态计数
type AdminAccountRefresh ¶ added in v0.2.11
type AdminAccountRefresh struct {
Account AdminAccount `json:"account"`
PreviousTier string `json:"previous_tier"`
Tier string `json:"tier"`
PreviousModels int `json:"previous_models"`
Models int `json:"models"`
}
AdminAccountRefresh 表示一次手动刷新后的账户与刷新前后的权益和模型数
type AdminCooldown ¶
type AdminCooldown struct {
AccountID string `json:"account_id"`
AccountLabel string `json:"account_label"`
Channel string `json:"channel"`
ModelID string `json:"model_id"`
Scope string `json:"scope"`
Until time.Time `json:"until"`
Reason string `json:"reason,omitempty"`
}
AdminCooldown 表示账户模型冷却
type AdminEvent ¶
AdminEvent 表示管理端增量事件
type AdminLog ¶
type AdminLog struct {
Time time.Time `json:"time"`
Level string `json:"level"`
Source string `json:"source"`
Message string `json:"message"`
Fields []LogField `json:"fields,omitempty"`
Stage *LogStage `json:"stage,omitempty"`
Event string `json:"event"`
Request *RequestLog `json:"request,omitempty"`
}
AdminLog 表示管理页面展示的一条运行日志
type AdminProxy ¶ added in v0.2.12
type AdminProxy 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"`
}
AdminProxy 表示代理池中一个代理的可用性与绑定账户数
type AdminRequest ¶
type AdminRequest struct {
ID string `json:"id"`
Model string `json:"model"`
AccountID string `json:"account_id"`
AccountLabel string `json:"account_label"`
Channel string `json:"channel,omitempty"`
State string `json:"state"`
StartedAt time.Time `json:"started_at"`
// SentAt 是请求最近一次取得账户发往上游的时刻,排队中为零值
SentAt time.Time `json:"sent_at,omitzero"`
// LastDataAt 是最近一次收到上游输出的时刻,收到首个输出前为零值
LastDataAt time.Time `json:"last_data_at,omitzero"`
}
AdminRequest 表示活动请求摘要
type AdminService ¶
type AdminService interface {
Status(context.Context) (AdminStatus, error)
CatalogModels(context.Context) ([]aistudio.Model, error)
Accounts(context.Context) ([]AdminAccount, error)
AccountExits(context.Context) ([]AccountExit, error)
CreateAccount(context.Context, AccountCreateInput, *camoufoxnative.LiveView) (AdminAccount, error)
ChromeImportProfiles(context.Context) ([]ChromeImportProfile, error)
CookieBrowsers(ctx context.Context, proxy string) ([]CookieBrowser, error)
DiscoverCookieAccounts(context.Context, CookieImportInput) ([]CookieBrowser, error)
ImportChromeAccounts(context.Context, ChromeImportInput) ([]AdminAccount, error)
ImportAccountState(context.Context, AccountStateInput) (AdminAccount, error)
RenewAccountCookies(ctx context.Context, accountID string, token string, cookies []aistudio.StateCookie) (AdminAccount, error)
UpdateAccount(context.Context, string, AccountInput) (AdminAccount, error)
SetAccountState(ctx context.Context, accountID string, state string) (AdminAccount, error)
DeleteAccount(context.Context, string) error
LoginAccount(context.Context, string, *camoufoxnative.LiveView) (AdminAccount, error)
RefreshAccount(context.Context, string) (AdminAccountRefresh, error)
StartService(context.Context) (AdminStatus, error)
StopService(context.Context) (AdminStatus, error)
DownloadCamoufox(context.Context) (AdminStatus, error)
ClearLogs(context.Context) error
RuntimeConfig(context.Context) (RuntimeConfig, error)
UpdateRuntimeConfig(context.Context, RuntimeConfig) (RuntimeConfig, error)
Cooldowns(context.Context) ([]AdminCooldown, error)
ClearCooldown(ctx context.Context, accountID string, scope string) error
Requests(context.Context) ([]AdminRequest, error)
CancelRequest(context.Context, string) error
Events(context.Context) (<-chan AdminEvent, error)
FirstEventLatencies() []FirstEventLatency
RecordAccessStart(AccessLog)
RecordAccessLog(AccessLog)
}
AdminService 定义管理端需要的权威状态能力
type AdminStatus ¶
type AdminStatus struct {
State string `json:"state"`
Running bool `json:"running"`
Ready bool `json:"ready"`
Version string `json:"version"`
ActiveRequests int `json:"active_requests"`
Accounts AdminAccountCounts `json:"accounts"`
Camoufox camoufoxnative.Preparation `json:"camoufox"`
ChromeImport bool `json:"chrome_import"`
// Transition 是生成服务正在进行的启动或停止步骤,没有时省略
// 启动:probe_proxies 检测代理池,wait_camoufox 等待 Camoufox 下载,wait_catalog 等待首个账户读取模型目录,start_prewarm 开始预热 WAA Worker
// 停止:cancel_requests 停止在途请求,wait_catalog_stop 等待模型目录同步停止,close_workers 关闭 WAA Worker
Transition string `json:"transition,omitempty"`
// TransitionSince 是进入当前步骤的时刻,没有步骤时省略
TransitionSince *time.Time `json:"transition_since,omitempty"`
// Time 是生成这份状态的服务端时刻,管理页以它换算各阶段的已用时间
Time time.Time `json:"time"`
}
AdminStatus 表示管理端运行状态
type ChromeImportInput ¶
type ChromeImportInput struct {
AccountIDs []string `json:"account_ids"`
Proxy string `json:"proxy"`
Locale string `json:"locale"`
Timezone string `json:"timezone"`
}
ChromeImportInput 表示批量导入的 Chrome 账号与账户环境
type ChromeImportProfile ¶
type ChromeImportProfile struct {
ID string `json:"id"`
Profile string `json:"profile"`
DisplayName string `json:"display_name"`
Email string `json:"email"`
// Restricted 是该账户服务受限的原因,受限的账户不能导入
Restricted string `json:"restricted"`
}
ChromeImportProfile 表示可从本机 Chrome 导入的账号
type Config ¶
type Config struct {
// PickPath 以系统对话框选择账户目录并返回选中的路径,用户取消时返回空串;只在桌面版提供
PickPath func(start string) (string, error)
APIKey string
Admin AdminService
AdminAuthEnabled bool
AdminUsername string
AdminPassword string
// AdminSessionPath 是记住我的管理会话文件
AdminSessionPath string
Ledger RequestLedger
Prompts PromptStore
Updates UpdateService
// MediaDir 是媒体 URL 模式下生成媒体的保存目录
MediaDir string
// MediaLimit 是媒体目录的总字节上限,超过时删除最久未使用的文件
MediaLimit int64
// MediaLinks 返回媒体输出是否使用 URL 与设置的服务地址
MediaLinks func() (enabled bool, base string)
// ResponseModes 返回非流式保活与假流式设置
ResponseModes func() ResponseModes
// SearchSettings 返回当前生成服务的搜索型号与全模型搜索设置
SearchSettings func() (modelAliases, googleSearch bool)
// WaitLaunch 在生成服务启动期间等到启动结束,公开 API 请求经它等待后再处理
WaitLaunch func(context.Context)
// EgressProxy 返回服务连接外部 MCP 服务器所用的出口代理,空串为直连
EgressProxy func() string
// States 持久保存 Responses、Interactions 与 Chat 音频回复的续接节点,为空时只保存在内存中
States StateStore
}
Config 定义公开 API 服务配置
type CookieBrowser ¶ added in v0.2.14
type CookieBrowser struct {
Address string `json:"address"`
Browser string `json:"browser"`
Email string `json:"email"`
AuthUser int `json:"auth_user"`
Imported bool `json:"imported"`
SignedOut bool `json:"signed_out"`
Error string `json:"error"`
// Restricted 是该账户服务受限的原因,受限的账户不能导入
Restricted string `json:"restricted"`
// DeviceBound 表示 Cookie 带 __Secure-1PSIDRTS,会话绑定原浏览器所在的设备,导入的副本约 2 小时内失效
DeviceBound bool `json:"device_bound"`
}
CookieBrowser 表示本机开启远程调试的浏览器与其中登录 AI Studio 的账户
type CookieImportInput ¶ added in v0.2.14
CookieImportInput 表示识别 Cookie 中账户时提交的 Cookie 文本与出口代理
type FirstEventLatency ¶ added in v0.2.17
type FirstEventLatency struct {
Model string `json:"model"`
Channel string `json:"channel"`
Samples int `json:"samples"`
P95MS int64 `json:"p95_ms"`
}
FirstEventLatency 是一个模型与通道近期原请求首事件等待的 p95 与样本数
type InvalidConfigValue ¶ added in v0.2.19
type InvalidConfigValue struct {
Key string `json:"key"`
Value string `json:"value"`
Reason string `json:"reason"`
}
InvalidConfigValue 表示加载时取值无效、按默认值生效的一个配置项
type LogStage ¶ added in v0.3.9
type LogStage struct {
Name string `json:"name"`
Step int `json:"step,omitempty"`
Steps int `json:"steps,omitempty"`
State string `json:"state,omitempty"`
}
LogStage 是分阶段运行日志所属的阶段,Step 与 Steps 为当前步骤与总步骤数,State 为结束状态 completed、failed 或 cancelled
type PairingAccountResult ¶ added in v0.3.0
type PairingAccountResult struct {
Account AdminAccount `json:"account"`
RenewalToken string `json:"renewal_token"`
}
PairingAccountResult 是配对上传的结果:导入的账户与原电脑推送新会话时使用的该账户续签凭据
type PairingRenewalInput ¶ added in v0.3.0
type PairingRenewalInput struct {
Cookies []aistudio.StateCookie `json:"cookies"`
}
PairingRenewalInput 是原电脑为配对账户推送的新会话 Cookie
type PairingToken ¶ added in v0.2.6
PairingToken 是远程配对令牌与到期时间
type Prompt ¶ added in v0.2.14
type Prompt struct {
PromptSummary
Data json.RawMessage `json:"data"`
}
Prompt 是一份保存的对话,Data 为管理端写入的对话内容
type PromptStore ¶ added in v0.2.14
type PromptStore interface {
Prompts(ctx context.Context, pageSize int, pageToken string) ([]PromptSummary, string, error)
Prompt(context.Context, string) (Prompt, error)
SavePrompt(context.Context, Prompt) (PromptSummary, error)
RenamePrompt(ctx context.Context, id, title, description string) (PromptSummary, error)
CopyPrompt(ctx context.Context, source, id, title string) (PromptSummary, error)
DeletePrompt(context.Context, string) error
SystemInstructions(context.Context) ([]SystemInstructionPreset, error)
SaveSystemInstruction(context.Context, SystemInstructionPreset) error
DeleteSystemInstruction(context.Context, string) error
}
PromptStore 保存 Playground 对话与系统指令预设
type PromptSummary ¶ added in v0.2.14
type PromptSummary struct {
ID string `json:"id"`
Title string `json:"title"`
Model string `json:"model"`
Description string `json:"description"`
Created time.Time `json:"created_at"`
Updated time.Time `json:"updated_at"`
// Turns 是保存时对话的消息条数,没有记录时为空
Turns *int `json:"turns,omitempty"`
// Tokens 是保存时整段对话的 token 数,没有记录时为空
Tokens *int `json:"tokens,omitempty"`
}
PromptSummary 是对话列表中的一项
type ProofPhasesMS ¶ added in v0.3.10
type ProofPhasesMS struct {
LockMS float64 `json:"lock_ms"`
InteractionMS float64 `json:"interaction_ms"`
RefreshMS float64 `json:"refresh_ms"`
ComputeMS float64 `json:"compute_ms"`
}
ProofPhasesMS 是生成 WAA proof 的分项毫秒数:等待操作锁、界面操作、等待 VM 重建与 VM 生成 proof
type ProofTiming ¶ added in v0.3.10
type ProofTiming struct {
Total time.Duration
Lock time.Duration
Interaction time.Duration
Refresh time.Duration
Compute time.Duration
// SettingsSkipped 是空闲不够而没有做的运行设置步数
SettingsSkipped int
}
ProofTiming 是请求各次生成 WAA proof 的累计耗时:Total 为整个准备过程,其中等待操作锁、界面操作、等待 VM 重建与 VM 生成 proof 分项累计
type RequestAttempt ¶ added in v0.2.6
type RequestAttempt struct {
Account string `json:"account"`
Channel string `json:"channel"`
Error string `json:"error"`
DurationMS int64 `json:"duration_ms"`
// Hedge 表示首事件超时后发起的备用请求,Superseded 表示另一方先返回首事件后被取消
Hedge bool `json:"hedge,omitempty"`
Superseded bool `json:"superseded,omitempty"`
}
RequestAttempt 记录一次未成功的上游尝试
type RequestBody ¶ added in v0.2.6
type RequestBody struct {
ID string `json:"id"`
Time time.Time `json:"time"`
Request string `json:"request"`
RequestSize int64 `json:"request_size"`
Response string `json:"response"`
ResponseSize int64 `json:"response_size"`
}
RequestBody 保存一次请求截断后的请求与响应正文
type RequestLedger ¶ added in v0.2.6
type RequestLedger interface {
BodyCapture() bool
SaveBody(RequestBody)
Usage(context.Context, UsageQuery) (UsageReport, error)
UsagePairs(context.Context, UsageQuery) ([]UsagePair, error)
Records(context.Context, UsageRecordQuery) (UsageRecordPage, error)
ExportRecords(context.Context, UsageRecordQuery, io.Writer) error
RequestBody(context.Context, string) (RequestBody, error)
}
RequestLedger 提供请求用量统计、请求记录与可选的正文记录
type RequestLog ¶
type RequestLog struct {
ID string `json:"id"`
State string `json:"state"`
StartedAt time.Time `json:"started_at,omitzero"`
Model string `json:"model,omitempty"`
Method string `json:"method,omitempty"`
Path string `json:"path,omitempty"`
Status int `json:"status,omitempty"`
DurationMS float64 `json:"duration_ms,omitempty"`
Usage *RequestLogUsage `json:"usage,omitempty"`
ToolCalls int `json:"tool_calls,omitempty"`
FinishReason string `json:"finish_reason,omitempty"`
Error string `json:"error,omitempty"`
InputMessages int `json:"input_messages,omitempty"`
InputTextChars int `json:"input_text_chars,omitempty"`
InputMedia int `json:"input_media,omitempty"`
InputMediaBytes int64 `json:"input_media_bytes,omitempty"`
InputFiles int `json:"input_files,omitempty"`
Parameters map[string]string `json:"parameters,omitempty"`
FirstEventMS float64 `json:"first_event_ms,omitempty"`
QueueMS float64 `json:"queue_ms,omitempty"`
ProofMS float64 `json:"proof_ms,omitempty"`
ProofPhases *RequestLogProofPhases `json:"proof_phases,omitempty"`
UpstreamBytes int64 `json:"upstream_bytes,omitempty"`
Channel string `json:"channel,omitempty"`
}
RequestLog 保存可关联的请求状态、用量与诊断字段
type RequestLogProofPhases ¶ added in v0.3.10
type RequestLogProofPhases struct {
ProofPhasesMS
SettingsSkipped int `json:"settings_skipped,omitempty"`
}
RequestLogProofPhases 是请求日志中生成 WAA proof 的分项,SettingsSkipped 是空闲不够而没有做的运行设置步数
type RequestLogUsage ¶
type RequestLogUsage struct {
InputTokens int64 `json:"input_tokens"`
CachedTokens int64 `json:"cached_tokens"`
ReasoningTokens int64 `json:"reasoning_tokens"`
ReplyTokens int64 `json:"reply_tokens"`
OutputTokens int64 `json:"output_tokens"`
TotalTokens int64 `json:"total_tokens"`
AverageTokensPerSecond float64 `json:"average_tokens_per_second,omitempty"`
}
RequestLogUsage 区分输入、缓存命中、思考、回复与首字之后的输出速率
type ResponseModes ¶ added in v0.2.15
type ResponseModes struct {
// NonstreamKeepalive 让非流式请求在等待结果期间定时写出换行
NonstreamKeepalive bool
// FakeStream 让流式请求收齐完整结果后再按流式输出
FakeStream bool
}
ResponseModes 是生成请求的响应方式设置
type RuntimeConfig ¶
type RuntimeConfig struct {
AutoStart bool `json:"auto_start"`
HideDockIcon bool `json:"hide_dock_icon"`
RequestBodyLog bool `json:"request_body_log"`
AdminAuthEnabled bool `json:"admin_auth_enabled"`
AdminUsername string `json:"admin_username"`
AdminPassword *string `json:"admin_password,omitempty"`
AdminPasswordSet bool `json:"admin_password_set"`
SavedAdminPassword string `json:"-"`
BuildNativeNonstream bool `json:"build_native_nonstream"`
NonstreamKeepalive bool `json:"nonstream_keepalive"`
FakeStream bool `json:"fake_stream"`
YouTubeLinks bool `json:"youtube_links"`
StripThoughtSignatures bool `json:"strip_thought_signatures"`
SearchModelAliases bool `json:"search_model_aliases"`
DiscoverHiddenModels bool `json:"discover_hidden_models"`
GoogleSearch bool `json:"google_search"`
FirstEventHedge string `json:"first_event_hedge"`
FirstEventHedgeModels string `json:"first_event_hedge_models"`
ContinuationRewrite bool `json:"continuation_rewrite"`
ContinuationPrompt string `json:"continuation_prompt"`
LogFile bool `json:"log_file"`
LogMaxTotalMB int `json:"log_max_total_mb"`
AuthStates string `json:"auth_states"`
ListenAddr string `json:"listen_addr"`
APIKey string `json:"proxy_api_key"`
ActiveListenAddr string `json:"active_listen_addr"`
ReservedListenAddr string `json:"reserved_listen_addr"`
PreviewListenAddr string `json:"preview_listen_addr"`
ActivePreviewListenAddr string `json:"active_preview_listen_addr"`
ActiveAPIKey string `json:"active_proxy_api_key"`
ManagementRestartRequired bool `json:"management_restart_required"`
ServiceRestartRequired bool `json:"service_restart_required"`
Proxy string `json:"proxy"`
ActiveProxy string `json:"active_proxy"`
ProxyPool []AdminProxy `json:"proxy_pool"`
InitTimeout string `json:"init_timeout"`
RequestTimeout string `json:"request_timeout"`
WarmWorkerLimit int `json:"warm_worker_limit"`
MaxActiveWorkers int `json:"max_active_workers"`
WarmStartupConcurrency int `json:"warm_startup_concurrency"`
PerAccountConcurrency int `json:"per_account_concurrency"`
RoutingStrategy string `json:"routing_strategy"`
AccountOrder string `json:"account_order"`
MaxAccountSwitches int `json:"max_account_switches"`
UpstreamChannels []string `json:"upstream_channels"`
ModelMapping string `json:"model_mapping"`
ModelChannels string `json:"model_channels"`
ModelAccounts string `json:"model_accounts"`
APIKeyAccounts string `json:"api_key_accounts"`
WAABackend string `json:"waa_backend"`
MediaOutput string `json:"media_output"`
MediaBaseURL string `json:"media_base_url"`
Environment []string `json:"environment"`
Invalid []InvalidConfigValue `json:"invalid"`
}
RuntimeConfig 表示全局运行配置
type SavedState ¶ added in v0.3.0
SavedState 是写入 StateStore 的一个续接节点
type StateStore ¶ added in v0.3.0
type StateStore interface {
Index() []StateNode
Read(id string) ([]byte, bool)
Save(saved []SavedState, removed []string)
}
StateStore 持久保存续接节点:Index 按保存顺序返回服务启动前保存的节点,Read 在访问时读出节点正文
type SystemInstructionPreset ¶ added in v0.2.18
type SystemInstructionPreset struct {
ID string `json:"id"`
Title string `json:"title"`
Text string `json:"text"`
}
SystemInstructionPreset 是一条保存的系统指令预设
type UpdateProgress ¶ added in v0.3.2
type UpdateProgress struct {
Stage string `json:"stage"`
Downloaded int64 `json:"downloaded"`
Total int64 `json:"total"`
}
UpdateProgress 表示在线更新的阶段(download、verify、install、restart)与发行包的已下载和总字节数,总字节数未知时为 0
type UpdateService ¶ added in v0.2.13
type UpdateService interface {
UpdateStatus(ctx context.Context, refresh bool) (UpdateStatus, error)
ApplyUpdate(ctx context.Context) (UpdateStatus, error)
}
UpdateService 检查并安装 GitHub 上的新发行版本
type UpdateStatus ¶ added in v0.2.13
type UpdateStatus struct {
Current string `json:"current"`
Latest string `json:"latest,omitempty"`
Available bool `json:"available"`
Mode string `json:"mode"`
ManagedBy string `json:"managed_by,omitempty"`
Notes string `json:"notes,omitempty"`
URL string `json:"url,omitempty"`
PublishedAt time.Time `json:"published_at,omitzero"`
CheckedAt time.Time `json:"checked_at,omitzero"`
Error string `json:"error,omitempty"`
Updating bool `json:"updating"`
Progress *UpdateProgress `json:"progress,omitempty"`
// LogDir 是服务日志目录的绝对路径
LogDir string `json:"log_dir"`
}
UpdateStatus 表示当前版本与 GitHub 最新发行版本
type UsageBucket ¶ added in v0.2.6
type UsageBucket struct {
At time.Time `json:"at"`
Cost float64 `json:"cost"`
UsageStats
}
UsageBucket 保存一个时间分桶的汇总与按 API 单价估算的美元费用
type UsageCursor ¶ added in v0.2.6
UsageCursor 是请求记录分页位置,下一页从该记录之后的更早记录开始
type UsageFilters ¶ added in v0.2.6
UsageFilters 按维度限定参与统计的请求,同一维度内多个取值为或关系
type UsageGroup ¶ added in v0.2.6
type UsageGroup struct {
Key string `json:"key"`
UsageStats
}
UsageGroup 保存一个维度取值的汇总
type UsageLatency ¶ added in v0.2.6
type UsageLatency struct {
AvgMS float64 `json:"avg_ms"`
P50MS float64 `json:"p50_ms"`
P95MS float64 `json:"p95_ms"`
P99MS float64 `json:"p99_ms"`
}
UsageLatency 汇总一组请求的平均值与分位耗时
type UsagePair ¶ added in v0.2.6
type UsagePair struct {
Account string `json:"account"`
Model string `json:"model"`
UsageStats
}
UsagePair 保存账户与模型组合的汇总
type UsageQuery ¶ added in v0.2.6
type UsageQuery struct {
From time.Time
To time.Time
Bucket time.Duration
Location *time.Location
Filters UsageFilters
Stack string
}
UsageQuery 选择用量统计的时间范围、分桶、时区、筛选与堆叠维度
type UsageRecent ¶ added in v0.2.6
type UsageRecent struct {
Minutes int `json:"minutes"`
Requests int64 `json:"requests"`
Tokens int64 `json:"tokens"`
}
UsageRecent 汇总最近几分钟的请求与 token,用于计算当前吞吐
type UsageRecord ¶ added in v0.2.6
type UsageRecord struct {
ID string `json:"id"`
Time time.Time `json:"time"`
Protocol string `json:"protocol"`
Path string `json:"path"`
Model string `json:"model"`
Account string `json:"account"`
Channel string `json:"channel"`
Status int `json:"status"`
State string `json:"state"`
DurationMS int64 `json:"duration_ms"`
FirstEventMS int64 `json:"first_event_ms"`
QueueMS int64 `json:"queue_ms"`
ProofMS int64 `json:"proof_ms"`
ProofPhases ProofPhasesMS `json:"proof_phases"`
InputTokens int64 `json:"input_tokens"`
CachedTokens int64 `json:"cached_tokens"`
ReasoningTokens int64 `json:"reasoning_tokens"`
ReplyTokens int64 `json:"reply_tokens"`
TotalTokens int64 `json:"total_tokens"`
ToolCalls int `json:"tool_calls"`
Error string `json:"error"`
Attempts []RequestAttempt `json:"attempts"`
HasBody bool `json:"has_body"`
}
UsageRecord 是一条已完成请求的账本记录
type UsageRecordPage ¶ added in v0.2.6
type UsageRecordPage struct {
Items []UsageRecord `json:"items"`
NextCursor string `json:"next_cursor,omitempty"`
}
UsageRecordPage 是按完成时间倒序的一页请求记录,NextCursor 为空表示没有更早的记录
type UsageRecordQuery ¶ added in v0.2.6
type UsageRecordQuery struct {
From time.Time
To time.Time
Filters UsageFilters
Status int
Search string
Before *UsageCursor
Limit int
}
UsageRecordQuery 选择请求记录的时间范围、筛选、状态码、关键字与分页位置
type UsageReport ¶ added in v0.2.6
type UsageReport struct {
From time.Time `json:"from"`
To time.Time `json:"to"`
BucketSeconds int64 `json:"bucket_seconds"`
GeneratedAt time.Time `json:"generated_at"`
LatestAt *time.Time `json:"latest_at,omitempty"`
Totals UsageStats `json:"totals"`
Previous UsageStats `json:"previous"`
Cost float64 `json:"cost"`
PreviousCost float64 `json:"previous_cost"`
UnpricedModels []string `json:"unpriced_models"`
Recent UsageRecent `json:"recent"`
Buckets []UsageBucket `json:"buckets"`
StackBy string `json:"stack_by"`
Series []UsageSeries `json:"series"`
Groups map[string][]UsageGroup `json:"groups"`
Options map[string][]string `json:"options"`
}
UsageReport 返回用量看板的汇总、上一周期、当前吞吐、估算费用与未计价模型、逐桶趋势、堆叠序列、分项与筛选候选
type UsageSeries ¶ added in v0.2.6
type UsageSeries struct {
Key string `json:"key"`
Other bool `json:"other,omitempty"`
Requests []int64 `json:"requests"`
Tokens []int64 `json:"tokens"`
}
UsageSeries 是堆叠趋势中一个维度取值逐桶的请求数与 token,Other 合并排名之外的取值
type UsageStats ¶ added in v0.2.6
type UsageStats struct {
Requests int64 `json:"requests"`
Succeeded int64 `json:"succeeded"`
Failed int64 `json:"failed"`
Canceled int64 `json:"canceled"`
RateLimited int64 `json:"rate_limited"`
InputTokens int64 `json:"input_tokens"`
CachedTokens int64 `json:"cached_tokens"`
ReasoningTokens int64 `json:"reasoning_tokens"`
ReplyTokens int64 `json:"reply_tokens"`
TotalTokens int64 `json:"total_tokens"`
Duration UsageLatency `json:"duration"`
FirstEvent UsageLatency `json:"first_event"`
QueueAvgMS float64 `json:"queue_avg_ms"`
LastAt *time.Time `json:"last_at,omitempty"`
}
UsageStats 汇总一组请求的结果、token 与耗时;成功包含工具调用、输出上限与上游终止
Source Files
¶
- account_tasks.go
- admin.go
- admin_auth.go
- anthropic.go
- anthropic_context.go
- anthropic_search.go
- audio_encode.go
- chat_audio.go
- chat_choices.go
- client_tools.go
- decisions.go
- embeddings.go
- errors.go
- field_order.go
- files.go
- gemini.go
- gemini_caches.go
- gemini_files.go
- gemini_predict.go
- generate.go
- image_edits.go
- interaction_input.go
- interaction_output.go
- interaction_resources.go
- interaction_tools.go
- interaction_webhook.go
- interactions.go
- keepalive.go
- ledger.go
- live.go
- login_view.go
- mcp_tools.go
- media.go
- media_output.go
- middleware.go
- openai.go
- pairing.go
- paths.go
- prompts.go
- remote_media.go
- responses.go
- responses_background.go
- responses_compaction.go
- responses_google_tools.go
- responses_retrieval.go
- router.go
- search_alias.go
- search_options.go
- thoughtsig.go
- transcriptions.go
- translations.go
- update.go
- video.go
- video_input.go
- video_tokens.go