Repository navigation
Description
发生了什么 / 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.
代码位置:
internal/aistudio/interaction.go(encodeModelInteraction,第 279–316 行)docs/protocol.md第 1457 行
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。
代码位置:
internal/aistudio/schema.go(geminiSchema,第 160–166 行)internal/aistudio/tools.go(toolSchemaShape,第 283 行)
两条路径都无条件把任意字符串 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
现象:
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等全部剥离。
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 通道。
建议修复:
- 在
schema.go的allowed白名单补齐"exclusiveMaximum": true, "uniqueItems": true,并在tools.go第 266 行补齐对应判断; - 在
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_ 前缀:
代码位置:
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。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}实际影响:
QuotaCooldownForError(internal/aistudio/quota.go第 84–88 行)仅在rpcError.StatusCode == http.StatusTooManyRequests(429)时生效;当后台 Interaction 任务因额度/限流以status == 4失败时,由于StatusCode被写死为502,该账号不会进入额度冷却,后续请求仍会反复命中该耗尽账号;- 若
status == 4的错误实为参数错误(code3/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