Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

[Bug] CreateInteraction 单独发送 responseMimeType 返回 400,以及 Playground JSON Schema 的 format 与关键字校验遗漏 #375

Backlog

Description

@roompragma-afk

发生了什么 / What happened

在 v0.3.17(5deae85)上排查并确认了六个可稳定复现的请求编码与响应映射问题:


1. CreateInteraction 设置了 interaction[15](responseMimeType)但未设置 responseFormat,上游稳定返回 HTTP 400

现象与上游报错:
在已迁移至后台模型通道(field 79 kind 2,例如 gemini-4-*)的账号上,只要客户端请求启用了 JSON 模式或结构化输出(例如 OpenAI response_format: {"type": "json_object"} / json_schema,或 Gemini generationConfig.responseMimeType: "application/json"),上游 CreateInteraction 直接返回:

HTTP 400, protocol error code 3: responseFormat must be set when responseMimeType is set.

代码位置:

system := request.System
responseMIME := strings.TrimSpace(request.Config.ResponseMIMEType)
if schema := request.Config.responseSchema(); len(schema) > 0 {
    if _, err := encodeResponseSchema(schema); err != nil {
        return nil, nil, fmt.Errorf("response schema: %w", err)
    }
    system = append(slices.Clone(system), describedSchema("", schema))
    if responseMIME == "" {
        responseMIME = "application/json"
    }
}
...
if responseMIME != "" {
    interaction[15] = responseMIME
}

原因与建议修复:
encodeModelInteraction 只写入了 interaction[15] = responseMIME,从未设置对应的 responseFormat 字段,导致所有经 CreateInteraction 的 JSON / 结构化输出请求必现 400。

  • 若上游 CreateInteraction 存在已验证的 responseFormat 线格式位置,建议一并编码发送;
  • 若暂不发送线格式 responseFormat,建议在未提供 responseFormat 时省略 interaction[15](Schema 约束已通过 describedSchema 写入 system),避免触发上游强校验报错。

最小复现请求(OpenAI 或 Gemini 均可复现):

{
  "model": "gemini-4-...",
  "response_format": { "type": "json_object" },
  "messages": [{ "role": "user", "content": "Return {\"ok\": true}" }]
}

2. Playground Schema 编码原样透传任意 format 值,导致 Pydantic / Zod / MCP 工具声明触发上游 400

现象:
常见框架(Pydantic v2、Zod z.string().url() / .email() / .uuid()、FastAPI、各类 MCP Server)生成的 JSON Schema 普遍带有标准 Draft-07/2020-12 的 format(如 "uri"、"email"、"uuid"、"date"、"hostname")。经 Playground 通道发送给 MakerSuite 时,上游仅接受特定 format 集合(如 STRING 仅接受 enum / date-time,INTEGER 接受 int32 / int64,NUMBER 接受 float / double),其余值直接返回 HTTP 400 INVALID_ARGUMENT。

代码位置:

两条路径都无条件把任意字符串 format 复制到 Playground Schema 的 field 1:

if value, ok := schema["format"]; ok {
    format, err := schemaString(value, "format")
    if err != nil {
        return nil, err
    }
    encoded["format"] = format
}

最小复现工具参数:

{
  "type": "object",
  "properties": {
    "url": { "type": "string", "format": "uri" },
    "id": { "type": "string", "format": "uuid" }
  },
  "required": ["url"]
}

建议修复:
在写入 Playground Schema encoded["format"](以及 toolSchemaShape)前按节点 type 校验上游支持的 format 白名单;不受支持的 format 从 wire field 1 中省略,并在需要时由工具说明/完整 Schema 保留该约束。


3. geminiSchema 的 allowed 白名单与 tools.go 漏掉了 exclusiveMaximum 和 uniqueItems,且 encodeResponseSchema 未调用 inlineSchemaRefs

现象:

  1. docs/protocol.md 第 1224 行和 jsonSchemaBeyondPlayground 已明确列出了 exclusiveMaximum 与 uniqueItems,但 geminiSchema 的 allowed 表以及 tools.go 的说明附加判断都漏掉了这两个关键字:
    • internal/aistudio/schema.go 第 142–148 行:allowed 包含 exclusiveMinimum、propertyNames、prefixItems、additionalProperties,但缺少 exclusiveMaximum 和 uniqueItems。
    • internal/aistudio/schema.go 第 1024 行:jsonSchemaBeyondPlayground 明确包含 exclusiveMaximum 与 uniqueItems。
    • internal/aistudio/tools.go 第 266 行:判断是否向 description 附加完整 JSON Schema 时同样漏掉了 "exclusiveMaximum" 与 "uniqueItems"。
    • 结果:只要 Schema 中任意节点带 exclusiveMaximum 或 uniqueItems,geminiSchema() 就会返回 UnverifiedProtocolError,迫使整份 Schema 降级走 toolSchemaShape(),将原本支持的 oneOf/anyOf/allOf/not/example 等全部剥离。
  2. tools.go 第 254 行在编码函数参数前调用了 inlined := inlineSchemaRefs(ordered),但结构化输出路径 encodeResponseSchema(schema.go 第 921 行) 与 RequestNeedsBuild(schema.go 第 997 行) 均未调用 inlineSchemaRefs。Pydantic / Zod 生成的结构化输出 Schema 一旦含 #/$defs/... 本地引用,就会在 geminiSchema() 中因遇到 "$ref" 报错并退化为不完整形状($ref 指向的节点变成空 {}),且 RequestNeedsBuild 会把本可在 Playground 展开的本地 $ref 误判为需要 Build 通道。

建议修复:

  1. 在 schema.go 的 allowed 白名单补齐 "exclusiveMaximum": true, "uniqueItems": true,并在 tools.go 第 266 行补齐对应判断;
  2. 在 encodeResponseSchema(或统一的 Schema 入口)中先执行 inlineSchemaRefs(同时可支持标准 JSON Pointer 多级路径与 ~0/~1 转义)。

4. normalizedReasoningEffort 与 geminiLiveBidiSetup 未剥离标准 Protobuf 枚举前缀 THINKING_LEVEL_*,导致返回 400

现象:
标准 Gemini API / Protobuf JSON 客户端在发送 generationConfig.thinkingConfig.thinkingLevel 时,除了简写形式("LOW"、"HIGH")外,常发送带完整枚举前缀的 "THINKING_LEVEL_MINIMAL"、"THINKING_LEVEL_LOW"、"THINKING_LEVEL_MEDIUM"、"THINKING_LEVEL_HIGH"、"THINKING_LEVEL_EXTRA_HIGH"。
目前代码专门处理了 "THINKING_LEVEL_UNSPECIFIED",但未剥离非空档位的 thinking_level_ 前缀:

代码位置:

  1. internal/aistudio/generate.go(normalizedReasoningEffort,第 368–374 行):
    func normalizedReasoningEffort(value string) string {
        effort := strings.ToLower(strings.TrimSpace(value))
        if effort == "thinking_level_unspecified" {
            return ""
        }
        return effort
    }
    当传入 "THINKING_LEVEL_HIGH" 时返回 "thinking_level_high",随后在 parseReasoningEffortLevel(interaction.go:771)中命中 default 分支,直接报错 400: reasoning effort 必须是 none、minimal、low、medium、high、xhigh、extra_high 或 max。
  2. internal/api/live_gemini.go(geminiLiveBidiSetup,第 262–264 行):
    同文件对 mediaResolution 和 turnCoverage 都定义了带前缀的映射表(第 146–150 行),唯独 ThinkingLevel 直接做了 strings.ToLower(config.ThinkingConfig.ThinkingLevel),导致 "THINKING_LEVEL_LOW" 变成 "thinking_level_low" 并在 validateLiveVariant(bidi.go:127)被拒绝:
    thinking_level 必须是 minimal、low、medium 或 high
    

建议修复:
在 normalizedReasoningEffort 与 geminiLiveBidiSetup 中统一使用 strings.TrimPrefix(..., "thinking_level_") 去掉枚举前缀("unspecified" 仍归为空串 "")。


5. Generate 在 Interaction 模型路径(route.IsModel())漏掉了 c.turns.restore,导致混合号池无法从进程内轮次缓存恢复思考签名

现象:
docs/protocol.md 第 1465 行明确说明:模型目标(field 79 kind 2)的 Interaction 路径「在混合账户池中写入轮次缓存以与未迁移账户的 GenerateContent 接续思考签名」。
但实际代码中,interactionEvents 虽然在结束时调用了 c.turns.store(...),入口处却被 !route.IsInteraction() 跳过了 c.turns.restore(...):

代码位置:

  • internal/aistudio/generate.go 第 812–821 行:
    restoring := request.restoreModelTurns && !build && !assistant && !route.IsAgent()
    if restoring && c.turns != nil {
        if !route.IsInteraction() {
            var tip turnLink
            request.Contents, request.turnToken, tip = c.turns.restore(apiKey, request.Contents)
            request.turnChain = turnChain{contents: request.Contents, tip: tip}
        } else {
            request.turnChain = turnChain{contents: request.Contents, tip: turnChain{}.tipOf(request.Contents)}
        }
    }
  • internal/aistudio/interaction.go 第 968–970 行:
    if err == nil && finished && restoring && c.turns != nil {
        c.turns.store(apiKey, request.turnChain.tip, turn)
    }

实际影响:
当上一轮由未迁移账号(GenerateContent)或已迁移账号(CreateInteraction)生成并存入 c.turns,下一轮请求被调度到已迁移账号(route.IsInteraction() && route.IsModel())时,若客户端未回传 thoughtSignature,由于 else 分支没有调用 c.turns.restore,历史模型轮中的 Thought 与 ThoughtSignature 不会被补回,全部退化为 skip_thought_signature_validator 占位签名。

建议修复:
既然 restoring 已经排除了 route.IsAgent(),对所有 restoring && c.turns != nil 的模型请求统一调用 c.turns.restore(apiKey, request.Contents) 补回历史模型轮的思考与签名 Part(Interaction 路径仅忽略返回的 turnToken 即可)。


6. DecodeInteractionStream 对最终状态 status == 4(Failed)硬编码返回 502 Bad Gateway,导致上游 429 额度耗尽不触发账号冷却与换号

现象:
在 CreateInteractionStream / GetInteractionStream 中,流尾 trailer 使用 interactionStatusHTTP(interaction.go 第 56–60 行)将 google.rpc.Code(如 8 -> 429、3 -> 400、7 -> 403)映射为对应的 HTTP 状态码。
但当上游通过最终 interaction 事件($event[19][0],status == 4)并在 field 28(interaction[27])中返回错误码与消息时,decodeEvent 却无条件硬编码为 http.StatusBadGateway(502):

代码位置:

case 4:
    message := decodeInteractionErrors(rawAt(interaction, 27))
    if message == "" {
        message = "interaction failed"
    }
    return false, &RPCError{Method: d.method, StatusCode: http.StatusBadGateway, Message: message}

实际影响:

  1. QuotaCooldownForError(internal/aistudio/quota.go 第 84–88 行)仅在 rpcError.StatusCode == http.StatusTooManyRequests(429)时生效;当后台 Interaction 任务因额度/限流以 status == 4 失败时,由于 StatusCode 被写死为 502,该账号不会进入额度冷却,后续请求仍会反复命中该耗尽账号;
  2. 若 status == 4 的错误实为参数错误(code 3 / INVALID_ARGUMENT,应为 400),写死为 502 会导致 retryableGenerateAccountError(runtime.go 第 3438 行)将其误判为可重试服务端错误,白白消耗 MAX_ACCOUNT_SWITCHES 在其他账号上重放必败请求。

建议修复:
在解析 interaction[27](decodeInteractionErrors)时保留上游错误码,按 interactionStatusHTTP / 标准 google.rpc.Code 映射设置 RPCError.StatusCode 与 RPCError.Code(未知错误码再回退 http.StatusBadGateway)。

版本 / Version

v0.3.17

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions