Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -692,6 +692,7 @@ cp .env.example .env
| `STRIP_THOUGHT_SIGNATURES` | `false` | 发往上游前去掉对话历史中的思考签名 |
| `SEARCH_MODEL_ALIASES` | `true` | 提供支持搜索的模型的 `-search` 型号,使用该型号时启用 Google 搜索 |
| `DISCOVER_HIDDEN_MODELS` | `false` | 同步账户模型目录时找出 AI Studio 官网尚未公开的模型并加入目录 |
| `DISABLE_INTERACTION_MODELS` | `false` | kind=2 interaction 模型不按目录标记走 CreateInteractionStream/CreateInteraction,改与普通模型一样走 GenerateContent(目录标记为前端建议,实测服务端仍接受) |
| `GOOGLE_SEARCH` | `false` | 为 OpenAI、Anthropic、Gemini 与 Interactions 的生成请求启用 Google 搜索,包含普通型号与携带函数工具的请求 |
| `CONTINUATION_REWRITE` | `true` | 以 assistant 消息结尾的请求在不支持原生续写的模型上改写为续写请求;关闭时所有模型原样发送,上游拒绝时返回其错误 |
| `CONTINUATION_PROMPT` | 内置英文续写句 | 改写时与末尾 assistant 消息一起写入系统指令的提示词;设为空时末尾 assistant 消息改作 user 消息发送 |
Expand Down
1 change: 1 addition & 0 deletions docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,7 @@ Camoufox 运行中与服务的 WebDriver BiDi 连接断开时,服务最多等
| `STRIP_THOUGHT_SIGNATURES` | 去掉历史中的思考签名 | `false` |
| `SEARCH_MODEL_ALIASES` | 提供 `-search` 型号 | `true` |
| `DISCOVER_HIDDEN_MODELS` | 探测官网隐藏模型 | `false` |
| `DISABLE_INTERACTION_MODELS` | kind=2 interaction 模型改走 GenerateContent | `false` |
| `GOOGLE_SEARCH` | 全模型启用 Google 搜索 | `false` |
| `CONTINUATION_REWRITE` | 末尾 assistant 轮改写为续写 | `true` |
| `CONTINUATION_PROMPT` | 续写提示词 | 内置英文续写句 |
Expand Down
134 changes: 129 additions & 5 deletions internal/aistudio/interaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ func EncodeCreateInteractionStreamRequest(request GenerateRequest, defaults Gene
// field 54 输出格式:视频格式 field 4 宽高比、field 5 时长、field 6 分辨率,编辑任务不带输出格式
if task == interactionVideoTasks["edit"] {
interaction = interaction[:27]
} else {
} else if defaults.VideoResolution != "" {
interaction[53] = []any{[]any{[]any{nil, nil, nil, video}}}
}
body, proofAt, _ := marshalWAAArray([]any{int64(1), int64(1), nil, interaction, nil, int64(1)}, 5)
Expand Down Expand Up @@ -523,15 +523,25 @@ func decodeInteractionEvent(method string, raw json.RawMessage, emit func(Event)
if err != nil {
return false, withMethod(err, method)
}
finishReason := "stop"
switch status {
case 2:
finishReason = "tool_calls"
case 3:
case 6:
finishReason = "length"
case 4:
return false, &RPCError{Method: method, StatusCode: http.StatusBadGateway, Message: "interaction failed"}
case 5:
return false, &RPCError{Method: method, StatusCode: http.StatusBadGateway, Message: "interaction cancelled"}
default:
return false, &ProtocolEvidenceError{Method: method, Path: "$event[19][0][1]", Detail: fmt.Sprintf("未识别的最终状态 %d", status), Raw: cloneRaw(raw)}
}
if status == 2 {
if err := decodeInteractionCalls(method, interaction, raw, emit); err != nil {
return false, err
}
}
if usage := rawAt(interaction, 12); !isJSONNull(usage) {
decoded, err := decodeInteractionUsage(method, usage, raw)
if err != nil {
Expand All @@ -547,7 +557,65 @@ func decodeInteractionEvent(method string, raw json.RawMessage, emit func(Event)
return false, withMethod(err, method)
}
}
return true, emit(Event{Kind: EventFinish, FinishReason: "stop", EnvironmentID: environmentID})
return true, emit(Event{Kind: EventFinish, FinishReason: finishReason, EnvironmentID: environmentID})
}

// decodeInteractionCalls 从 requires_action 终态的 interaction 提取函数调用:调用以 content 形式出现在 step 列表(索引 26)的模型 step 内,content 索引 10 为 ["<NAME>",<ARGS>,"<ID>"?];step 列表缺失时回退扫描整个 interaction
func decodeInteractionCalls(method string, interaction []json.RawMessage, raw json.RawMessage, emit func(Event) error) error {
var root any
if steps := rawAt(interaction, 26); !isJSONNull(steps) {
if err := json.Unmarshal(steps, &root); err != nil {
return withMethod(err, method)
}
} else {
data, err := json.Marshal(interaction)
if err != nil {
return withMethod(err, method)
}
if err := json.Unmarshal(data, &root); err != nil {
return withMethod(err, method)
}
}
var calls []json.RawMessage
scanInteractionCalls(root, &calls, 0)
emitted := make(map[string]bool, len(calls))
for index, callRaw := range calls {
call, err := decodeFunctionCall(callRaw, fmt.Sprintf("$event[19][0] call[%d]", index), raw)
if err != nil {
continue
}
if emitted[string(callRaw)] {
continue
}
emitted[string(callRaw)] = true
if err := emit(Event{Kind: EventToolCall, FunctionCall: &call}); err != nil {
return err
}
}
return nil
}

// scanInteractionCalls 递归收集形如函数调用的 content:数组索引 10 为以字符串(名称)开头的数组
func scanInteractionCalls(node any, calls *[]json.RawMessage, depth int) {
if depth > 12 {
return
}
arr, ok := node.([]any)
if !ok {
return
}
if len(arr) > 10 {
if candidate, ok := arr[10].([]any); ok && len(candidate) > 0 {
if _, ok := candidate[0].(string); ok {
if data, err := json.Marshal(candidate); err == nil {
*calls = append(*calls, data)
}
}
}
}
for _, child := range arr {
scanInteractionCalls(child, calls, depth+1)
}
}

// decodeInteractionDelta 解码 content delta:field 1 文本、field 2 图片、field 3 音频、field 4 文档、field 5 视频、field 6 思考摘要、field 7 思考签名、field 10 引用
Expand Down Expand Up @@ -804,8 +872,12 @@ func trimWireNil(values []any) []any {
return values
}

// EncodeCreateInteractionRequest 编码官网后台 agent 的 CreateInteraction 请求并返回参与 WAA 绑定的文本内容
func EncodeCreateInteractionRequest(request GenerateRequest, model Model) ([]byte, int, []Content, error) {
// EncodeCreateInteractionRequest 编码官网后台 interaction 的 CreateInteraction 请求并返回参与 WAA 绑定的文本内容;目标是 agent 或 kind=2 模型
func EncodeCreateInteractionRequest(request GenerateRequest, model Model, defaults GenerationDefaults) ([]byte, int, []Content, error) {
// field 79 kind=2 的模型不是 agent:field 17 携带模型目标与 generation config,与官网一致
if model.Capabilities["interaction_model"] {
return encodeModelInteractionTarget(request, model, defaults)
}
agent := strings.TrimPrefix(strings.TrimSpace(request.Model), "models/")
// kind 是该 agent 的 agent_config 类型:带默认模型的 agent 为 antigravity,其余为 deep-research
kind := "deep-research"
Expand Down Expand Up @@ -862,6 +934,58 @@ func EncodeCreateInteractionRequest(request GenerateRequest, model Model) ([]byt
return body, proofAt, binding, nil
}

// encodeModelInteractionTarget 编码 kind=2 模型的 CreateInteraction 请求:field 17 为模型目标与 generation config,generation config 与 CreateInteractionStream 同构
func encodeModelInteractionTarget(request GenerateRequest, model Model, defaults GenerationDefaults) ([]byte, int, []Content, error) {
steps, binding, _, err := encodeInteractionSteps(request.Contents)
if err != nil {
return nil, 0, nil, err
}
// field 7 只在请求显式声明工具时写入:kind=2 模型不注入目录默认工具,与官网一致
var tools []any
if request.Tools.Explicit {
tools, err = agentTools(request.Tools, model)
if err != nil {
return nil, 0, nil, err
}
}
level, err := interactionThinkingLevel(request.Config, defaults)
if err != nil {
return nil, 0, nil, err
}
maxOutput := defaults.MaxOutputTokens
if request.Config.MaxOutputTokens != nil {
maxOutput = *request.Config.MaxOutputTokens
}
if maxOutput > defaults.MaxOutputTokens {
maxOutput = defaults.MaxOutputTokens
}
if maxOutput <= 0 {
return nil, 0, nil, fmt.Errorf("max output tokens %d 超出模型范围 1-%d", maxOutput, defaults.MaxOutputTokens)
}
config := make([]any, 8)
if level != 0 {
config[5] = level
}
config[6] = int64(1)
config[7] = maxOutput
interaction := make([]any, 27)
if system := strings.TrimSpace(SystemText(request.System)); system != "" {
interaction[6] = system
}
if len(tools) > 0 {
interaction[7] = tools
}
// field 17 为续接的上一轮 interaction ID
if request.PreviousInteractionID != "" {
interaction[16] = request.PreviousInteractionID
}
// field 17 为模型目标:field 1 为模型名、field 2 为 generation config
interaction[17] = []any{wireModelName(request.Model), config}
interaction[26] = []any{steps}
body, proofAt, _ := marshalWAAArray([]any{nil, int64(1), int64(1), interaction, nil, int64(1)}, 5)
return body, proofAt, binding, nil
}

// EncodeGetInteractionStreamRequest 编码按 interaction ID 读取后台任务增量与终态的请求
func EncodeGetInteractionStreamRequest(id string, model string) ([]byte, int, error) {
return marshalWAAArray([]any{id, int64(1), nil, nil, nil, int64(1), wireModelName(model)}, 5)
Expand All @@ -887,7 +1011,7 @@ func (c *Client) generateInteractionTask(ctx context.Context, request GenerateRe
reason = "该模型使用 CreateInteraction 后台任务,收集完成后返回"
}
reportUpstreamMode(ctx, "GetInteractionStream", "stream", 0, reason)
body, proofAt, binding, err := EncodeCreateInteractionRequest(request, entry.model)
body, proofAt, binding, err := EncodeCreateInteractionRequest(request, entry.model, entry.defaults)
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrInvalidArgument, err)
}
Expand Down
2 changes: 2 additions & 0 deletions internal/aistudio/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,8 @@ func decodeModelRow(raw json.RawMessage, rowIndex int) (modelEntry, error) {
}
// field 4 为 2 且不是后台任务的模型经 CreateInteractionStream 生成,与官网一样以内联数据发送图片
model.Capabilities["interaction_stream"] = kind == 2 && !model.Capabilities["interaction_task"]
// field 4 为 2 表示 interaction 目标是模型而非 agent,后台任务的 CreateInteraction 在 field 17 携带模型目标
model.Capabilities["interaction_model"] = kind == 2
if value := rawAt(interaction, 5); !isJSONNull(value) {
agentModel, err := rawString(value, path+"[78][5]", raw)
if err != nil {
Expand Down
6 changes: 6 additions & 0 deletions internal/aistudio/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -645,11 +645,17 @@ func (l *AccountLease) InteractionRoute(modelID string) (stream bool, task bool)
return interactionRoute(model, GenerationDefaults{}, l.Channel())
}

// DisableInteractionModels 置位时 kind=2 interaction 模型不按目录标记走 CreateInteractionStream/CreateInteraction,改与普通模型一样走 GenerateContent;由应用层按配置设置
var DisableInteractionModels bool

// interactionRoute 返回模型在指定通道上是否走 CreateInteractionStream 或 CreateInteraction 后台任务
func interactionRoute(model Model, defaults GenerationDefaults, channel Channel) (stream bool, task bool) {
if channel == ChannelBuild {
return false, false
}
if DisableInteractionModels && model.Capabilities["interaction_model"] {
return false, false
}
return model.Capabilities["interaction_stream"] || defaults.InteractionStream,
model.Capabilities["interaction_task"] || defaults.InteractionTask
}
Expand Down
1 change: 1 addition & 0 deletions internal/api/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,7 @@ type RuntimeConfig struct {
StripThoughtSignatures bool `json:"strip_thought_signatures"`
SearchModelAliases bool `json:"search_model_aliases"`
DiscoverHiddenModels bool `json:"discover_hidden_models"`
DisableInteractionModels bool `json:"disable_interaction_models"`
GoogleSearch bool `json:"google_search"`
FirstEventHedge string `json:"first_event_hedge"`
FirstEventHedgeModels string `json:"first_event_hedge_models"`
Expand Down
2 changes: 2 additions & 0 deletions internal/app/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -1728,6 +1728,7 @@ func (admin *runtimeAdmin) UpdateRuntimeConfig(_ context.Context, value api.Runt
BuildNativeNonstream: value.BuildNativeNonstream,
NonstreamKeepalive: value.NonstreamKeepalive, FakeStream: value.FakeStream, YouTubeLinks: value.YouTubeLinks,
SearchModelAliases: value.SearchModelAliases, DiscoverHiddenModels: value.DiscoverHiddenModels, GoogleSearch: value.GoogleSearch, StripThoughtSignatures: value.StripThoughtSignatures,
DisableInteractionModels: value.DisableInteractionModels,
ContinuationRewrite: value.ContinuationRewrite, ContinuationPrompt: strings.TrimSpace(value.ContinuationPrompt),
ReplyTool: value.ReplyTool, UserMessageRewrite: strings.ToLower(strings.TrimSpace(value.UserMessageRewrite)), ThinkingGuard: value.ThinkingGuard,
FirstEventHedge: strings.ToLower(strings.TrimSpace(value.FirstEventHedge)), FirstEventHedgeModels: strings.TrimSpace(value.FirstEventHedgeModels), FirstEventTimeout: strings.ToLower(strings.TrimSpace(value.FirstEventTimeout)), AuthStates: value.AuthStates, ListenAddr: value.ListenAddr, PreviewListenAddr: value.PreviewListenAddr,
Expand Down Expand Up @@ -2082,6 +2083,7 @@ func runtimeConfigDTO(cfg config.Config) api.RuntimeConfig {
BuildNativeNonstream: cfg.BuildNativeNonstream,
NonstreamKeepalive: cfg.NonstreamKeepalive, FakeStream: cfg.FakeStream, YouTubeLinks: cfg.YouTubeLinks,
SearchModelAliases: cfg.SearchModelAliases, DiscoverHiddenModels: cfg.DiscoverHiddenModels, GoogleSearch: cfg.GoogleSearch, StripThoughtSignatures: cfg.StripThoughtSignatures,
DisableInteractionModels: cfg.DisableInteractionModels,
ContinuationRewrite: cfg.ContinuationRewrite, ContinuationPrompt: cfg.ContinuationPrompt,
ReplyTool: cfg.ReplyTool, UserMessageRewrite: cfg.UserMessageRewrite, ThinkingGuard: cfg.ThinkingGuard,
FirstEventHedge: cfg.FirstEventHedge, FirstEventHedgeModels: cfg.FirstEventHedgeModels, FirstEventTimeout: cfg.FirstEventTimeout, AuthStates: cfg.AuthStates, ListenAddr: cfg.ListenAddr, APIKey: cfg.ProxyAPIKey,
Expand Down
1 change: 1 addition & 0 deletions internal/app/lifecycle.go
Original file line number Diff line number Diff line change
Expand Up @@ -778,6 +778,7 @@ func (manager *runtimeManager) UpdateRuntimeConfig(ctx context.Context, value ap
)
mapping, _ := config.ParseModelMapping(updated.ModelMapping)
current.service.SetRequestPolicy(mapping, updated.MaxAccountSwitches)
aistudio.DisableInteractionModels = updated.DisableInteractionModels
manager.settings.Store(&requestSettings{
modes: api.ResponseModes{NonstreamKeepalive: updated.NonstreamKeepalive, FakeStream: updated.FakeStream},
searchModelAliases: updated.SearchModelAliases,
Expand Down
1 change: 1 addition & 0 deletions internal/app/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ func newRuntime(
pooled.YouTubeLinks = cfg.YouTubeLinks
pooled.DiscoverHiddenModels = cfg.DiscoverHiddenModels
pooled.StripThoughtSignatures = cfg.StripThoughtSignatures
aistudio.DisableInteractionModels = cfg.DisableInteractionModels
pooled.ContinuationRewrite = cfg.ContinuationRewrite
pooled.ContinuationPrompt = cfg.ContinuationPrompt
service := newTrackedService(lifecycle, pooled, pool, requests, workers, cfg.RequestTimeout)
Expand Down
4 changes: 4 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ var configKeys = [...]string{
"STRIP_THOUGHT_SIGNATURES",
"SEARCH_MODEL_ALIASES",
"DISCOVER_HIDDEN_MODELS",
"DISABLE_INTERACTION_MODELS",
"GOOGLE_SEARCH",
"FIRST_EVENT_HEDGE",
"FIRST_EVENT_HEDGE_MODELS",
Expand Down Expand Up @@ -142,6 +143,7 @@ type Config struct {
StripThoughtSignatures bool
SearchModelAliases bool
DiscoverHiddenModels bool
DisableInteractionModels bool
GoogleSearch bool
FirstEventHedge string
FirstEventHedgeModels string
Expand Down Expand Up @@ -256,6 +258,7 @@ var configSetters = map[string]func(*Config, string) error{
"GOOGLE_SEARCH": boolSetter("GOOGLE_SEARCH", func(c *Config) *bool { return &c.GoogleSearch }),
"YOUTUBE_LINKS": boolSetter("YOUTUBE_LINKS", func(c *Config) *bool { return &c.YouTubeLinks }),
"STRIP_THOUGHT_SIGNATURES": boolSetter("STRIP_THOUGHT_SIGNATURES", func(c *Config) *bool { return &c.StripThoughtSignatures }),
"DISABLE_INTERACTION_MODELS": boolSetter("DISABLE_INTERACTION_MODELS", func(c *Config) *bool { return &c.DisableInteractionModels }),
"CONTINUATION_REWRITE": boolSetter("CONTINUATION_REWRITE", func(c *Config) *bool { return &c.ContinuationRewrite }),
"REPLY_TOOL": boolSetter("REPLY_TOOL", func(c *Config) *bool { return &c.ReplyTool }),
"USER_MESSAGE_REWRITE": textSetter(func(c *Config) *string { return &c.UserMessageRewrite }, lowerTrim),
Expand Down Expand Up @@ -644,6 +647,7 @@ func (c Config) envValues() map[string]string {
"YOUTUBE_LINKS": strconv.FormatBool(c.YouTubeLinks),
"STRIP_THOUGHT_SIGNATURES": strconv.FormatBool(c.StripThoughtSignatures),
"SEARCH_MODEL_ALIASES": strconv.FormatBool(c.SearchModelAliases),
"DISABLE_INTERACTION_MODELS": strconv.FormatBool(c.DisableInteractionModels),
"DISCOVER_HIDDEN_MODELS": strconv.FormatBool(c.DiscoverHiddenModels),
"GOOGLE_SEARCH": strconv.FormatBool(c.GoogleSearch),
"FIRST_EVENT_HEDGE": c.FirstEventHedge,
Expand Down