From d3cb5355b9779fd587beb15db4522d87e7613e78 Mon Sep 17 00:00:00 2001 From: csszyft Date: Thu, 26 Nov 2026 20:06:55 +0000 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=20gemini-gif=20?= =?UTF-8?q?=E5=8A=A8=E5=9B=BE=E7=94=9F=E6=88=90=E6=94=AF=E6=8C=81=E5=B9=B6?= =?UTF-8?q?=E5=AF=B9=E9=BD=90=20OpenAI=20/=20Gemini=20=E7=94=BB=E5=9B=BE?= =?UTF-8?q?=E4=B8=8E=E5=A4=9A=E5=9B=BE=E5=8D=8F=E8=AE=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增纯 Go 二进制 protobuf 通道编解码与 5s 后台 hNvQHb 轮询以支持 gemini-gif - 对齐 OpenAI /v1/images/generations 与 /v1/images/edits(multipart + JSON 多图与 gpt-image-2.6 字段) - 对齐 Gemini :generateContent(responseModalities=IMAGE、imageConfig)并开放 FeatureImage :predict - Chat Completions 透传图片宽高比,Responses image_generation_call 返回 output_format - 补充 README / protocol 文档与单元测试 --- README.en.md | 5 +- README.md | 5 +- docs/protocol.md | 7 +- internal/adapter/gemini_handler.go | 58 ++- internal/adapter/gemini_predict.go | 275 ++++++++++ internal/adapter/image_gif_compat_test.go | 278 ++++++++++ internal/adapter/image_handler.go | 342 ++++++++++-- internal/adapter/openai_chat.go | 30 +- internal/adapter/responses_handler.go | 10 +- internal/adapter/stream.go | 2 +- internal/adapter/tool_bridge.go | 2 + internal/gemini/channel.go | 66 ++- internal/gemini/channel_proto.go | 521 +++++++++++++++++++ internal/gemini/client.go | 51 +- internal/gemini/cookies.go | 3 + internal/gemini/decoder.go | 164 +++++- internal/gemini/gif_decoder_test.go | 606 ++++++++++++++++++++++ internal/gemini/model_guard.go | 24 +- internal/gemini/models.go | 56 +- internal/gemini/payload.go | 15 +- internal/gemini/request.go | 1 + internal/gemini/research.go | 13 +- 22 files changed, 2426 insertions(+), 108 deletions(-) create mode 100644 internal/adapter/gemini_predict.go create mode 100644 internal/adapter/image_gif_compat_test.go create mode 100644 internal/gemini/channel_proto.go create mode 100644 internal/gemini/gif_decoder_test.go diff --git a/README.en.md b/README.en.md index 5d8dc64..29493cb 100644 --- a/README.en.md +++ b/README.en.md @@ -48,6 +48,7 @@ Convert Google Gemini Web into OpenAI, Claude, and Gemini compatible APIs. | `gemini-4-hydrogen-task`, `gemini-4-carbon-task`, `gemini-4-neon-task` | Task | Tasks performed on your behalf | | | | `gemini-default` | Default | Each account's official default model | | | | `gemini-3.1-flash-image` | Nano Banana 2 | Image generation and editing | | | +| `gemini-gif` | GIF | Animated GIF generation and editing | | | | `gemini-video` | Video | Video generation | | | | `gemini-music` | Music | Music generation | | | | `gemini-canvas` | Canvas | Documents and code (hidden by default; toggle on Models page) | | | @@ -60,9 +61,9 @@ Convert Google Gemini Web into OpenAI, Claude, and Gemini compatible APIs. - **Subscription tiers**: a model that only a higher subscription tier offers returns 403 with the required tier and the current accounts' tiers - **Catalog fields**: `available_account_count` is the number of usable accounts, `default` marks the default model, and `thinking_levels` lists the available thinking levels - **Tool models**: tool IDs appear only for accounts that have the corresponding official tool and run on that account's official default model -- **Images**: the image ID works with conversational image requests and `/v1/images/*`; `size` and `imageConfig.aspectRatio` support 1:1, 9:16, 3:4, 4:3, 16:9, 2:3, 21:9, 1:8, and 8:1 +- **Images**: the image IDs work with conversational image requests, Gemini `generateContent` / `:predict`, and `/v1/images/*` (text-to-image and multi-image editing); `size` and `imageConfig.aspectRatio` support 1:1, 9:16, 3:4, 4:3, 16:9, 2:3, 21:9, 1:8, and 8:1 (`gemini-gif` snaps to 16:9 or 9:16) - **Video**: for video IDs, `imageConfig.aspectRatio` supports landscape 16:9 and portrait 9:16 -- **Chat history**: Task, Deep Research, and video requests use saved chats; Deep Research and video chats remain in the account history, and with `GEMINI_SAVE_HISTORY=false` (the default) a Task chat is deleted from the account together with its task record once generation has ended for over a minute without a follow-up, or when the service stops +- **Chat history**: Task, Deep Research, animated GIF, and video requests use saved chats; Deep Research, animated GIF, and video chats remain in the account history, and with `GEMINI_SAVE_HISTORY=false` (the default) a Task chat is deleted from the account together with its task record once generation has ended for over a minute without a follow-up, or when the service stops - **Deep Research**: the research plan and progress are returned as reasoning and the report as text, with the report's citations returned as web sources in each protocol's citation fields; a run usually takes over ten minutes, so set the client request timeout longer than that - **Quotas**: context windows, model access, and quotas depend on the account's plan and region; account usage is shown on the admin Accounts page - **Token usage**: text input, visible output, and reasoning summaries are counted with a local Gemini tokenizer; the token counting endpoints estimate images, audio, video, and PDFs with the Gemini API counting rules diff --git a/README.md b/README.md index 88a9705..987f377 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,7 @@ | `gemini-4-hydrogen-task`、`gemini-4-carbon-task`、`gemini-4-neon-task` | Task | 代为执行任务 | | | | `gemini-default` | Default | 各账号的官方默认模型 | | | | `gemini-3.1-flash-image` | Nano Banana 2 | 图片生成与编辑 | | | +| `gemini-gif` | GIF | 动图生成与编辑 | | | | `gemini-video` | Video | 视频生成 | | | | `gemini-music` | Music | 音乐生成 | | | | `gemini-canvas` | Canvas | 文档与代码(默认关闭,可在模型页开启) | | | @@ -60,9 +61,9 @@ - **订阅层级**:只有更高订阅层级才有的模型返回 403,写明所需层级与当前账号的层级 - **目录字段**:`available_account_count` 是可用账号数,`default` 标出默认模型,`thinking_levels` 列出可选思考强度 - **工具模型**:工具 ID 只在账号具备对应官网工具时出现,由该账号的官网默认模型执行 -- **图片**:图片 ID 用于对话生图和 `/v1/images/*`,`size` 与 `imageConfig.aspectRatio` 支持 1:1、9:16、3:4、4:3、16:9、2:3、21:9、1:8、8:1 +- **图片**:图片 ID 用于对话生图、Gemini `generateContent` / `:predict` 和 `/v1/images/*`(支持文生图与多图图生图),`size` 与 `imageConfig.aspectRatio` 支持 1:1、9:16、3:4、4:3、16:9、2:3、21:9、1:8、8:1(`gemini-gif` 动图对齐到官网 16:9 或 9:16) - **视频**:视频 ID 的 `imageConfig.aspectRatio` 支持横向 16:9 与竖向 9:16 -- **会话历史**:Task、Deep Research 与视频请求使用普通会话;Deep Research 与视频的对话保存在账号历史中,`GEMINI_SAVE_HISTORY=false`(默认)时,Task 的会话在生成结束超过一分钟且没有续接后或服务停止时,连同任务记录从账号中删除 +- **会话历史**:Task、Deep Research、GIF 动图与视频请求使用普通会话;Deep Research、GIF 与视频的对话保存在账号历史中,`GEMINI_SAVE_HISTORY=false`(默认)时,Task 的会话在生成结束超过一分钟且没有续接后或服务停止时,连同任务记录从账号中删除 - **Deep Research**:研究计划与进度作为思考内容返回,报告作为正文返回,报告中的引用以各协议的引用字段给出网页来源;一次通常需要十几分钟,客户端请求超时要设得更长 - **配额**:上下文窗口、模型权限和配额由账号的套餐与地区决定,账号用量在管理端账号页查看 - **token usage**:文本输入、可见输出和思考摘要按 Gemini tokenizer 计算;计数接口中的图片、音频、视频与 PDF 按 Gemini API 计数规则估算 diff --git a/docs/protocol.md b/docs/protocol.md index 48c4865..086752c 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -278,6 +278,7 @@ payload[24] = ["neon_launch_ultra_policy",[ | 公开 ID | 官网工具 | featureMode | 能力号 | | --- | --- | ---: | ---: | | `gemini-3.1-flash-image` | Create image | `14` | `82` | +| `gemini-gif` | Create image(GIF) | `14` | `82`、`247` | | `gemini-video` | Create video | `11` | `71`、`140` | | `gemini-music` | Create music | `21` | `139` | | `gemini-canvas` | Canvas | `2` | `51` | @@ -292,7 +293,7 @@ payload[24] = ["neon_launch_ultra_policy",[ - **模型内容**:显示名称与说明取 Gem 行 `[ID,[名称,说明],[指令]]`,协调模型取账号默认模型,生成请求在 `inner[19]` 写 Gem ID - **读取失败**:重读时 Gem 列表读取失败(如 `CNgdBe` 返回 1096“无法加载对话”)沿用上次读到的 Gem;首次初始化就失败的账号不提供 Gem,其余模型照常可用 -Task、Deep Research 只在普通会话中提供,视频成品在生成流结束后从会话读取;这三类请求在 `GEMINI_SAVE_HISTORY=false` 时也使用普通会话。Deep Research 与 Create video 的会话保留在账号历史中;Task 会话的删除见 [Task](#task) 的“不保存历史时的清理”。 +Task、Deep Research、GIF 动图只在普通会话中提供,视频与 GIF 成品在生成流结束后从会话读取;这几类请求在 `GEMINI_SAVE_HISTORY=false` 时也使用普通会话。Deep Research、Create image(GIF)与 Create video 的会话保留在账号历史中;Task 会话的删除见 [Task](#task) 的“不保存历史时的清理”。 `payload[19]` 是工具选项组。组槽 `0` 为 featureMode,`3` 为组名,`7` 为选项;选项槽 `0` 为选项 ID,`2` 为默认选中,`3` 为显示名称。Pro 账号的选项组为: @@ -1162,7 +1163,9 @@ candidate[12][7] = [[[ 同一 payload 的镜像结构也在 `payload[26][0][0][0][9][0][0][3][18]` 重复 generator tag;当前解码器以候选 rich content 为主读取路径。 -服务公开的 `gemini-3.1-flash-image` 见「工具条目」,协调模型为账号默认模型。该 ID 支持对话入口、Gemini `generateContent` 与 `/v1/images/generations`、`/v1/images/edits`;Responses 的 `image_generation` 工具对所选模型发送 Create image。OpenAI Chat/Responses 通过 `provider_model` 返回实际 generator tag。 +服务公开的 `gemini-3.1-flash-image` 见「工具条目」,协调模型为账号默认模型。该 ID 支持对话入口、Gemini `generateContent` / `:predict` 与 `/v1/images/generations`、`/v1/images/edits`(均支持文生图与最多 10 张参考图);Responses 的 `image_generation` 工具对所选模型发送 Create image。OpenAI Chat/Responses 通过 `provider_model` 返回实际 generator tag。 + +服务同时公开 `gemini-gif`(Create image 工具并强制选中格式选项 `64`,宽高比自动对齐 `16:9` 或 `9:16`):该请求在持久化会话中以 `application/x-protobuf` 二进制 WebChannel 通道发送和解码,服务端收到后台生成标记后以 `5s` 间隔调用 `hNvQHb` 轮询直至成品完成,并在 OpenAI `/v1/images/*` 与 Gemini `generateContent`(兼容 `responseModalities: ["IMAGE"]`) / `:predict` 中按标准 `image/gif` 返回,`provider_model` 为 `models/omni_1p5_gif`。 图片生成期间还会先出现根级稀疏进度: diff --git a/internal/adapter/gemini_handler.go b/internal/adapter/gemini_handler.go index b3c9221..15a0256 100644 --- a/internal/adapter/gemini_handler.go +++ b/internal/adapter/gemini_handler.go @@ -115,6 +115,13 @@ func GeminiRouterHandler(pool *balancer.AccountPool, store *requestdb.Store) gin bindScope(c, pool, model) switch method { case "generateContent", "streamGenerateContent", "countTokens": + case "predict": + if imageModel(pool, model) { + geminiImagePredict(c, pool, model) + return + } + writeGeminiError(c, http.StatusNotFound, "NOT_FOUND", geminiUnsupportedMethod(model, method, geminiMethodCapability(method))) + return case "predictLongRunning": if videoModel(pool, model) { geminiVideoOperation(c, pool, store, model) @@ -595,19 +602,53 @@ func geminiToolBridge(request GeminiGenerateContentRequest) (ToolBridge, []strin return bridge, nil, err } for field := range config { - if field == "responseMimeType" || field == "responseJsonSchema" || field == "responseSchema" || field == "responseFormat" || field == "thinkingConfig" || field == "imageConfig" || field == "candidateCount" || field == "stopSequences" || field == "maxOutputTokens" { + if field == "responseMimeType" || field == "responseJsonSchema" || field == "responseSchema" || field == "responseFormat" || field == "responseModalities" || field == "thinkingConfig" || field == "imageConfig" || field == "candidateCount" || field == "stopSequences" || field == "maxOutputTokens" { continue } unsupported = append(unsupported, "generationConfig."+field) } + if raw, ok := config["responseModalities"]; ok && len(raw) > 0 && string(raw) != "null" { + var modalities []string + if err := json.Unmarshal(raw, &modalities); err != nil { + return bridge, nil, fmt.Errorf("generationConfig.responseModalities 必须是字符串数组") + } + var hasImage, hasText bool + for _, modality := range modalities { + switch strings.ToUpper(strings.TrimSpace(modality)) { + case "IMAGE": + hasImage = true + case "TEXT": + hasText = true + } + } + if hasImage && !hasText { + bridge.ImageOnly = true + } + } var imageConfig map[string]json.RawMessage - _ = json.Unmarshal(config["imageConfig"], &imageConfig) + if len(config["imageConfig"]) > 0 && string(config["imageConfig"]) != "null" { + if err := json.Unmarshal(config["imageConfig"], &imageConfig); err != nil { + return bridge, nil, fmt.Errorf("generationConfig.imageConfig 必须是对象") + } + } for field := range imageConfig { - if field != "aspectRatio" { + if field != "aspectRatio" && field != "outputMimeType" { unsupported = append(unsupported, "generationConfig.imageConfig."+field) } } - _ = json.Unmarshal(imageConfig["aspectRatio"], &bridge.AspectRatio) + var rawAspectRatio string + _ = json.Unmarshal(imageConfig["aspectRatio"], &rawAspectRatio) + bridge.AspectRatio = normalizeGeminiAspectRatio(rawAspectRatio) + if rawOutMime := imageConfig["outputMimeType"]; len(rawOutMime) > 0 && string(rawOutMime) != "null" { + var outMime string + if err := json.Unmarshal(rawOutMime, &outMime); err != nil { + return bridge, nil, fmt.Errorf("generationConfig.imageConfig.outputMimeType 必须是字符串") + } + outMime = strings.ToLower(strings.TrimSpace(outMime)) + if outMime != "" && outMime != "image/gif" && outMime != "image/png" && outMime != "image/jpeg" && outMime != "image/webp" { + unsupported = append(unsupported, "generationConfig.imageConfig.outputMimeType") + } + } if raw, ok := config["maxOutputTokens"]; ok { if err := json.Unmarshal(raw, &bridge.MaxTokens); err != nil { return bridge, nil, fmt.Errorf("generationConfig.maxOutputTokens 必须是整数") @@ -645,7 +686,7 @@ func geminiToolBridge(request GeminiGenerateContentRequest) (ToolBridge, []strin } if format.Image != nil { if format.Image.AspectRatio != "" { - bridge.AspectRatio = geminiResponseFormatValue(format.Image.AspectRatio) + bridge.AspectRatio = normalizeGeminiAspectRatio(geminiResponseFormatValue(format.Image.AspectRatio)) } if format.Image.ImageSize != "" { unsupported = append(unsupported, "generationConfig.responseFormat.image.imageSize") @@ -656,6 +697,7 @@ func geminiToolBridge(request GeminiGenerateContentRequest) (ToolBridge, []strin } } switch { + case strings.HasPrefix(strings.ToLower(strings.TrimSpace(mime)), "image/"): case mime == "text/x.enum": var enum struct { Enum []string `json:"enum"` @@ -805,7 +847,11 @@ func buildGeminiResponse(result generationResult, bridge ToolBridge, includeThou if includeThoughts && primary.Thought != "" { parts = append(parts, gin.H{"text": primary.Thought, "thought": true}) } - for _, part := range geminiStructuredParts(content, primary) { + displayText := content + if bridge.ImageOnly && hasGeneratedImage(primary) { + displayText = "" + } + for _, part := range geminiStructuredParts(displayText, primary) { parts = append(parts, geminiOutputPart(part)) } for index, call := range calls { diff --git a/internal/adapter/gemini_predict.go b/internal/adapter/gemini_predict.go new file mode 100644 index 0000000..23406de --- /dev/null +++ b/internal/adapter/gemini_predict.go @@ -0,0 +1,275 @@ +package adapter + +import ( + "cmp" + "context" + "encoding/base64" + "encoding/json" + "fmt" + "net/http" + "sort" + "strings" + + "github.com/Mag1cFall/Gemini-Web2API/internal/balancer" + "github.com/Mag1cFall/Gemini-Web2API/internal/gemini" + "github.com/Mag1cFall/Gemini-Web2API/internal/logging" + "github.com/gin-gonic/gin" +) + +type geminiPredictMedia struct { + BytesBase64Encoded string `json:"bytesBase64Encoded"` + MimeType string `json:"mimeType"` + GCSURI string `json:"gcsUri"` + URI string `json:"uri"` +} + +type geminiPredictReferenceImage struct { + ReferenceImage *geminiPredictMedia `json:"referenceImage"` + BytesBase64Encoded string `json:"bytesBase64Encoded"` + MimeType string `json:"mimeType"` + GCSURI string `json:"gcsUri"` + URI string `json:"uri"` +} + +type geminiPredictInstance struct { + Prompt string `json:"prompt"` + Image *geminiPredictMedia `json:"image"` + Images []geminiPredictMedia `json:"images"` + ReferenceImages []geminiPredictReferenceImage `json:"referenceImages"` +} + +type geminiPredictRequest struct { + Instances []geminiPredictInstance `json:"instances"` + Parameters map[string]json.RawMessage `json:"parameters"` +} + +func imageModel(pool *balancer.AccountPool, id string) bool { + model, ok := findModel(pool, id) + return ok && model.Feature == gemini.FeatureImage +} + +// normalizeGeminiAspectRatio 规范化图片宽高比;auto 与 1K/2K/4K 等分辨率挡位按未指定处理,WxH 约分为 W:H +func normalizeGeminiAspectRatio(raw string) string { + trimmed := strings.TrimSpace(raw) + if trimmed == "" || strings.EqualFold(trimmed, "auto") || imageResolutionTier(trimmed) { + return "" + } + if _, canonical, ok := gemini.ParseAspectRatio(trimmed, false); ok { + return canonical + } + return trimmed +} + +func imageResolutionTier(value string) bool { + switch strings.ToUpper(strings.TrimSpace(value)) { + case "1K", "2K", "4K": + return true + default: + return false + } +} + +func collectPredictMedia(instance geminiPredictInstance) []geminiPredictMedia { + items := make([]geminiPredictMedia, 0, 1+len(instance.Images)+len(instance.ReferenceImages)) + appendIfValid := func(item geminiPredictMedia) { + if strings.TrimSpace(item.BytesBase64Encoded) == "" && + strings.TrimSpace(item.URI) == "" && + strings.TrimSpace(item.GCSURI) == "" { + return + } + items = append(items, item) + } + if instance.Image != nil { + appendIfValid(*instance.Image) + } + for _, img := range instance.Images { + appendIfValid(img) + } + for _, ref := range instance.ReferenceImages { + if ref.ReferenceImage != nil { + appendIfValid(*ref.ReferenceImage) + continue + } + appendIfValid(geminiPredictMedia{ + BytesBase64Encoded: ref.BytesBase64Encoded, + MimeType: ref.MimeType, + GCSURI: ref.GCSURI, + URI: ref.URI, + }) + } + return items +} + +func firstParam(params map[string]json.RawMessage, keys ...string) (json.RawMessage, bool) { + for _, key := range keys { + if raw, ok := params[key]; ok && len(raw) > 0 && string(raw) != "null" { + return raw, true + } + } + return nil, false +} + +func parsePredictParameters(params map[string]json.RawMessage) (sampleCount int, aspectRatio string, unsupported []string, err error) { + sampleCount = 1 + if raw, ok := firstParam(params, "sampleCount", "sample_count"); ok { + var count protoInt + if err := json.Unmarshal(raw, &count); err != nil { + return 0, "", nil, fmt.Errorf("parameters.sampleCount 必须是整数") + } + if count < 1 || count > 4 { + return 0, "", nil, fmt.Errorf("parameters.sampleCount 必须在 1 到 4 之间") + } + sampleCount = int(count) + } + if raw, ok := firstParam(params, "aspectRatio", "aspect_ratio"); ok { + var ratio string + if err := json.Unmarshal(raw, &ratio); err != nil { + return 0, "", nil, fmt.Errorf("parameters.aspectRatio 必须是字符串") + } + aspectRatio = normalizeGeminiAspectRatio(ratio) + } + for field := range params { + switch field { + case "sampleCount", "sample_count", "aspectRatio", "aspect_ratio", "outputOptions", "output_options": + default: + unsupported = append(unsupported, "parameters."+field) + } + } + sort.Strings(unsupported) + return sampleCount, aspectRatio, unsupported, nil +} + +func resolvePredictMedia(ctx context.Context, client *gemini.Client, items []geminiPredictMedia) ([]gemini.FileData, error) { + files := make([]gemini.FileData, 0, len(items)) + for idx, item := range items { + mimeType := strings.TrimSpace(item.MimeType) + if b64 := strings.TrimSpace(item.BytesBase64Encoded); b64 != "" { + if dataMime, rawData, ok := splitDataURL(b64); ok { + mimeType = cmp.Or(mimeType, dataMime) + b64 = rawData + } + data, err := decodeBase64(b64) + if err != nil { + return nil, fmt.Errorf("image.bytesBase64Encoded: %w", err) + } + if mimeType == "" { + mimeType = strings.Split(http.DetectContentType(data), ";")[0] + } + files = append(files, gemini.FileData{ + Data: data, + FileName: fmt.Sprintf("image_%d%s", idx, mimeTypeToExt(mimeType)), + MimeType: mimeType, + }) + continue + } + uri := cmp.Or(strings.TrimSpace(item.URI), strings.TrimSpace(item.GCSURI)) + if uri == "" { + continue + } + if id, ok := storedFileID(uri); ok && (!strings.Contains(uri, "://") || strings.Contains(uri, "/v1beta/files/") || strings.Contains(uri, "/v1/files/")) { + file, err := storedFileData(ctx, id) + if err != nil { + return nil, err + } + if mimeType != "" { + file.MimeType = mimeType + } + files = append(files, *file) + continue + } + data, err := fetchRemoteMedia(ctx, client, uri) + if err != nil { + return nil, fmt.Errorf("下载参考图片失败: %w", err) + } + if mimeType == "" { + mimeType = strings.Split(http.DetectContentType(data), ";")[0] + } + files = append(files, gemini.FileData{ + Data: data, + FileName: fmt.Sprintf("image_%d%s", idx, mimeTypeToExt(mimeType)), + MimeType: mimeType, + }) + } + return files, nil +} + +// geminiImagePredict 处理 Gemini Imagen 风格 models/{model}:predict,支持文生图与单/多图参考图生图 +func geminiImagePredict(c *gin.Context, pool *balancer.AccountPool, model string) { + var request geminiPredictRequest + if err := decodeGeminiRequest(c, &request); err != nil { + writeGeminiError(c, http.StatusBadRequest, "INVALID_ARGUMENT", err.Error()) + return + } + if len(request.Instances) == 0 { + writeGeminiError(c, http.StatusBadRequest, "INVALID_ARGUMENT", "instances must contain at least one instance") + return + } + instance := request.Instances[0] + mediaSpecs := collectPredictMedia(instance) + if strings.TrimSpace(instance.Prompt) == "" && len(mediaSpecs) == 0 { + writeGeminiError(c, http.StatusBadRequest, "INVALID_ARGUMENT", "instances[0] must contain a prompt or at least one image") + return + } + if len(mediaSpecs) > maxInputImages { + writeGeminiError(c, http.StatusBadRequest, "INVALID_ARGUMENT", fmt.Sprintf("at most %d input images are supported", maxInputImages)) + return + } + sampleCount, aspectRatio, unsupported, err := parsePredictParameters(request.Parameters) + if err != nil { + writeGeminiError(c, http.StatusBadRequest, "INVALID_ARGUMENT", err.Error()) + return + } + logging.FromContext(c.Request.Context()).Begin("gemini", model, false, 1, 0) + if err := awaitModel(c, pool, model); err != nil { + writeGeminiError(c, upstreamStatus(err), geminiUpstreamStatus(err), err.Error()) + return + } + setUnsupportedParameters(c, unsupported) + + defer startNonstreamKeepalive(c)() + predictions := make([]gin.H, 0, sampleCount) + for index := 0; index < sampleCount && len(predictions) < sampleCount; index++ { + responseID := fmt.Sprintf("predict_%d_%d", index, len(predictions)) + result, accountID, err := runGeneration( + c.Request.Context(), pool, "", sessionContinue, model, responseID, generationMedia{requireImage: true, aspectRatio: aspectRatio}, gemini.ThinkingLow, ToolBridge{}, + func(client *gemini.Client, _ bool) (string, []gemini.FileData, error) { + files, err := resolvePredictMedia(c.Request.Context(), client, mediaSpecs) + if err != nil { + return "", nil, err + } + return instance.Prompt, files, nil + }, nil, nil, + ) + c.Set("account_id", accountID) + if err != nil { + writeGeminiError(c, upstreamStatus(err), geminiUpstreamStatus(err), err.Error()) + return + } + for _, image := range result.Accumulator.Primary().Media { + if len(predictions) == sampleCount { + break + } + if image.Type != gemini.MediaGeneratedImage { + continue + } + data, err := result.Client.FetchMediaContent(c.Request.Context(), image) + if err != nil { + writeGeminiError(c, upstreamStatus(err), "INTERNAL", err.Error()) + return + } + mimeType := strings.Split(http.DetectContentType(data), ";")[0] + if mimeType == "" || mimeType == "application/octet-stream" { + mimeType = cmp.Or(image.MIMEType, "image/png") + } + predictions = append(predictions, gin.H{ + "bytesBase64Encoded": base64.StdEncoding.EncodeToString(data), + "mimeType": mimeType, + }) + } + } + if len(predictions) == 0 { + writeGeminiError(c, http.StatusBadGateway, "INTERNAL", "Upstream returned no generated images") + return + } + c.JSON(http.StatusOK, gin.H{"predictions": predictions}) +} diff --git a/internal/adapter/image_gif_compat_test.go b/internal/adapter/image_gif_compat_test.go new file mode 100644 index 0000000..d3ae638 --- /dev/null +++ b/internal/adapter/image_gif_compat_test.go @@ -0,0 +1,278 @@ +package adapter + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "mime/multipart" + "net/http" + "net/http/httptest" + "slices" + "testing" + + "github.com/Mag1cFall/Gemini-Web2API/internal/balancer" + "github.com/Mag1cFall/Gemini-Web2API/internal/gemini" + "github.com/gin-gonic/gin" +) + +func TestResolveImageAspectRatioAndTiers(t *testing.T) { + cases := []struct { + size string + aspect string + want string + err bool + }{ + {"auto", "", "", false}, + {"1K", "", "", false}, + {"2k", "", "", false}, + {"4K", "16:9", "16:9", false}, + {"1024x1024", "", "1:1", false}, + {"1536x1024", "", "3:2", false}, + {"1024x1024", "1:1", "1:1", false}, + {"1024x1024", "16:9", "", true}, + {"invalid", "", "", true}, + } + for _, tc := range cases { + got, err := resolveImageAspectRatio(tc.size, tc.aspect) + if (err != nil) != tc.err { + t.Fatalf("resolveImageAspectRatio(%q, %q) err=%v wantErr=%v", tc.size, tc.aspect, err, tc.err) + } + if !tc.err && got != tc.want { + t.Fatalf("resolveImageAspectRatio(%q, %q) = %q want %q", tc.size, tc.aspect, got, tc.want) + } + } +} + +func TestNonEmptyImageParametersForGIFModel(t *testing.T) { + fc, fd := 9, 200 + req := ImageGenerationRequest{ + OutputFormat: "gif", + FrameCount: &fc, + FrameDurationMS: &fd, + Complexity: "medium", + Quality: "high", + } + gotGIF := nonEmptyImageParameters(req, true) + if slices.Contains(gotGIF, "output_format") { + t.Fatalf("expected output_format=gif to be supported on gif model, got %v", gotGIF) + } + for _, want := range []string{"frame_count", "frame_duration_ms", "complexity", "quality"} { + if !slices.Contains(gotGIF, want) { + t.Fatalf("expected %q in unsupported list %v", want, gotGIF) + } + } + gotStatic := nonEmptyImageParameters(req, false) + if !slices.Contains(gotStatic, "output_format") { + t.Fatalf("expected output_format on non-gif model, got %v", gotStatic) + } +} + +func TestParseAndResolveJSONImageInputsMultiImage(t *testing.T) { + tinyPNG := []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n', 0x00, 0x00, 0x00, 0x0d, 'I', 'H', 'D', 'R'} + b64PNG := base64.StdEncoding.EncodeToString(tinyPNG) + dataURI := "data:image/png;base64," + b64PNG + + specs, err := parseJSONImageInputs( + json.RawMessage(`"`+dataURI+`"`), + json.RawMessage(`["`+b64PNG+`", {"image_url": "`+dataURI+`"}, {"image_url": {"url": "`+dataURI+`"}}, {"file_id": "file_123"}]`), + json.RawMessage(`{"b64_json": "`+b64PNG+`"}`), + ) + if err != nil { + t.Fatalf("parseJSONImageInputs failed: %v", err) + } + if len(specs) != 6 { + t.Fatalf("expected 6 parsed inputs, got %d: %+v", len(specs), specs) + } + + // Verify base64 / data URI items resolve cleanly without store/network + files, err := resolveImageInputs(t.Context(), nil, []imageInputSpec{specs[0], specs[1], specs[2], specs[3], specs[5]}) + if err != nil { + t.Fatalf("resolveImageInputs failed: %v", err) + } + if len(files) != 5 { + t.Fatalf("expected 5 resolved files, got %d", len(files)) + } + for i, f := range files { + if !bytes.Equal(f.Data, tinyPNG) { + t.Fatalf("file[%d] data mismatch: got %x want %x", i, f.Data, tinyPNG) + } + } +} + +func TestCollectMultipartImageInputsMergesAllFields(t *testing.T) { + var body bytes.Buffer + writer := multipart.NewWriter(&body) + for _, field := range []string{"image", "image[]", "images", "images[]", "markup"} { + part, err := writer.CreateFormFile(field, field+".png") + if err != nil { + t.Fatal(err) + } + _, _ = part.Write([]byte("pngdata-" + field)) + } + _ = writer.WriteField("image", "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7") + _ = writer.Close() + + req := httptest.NewRequest(http.MethodPost, "/v1/images/edits", &body) + req.Header.Set("Content-Type", writer.FormDataContentType()) + if err := req.ParseMultipartForm(1 << 20); err != nil { + t.Fatal(err) + } + defer req.MultipartForm.RemoveAll() + + inputs, err := collectMultipartImageInputs(req.MultipartForm) + if err != nil { + t.Fatalf("collectMultipartImageInputs failed: %v", err) + } + if len(inputs) != 6 { + t.Fatalf("expected 6 merged inputs across file and text fields, got %d", len(inputs)) + } +} + +func TestImageEditHandlerValidationJSONAndLimit(t *testing.T) { + gin.SetMode(gin.TestMode) + pool := balancer.NewAccountPool(0, 0) + + // Missing image on JSON edits returns 400 + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/edits", bytes.NewBufferString(`{"model":"gemini-gif","prompt":"animate this","output_format":"gif"}`)) + c.Request.Header.Set("Content-Type", "application/json") + ImageEditHandler(pool)(c) + if w.Code != http.StatusBadRequest { + t.Fatalf("expected 400 for missing JSON image, got %d: %s", w.Code, w.Body.String()) + } + + // Over 10 images returns 400 (validates multi-image limit check rather than multipart rejection) + w2 := httptest.NewRecorder() + c2, _ := gin.CreateTestContext(w2) + c2.Request = httptest.NewRequest(http.MethodPost, "/v1/images/edits", bytes.NewBufferString(`{"model":"gemini-gif","prompt":"animate","images":["a","b","c","d","e","f","g","h","i","j","k"]}`)) + c2.Request.Header.Set("Content-Type", "application/json") + ImageEditHandler(pool)(c2) + if w2.Code != http.StatusBadRequest || !bytes.Contains(w2.Body.Bytes(), []byte("at most 10 input images")) { + t.Fatalf("expected 400 max 10 images error, got %d: %s", w2.Code, w2.Body.String()) + } +} + +func TestGeminiToolBridgeResponseModalitiesAndImageConfig(t *testing.T) { + raw, err := geminiCamelKeys([]byte(`{ + "contents": [{"role": "user", "parts": [{"text": "draw a bee"}]}], + "generation_config": { + "response_modalities": ["image"], + "response_mime_type": "image/gif", + "image_config": { + "aspect_ratio": "1024x1024", + "output_mime_type": "image/gif" + } + } + }`)) + if err != nil { + t.Fatalf("geminiCamelKeys failed: %v", err) + } + var req GeminiGenerateContentRequest + if err := json.Unmarshal(raw, &req); err != nil { + t.Fatalf("unmarshal failed: %v", err) + } + bridge, unsupported, err := geminiToolBridge(req) + if err != nil { + t.Fatalf("geminiToolBridge failed: %v", err) + } + if !bridge.ImageOnly { + t.Fatal("expected ImageOnly=true for responseModalities=[image]") + } + if bridge.AspectRatio != "1:1" { + t.Fatalf("expected AspectRatio 1:1, got %q", bridge.AspectRatio) + } + if len(bridge.JSONSchema) != 0 { + t.Fatalf("expected empty JSONSchema for responseMimeType=image/gif, got %s", bridge.JSONSchema) + } + if len(unsupported) != 0 { + t.Fatalf("expected zero unsupported params, got %v", unsupported) + } + + // buildGeminiResponse strips leading text when ImageOnly=true and a generated GIF is present + acc := NewEventAccumulator() + acc.Usage = &gemini.Usage{} + acc.candidate(0).Text = "你的 GIF 已准备就绪!" + acc.candidate(0).Media = []gemini.Media{{Type: gemini.MediaGeneratedImage, MIMEType: "image/gif", URL: "data:image/gif;base64,R0lGODlh"}} + resp, err := buildGeminiResponse(generationResult{Accumulator: acc, Model: "gemini-gif", ResponseID: "resp_1"}, bridge, false) + if err != nil { + t.Fatalf("buildGeminiResponse failed: %v", err) + } + parts := resp["candidates"].([]gin.H)[0]["content"].(gin.H)["parts"].([]gin.H) + if len(parts) != 1 || parts[0]["inlineData"] == nil { + t.Fatalf("expected only inlineData part when ImageOnly=true, got %+v", parts) + } + + // Text+Image preserves text part + bridgeBoth := bridge + bridgeBoth.ImageOnly = false + respBoth, err := buildGeminiResponse(generationResult{Accumulator: acc, Model: "gemini-gif", ResponseID: "resp_2"}, bridgeBoth, false) + if err != nil { + t.Fatalf("buildGeminiResponse failed: %v", err) + } + partsBoth := respBoth["candidates"].([]gin.H)[0]["content"].(gin.H)["parts"].([]gin.H) + if len(partsBoth) != 2 { + t.Fatalf("expected text + inlineData parts when ImageOnly=false, got %+v", partsBoth) + } +} + +func TestGeminiPredictParsingAndMultiImage(t *testing.T) { + raw, err := geminiCamelKeys([]byte(`{ + "instances": [{ + "prompt": "merge and animate", + "image": {"bytes_base64_encoded": "AAAA", "mime_type": "image/png"}, + "images": [{"uri": "https://example.com/a.jpg"}], + "reference_images": [ + {"reference_image": {"bytes_base64_encoded": "BBBB", "mime_type": "image/jpeg"}}, + {"bytes_base64_encoded": "CCCC", "mime_type": "image/webp"} + ] + }], + "parameters": { + "sample_count": 2, + "aspect_ratio": "1536x1024", + "output_options": {"mime_type": "image/gif"} + } + }`)) + if err != nil { + t.Fatalf("geminiCamelKeys failed: %v", err) + } + var req geminiPredictRequest + if err := json.Unmarshal(raw, &req); err != nil { + t.Fatalf("unmarshal predict request failed: %v", err) + } + media := collectPredictMedia(req.Instances[0]) + if len(media) != 4 { + t.Fatalf("expected 4 predict media items, got %d: %+v", len(media), media) + } + count, ratio, unsupported, err := parsePredictParameters(req.Parameters) + if err != nil { + t.Fatalf("parsePredictParameters failed: %v", err) + } + if count != 2 || ratio != "3:2" || len(unsupported) != 0 { + t.Fatalf("unexpected predict params: count=%d ratio=%q unsupported=%v", count, ratio, unsupported) + } + if _, _, _, err := parsePredictParameters(map[string]json.RawMessage{"sampleCount": json.RawMessage(`5`)}); err == nil { + t.Fatal("expected error for sampleCount=5") + } +} + +func TestChatImageAspectRatioAndResponsesOutputFormat(t *testing.T) { + req := ChatRequest{ + ImageConfig: &ChatImageConfig{AspectRatio: "16:9", ImageSize: "2K"}, + Size: "1K", + } + if got := chatImageAspectRatio(req); got != "16:9" { + t.Fatalf("expected 16:9, got %q", got) + } + if got := chatImageAspectRatio(ChatRequest{Size: "2K"}); got != "" { + t.Fatalf("expected empty ratio for tier 2K, got %q", got) + } + + out := CandidateOutput{ + Media: []gemini.Media{{Type: gemini.MediaGeneratedImage, URL: "data:image/gif;base64,R0lGODlh"}}, + } + items := responseImageGenerationItems(out, "resp_x") + if len(items) != 1 || items[0]["output_format"] != "gif" { + t.Fatalf("expected output_format=gif in image_generation_call item, got %+v", items) + } +} diff --git a/internal/adapter/image_handler.go b/internal/adapter/image_handler.go index c7b2f99..334c499 100644 --- a/internal/adapter/image_handler.go +++ b/internal/adapter/image_handler.go @@ -1,9 +1,14 @@ package adapter import ( + "bytes" + "cmp" + "context" "encoding/base64" + "encoding/json" "fmt" "io" + "mime/multipart" "net/http" "strconv" "strings" @@ -15,32 +20,43 @@ import ( "github.com/gin-gonic/gin" ) +const maxInputImages = 10 + // ImageGenerationRequest 表示 OpenAI 图片生成请求 type ImageGenerationRequest struct { - Prompt string `json:"prompt"` - Model string `json:"model,omitempty"` - N int `json:"n,omitempty"` - Size string `json:"size,omitempty"` - AspectRatio string `json:"aspect_ratio,omitempty"` - ResponseFormat string `json:"response_format,omitempty"` - Quality string `json:"quality,omitempty"` - Style string `json:"style,omitempty"` - Stream bool `json:"stream,omitempty"` - PartialImages *int `json:"partial_images,omitempty"` - OutputFormat string `json:"output_format,omitempty"` - OutputCompression *int `json:"output_compression,omitempty"` - Background string `json:"background,omitempty"` - User string `json:"user,omitempty"` - InputFidelity string `json:"input_fidelity,omitempty"` - Moderation string `json:"moderation,omitempty"` + Prompt string `json:"prompt"` + Model string `json:"model,omitempty"` + N int `json:"n,omitempty"` + Size string `json:"size,omitempty"` + AspectRatio string `json:"aspect_ratio,omitempty"` + ResponseFormat string `json:"response_format,omitempty"` + Quality string `json:"quality,omitempty"` + Style string `json:"style,omitempty"` + Stream bool `json:"stream,omitempty"` + PartialImages *int `json:"partial_images,omitempty"` + OutputFormat string `json:"output_format,omitempty"` + OutputCompression *int `json:"output_compression,omitempty"` + FrameCount *int `json:"frame_count,omitempty"` + FrameDurationMS *int `json:"frame_duration_ms,omitempty"` + Complexity string `json:"complexity,omitempty"` + Background string `json:"background,omitempty"` + User string `json:"user,omitempty"` + InputFidelity string `json:"input_fidelity,omitempty"` + Moderation string `json:"moderation,omitempty"` + Image json.RawMessage `json:"image,omitempty"` + Images json.RawMessage `json:"images,omitempty"` + Markup json.RawMessage `json:"markup,omitempty"` } -type imageInput struct { +type imageInputSpec struct { data []byte filename string + mimeType string + ref string + fileID string } -// ImageGenerationHandler 处理 OpenAI 图片生成 +// ImageGenerationHandler 处理 OpenAI 图片生成(兼容携带 image/images 参考图) func ImageGenerationHandler(pool *balancer.AccountPool) gin.HandlerFunc { return func(c *gin.Context) { var request ImageGenerationRequest @@ -49,13 +65,38 @@ func ImageGenerationHandler(pool *balancer.AccountPool) gin.HandlerFunc { writeOpenAIError(c, http.StatusBadRequest, "invalid_request", err.Error()) return } - handleImageRequest(c, pool, request, nil) + inputs, err := parseJSONImageInputs(request.Image, request.Images, request.Markup) + if err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", err.Error()) + return + } + handleImageRequest(c, pool, request, inputs) } } -// ImageEditHandler 处理 OpenAI 图片编辑 +// ImageEditHandler 处理 OpenAI 图片编辑(同时支持 multipart/form-data 多图与 application/json 多图) func ImageEditHandler(pool *balancer.AccountPool) gin.HandlerFunc { return func(c *gin.Context) { + contentType := strings.ToLower(strings.TrimSpace(c.GetHeader("Content-Type"))) + if strings.HasPrefix(contentType, "application/json") { + var request ImageGenerationRequest + if err := decodeRequest(c, &request); err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", err.Error()) + return + } + inputs, err := parseJSONImageInputs(request.Image, request.Images, request.Markup) + if err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", err.Error()) + return + } + if len(inputs) == 0 { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "image is required") + return + } + handleImageRequest(c, pool, request, inputs) + return + } + if err := c.Request.ParseMultipartForm(32 << 20); err != nil { writeOpenAIError(c, http.StatusBadRequest, "invalid_request", err.Error()) return @@ -69,8 +110,8 @@ func ImageEditHandler(pool *balancer.AccountPool) gin.HandlerFunc { request := ImageGenerationRequest{ Prompt: c.PostForm("prompt"), Model: c.PostForm("model"), Size: c.PostForm("size"), AspectRatio: c.PostForm("aspect_ratio"), ResponseFormat: c.PostForm("response_format"), Quality: c.PostForm("quality"), Style: c.PostForm("style"), - OutputFormat: c.PostForm("output_format"), Background: c.PostForm("background"), User: c.PostForm("user"), - InputFidelity: c.PostForm("input_fidelity"), Moderation: c.PostForm("moderation"), + OutputFormat: c.PostForm("output_format"), Complexity: c.PostForm("complexity"), Background: c.PostForm("background"), + User: c.PostForm("user"), InputFidelity: c.PostForm("input_fidelity"), Moderation: c.PostForm("moderation"), } if rawN := strings.TrimSpace(c.PostForm("n")); rawN != "" { n, err := strconv.Atoi(rawN) @@ -89,7 +130,10 @@ func ImageEditHandler(pool *balancer.AccountPool) gin.HandlerFunc { request.Stream = stream } for name, target := range map[string]**int{ - "partial_images": &request.PartialImages, "output_compression": &request.OutputCompression, + "partial_images": &request.PartialImages, + "output_compression": &request.OutputCompression, + "frame_count": &request.FrameCount, + "frame_duration_ms": &request.FrameDurationMS, } { raw := strings.TrimSpace(c.PostForm(name)) if raw == "" { @@ -103,43 +147,232 @@ func ImageEditHandler(pool *balancer.AccountPool) gin.HandlerFunc { *target = &value } - headers := c.Request.MultipartForm.File["image"] - if len(headers) == 0 { - headers = c.Request.MultipartForm.File["image[]"] + inputs, err := collectMultipartImageInputs(c.Request.MultipartForm) + if err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", err.Error()) + return + } + if len(inputs) == 0 { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "image is required") + return } - inputs := make([]imageInput, 0, len(headers)) - for index, header := range headers { + handleImageRequest(c, pool, request, inputs) + } +} + +func collectMultipartImageInputs(form *multipart.Form) ([]imageInputSpec, error) { + if form == nil { + return nil, nil + } + keys := []string{"image", "image[]", "images", "images[]", "markup"} + var inputs []imageInputSpec + for _, key := range keys { + for _, header := range form.File[key] { file, err := header.Open() if err != nil { - writeOpenAIError(c, http.StatusBadRequest, "invalid_request", err.Error()) - return + return nil, err } data, readErr := io.ReadAll(file) file.Close() if readErr != nil { - writeOpenAIError(c, http.StatusBadRequest, "invalid_request", readErr.Error()) - return + return nil, readErr } filename := strings.TrimSpace(header.Filename) if filename == "" { - filename = fmt.Sprintf("image_%d.bin", index) + filename = fmt.Sprintf("image_%d.bin", len(inputs)) } - inputs = append(inputs, imageInput{data: data, filename: filename}) + inputs = append(inputs, imageInputSpec{data: data, filename: filename}) } - if len(inputs) == 0 { - writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "image is required") - return + for _, val := range form.Value[key] { + val = strings.TrimSpace(val) + if val == "" { + continue + } + inputs = append(inputs, imageInputSpec{ref: val}) + } + } + return inputs, nil +} + +func parseJSONImageInputs(fields ...json.RawMessage) ([]imageInputSpec, error) { + var inputs []imageInputSpec + for _, raw := range fields { + trimmed := bytes.TrimSpace(raw) + if len(trimmed) == 0 || string(trimmed) == "null" { + continue + } + if trimmed[0] == '[' { + var items []json.RawMessage + if err := json.Unmarshal(trimmed, &items); err != nil { + return nil, fmt.Errorf("images 必须是数组: %w", err) + } + for _, item := range items { + spec, ok, err := parseSingleJSONImageInput(item) + if err != nil { + return nil, err + } + if ok { + inputs = append(inputs, spec) + } + } + continue + } + spec, ok, err := parseSingleJSONImageInput(trimmed) + if err != nil { + return nil, err + } + if ok { + inputs = append(inputs, spec) } - handleImageRequest(c, pool, request, inputs) } + return inputs, nil } -func handleImageRequest(c *gin.Context, pool *balancer.AccountPool, request ImageGenerationRequest, inputs []imageInput) { +func parseSingleJSONImageInput(raw json.RawMessage) (imageInputSpec, bool, error) { + trimmed := bytes.TrimSpace(raw) + if len(trimmed) == 0 || string(trimmed) == "null" { + return imageInputSpec{}, false, nil + } + var str string + if json.Unmarshal(trimmed, &str) == nil { + str = strings.TrimSpace(str) + if str == "" { + return imageInputSpec{}, false, nil + } + return imageInputSpec{ref: str}, true, nil + } + var obj map[string]json.RawMessage + if err := json.Unmarshal(trimmed, &obj); err != nil { + return imageInputSpec{}, false, fmt.Errorf("输入图片格式无效,应为 URL、data URI、file_id 或图片对象") + } + var spec imageInputSpec + _ = json.Unmarshal(obj["file_id"], &spec.fileID) + _ = json.Unmarshal(obj["filename"], &spec.filename) + _ = json.Unmarshal(obj["mime_type"], &spec.mimeType) + var b64 string + _ = json.Unmarshal(obj["b64_json"], &b64) + if b64 == "" { + _ = json.Unmarshal(obj["data"], &b64) + } + if b64 != "" { + spec.ref = b64 + } + if spec.ref == "" && len(obj["image_url"]) > 0 { + var s string + if json.Unmarshal(obj["image_url"], &s) == nil { + spec.ref = s + } else { + var nested struct { + URL string `json:"url"` + } + _ = json.Unmarshal(obj["image_url"], &nested) + spec.ref = nested.URL + } + } + if spec.ref == "" { + _ = json.Unmarshal(obj["url"], &spec.ref) + } + if spec.ref == "" { + _ = json.Unmarshal(obj["markup"], &spec.ref) + } + spec.fileID = strings.TrimSpace(spec.fileID) + spec.ref = strings.TrimSpace(spec.ref) + if spec.fileID == "" && spec.ref == "" { + return imageInputSpec{}, false, nil + } + return spec, true, nil +} + +func resolveImageInputs(ctx context.Context, client *gemini.Client, specs []imageInputSpec) ([]gemini.FileData, error) { + files := make([]gemini.FileData, 0, len(specs)) + for idx, spec := range specs { + if len(spec.data) > 0 { + filename := strings.TrimSpace(spec.filename) + if filename == "" { + filename = fmt.Sprintf("image_%d%s", idx, mimeTypeToExt(cmp.Or(spec.mimeType, http.DetectContentType(spec.data)))) + } + files = append(files, gemini.FileData{Data: spec.data, FileName: filename, MimeType: spec.mimeType}) + continue + } + if spec.fileID != "" { + file, err := storedFileData(ctx, spec.fileID) + if err != nil { + return nil, err + } + if spec.mimeType != "" { + file.MimeType = spec.mimeType + } + files = append(files, *file) + continue + } + ref := strings.TrimSpace(spec.ref) + if ref == "" { + continue + } + if id, ok := storedFileID(ref); ok && (strings.HasPrefix(ref, "files/") || strings.Contains(ref, "/v1beta/files/") || strings.Contains(ref, "/v1/files/")) { + file, err := storedFileData(ctx, id) + if err != nil { + return nil, err + } + files = append(files, *file) + continue + } + if strings.HasPrefix(ref, "http://") || strings.HasPrefix(ref, "https://") { + data, err := fetchRemoteMedia(ctx, client, ref) + if err != nil { + return nil, fmt.Errorf("下载远程图片失败: %w", err) + } + mimeType := cmp.Or(spec.mimeType, strings.Split(http.DetectContentType(data), ";")[0]) + filename := cmp.Or(strings.TrimSpace(spec.filename), fmt.Sprintf("image_%d%s", idx, mimeTypeToExt(mimeType))) + files = append(files, gemini.FileData{Data: data, FileName: filename, MimeType: mimeType}) + continue + } + if mimeType, rawData, ok := splitDataURL(ref); ok { + data, err := decodeBase64(rawData) + if err != nil { + return nil, fmt.Errorf("图片 base64 解码失败: %w", err) + } + mimeType = cmp.Or(spec.mimeType, mimeType) + filename := cmp.Or(strings.TrimSpace(spec.filename), fmt.Sprintf("image_%d%s", idx, mimeTypeToExt(mimeType))) + files = append(files, gemini.FileData{Data: data, FileName: filename, MimeType: mimeType}) + continue + } + if strings.HasPrefix(ref, "file-") || strings.HasPrefix(ref, "file_") { + file, err := storedFileData(ctx, ref) + if err != nil { + return nil, err + } + files = append(files, *file) + continue + } + data, err := decodeBase64(ref) + if err == nil && len(data) > 0 { + mimeType := cmp.Or(spec.mimeType, strings.Split(http.DetectContentType(data), ";")[0]) + filename := cmp.Or(strings.TrimSpace(spec.filename), fmt.Sprintf("image_%d%s", idx, mimeTypeToExt(mimeType))) + files = append(files, gemini.FileData{Data: data, FileName: filename, MimeType: mimeType}) + continue + } + if id, ok := storedFileID(ref); ok { + if file, fileErr := storedFileData(ctx, id); fileErr == nil { + files = append(files, *file) + continue + } + } + return nil, fmt.Errorf("无法解析输入图片(支持 URL、data URI、base64 或已上传 file_id)") + } + return files, nil +} + +func handleImageRequest(c *gin.Context, pool *balancer.AccountPool, request ImageGenerationRequest, inputs []imageInputSpec) { logging.FromContext(c.Request.Context()).Begin("images", request.Model, request.Stream, 1, 0) if strings.TrimSpace(request.Prompt) == "" { writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "prompt is required") return } + if len(inputs) > maxInputImages { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", fmt.Sprintf("at most %d input images are supported", maxInputImages)) + return + } aspectRatio, err := resolveImageAspectRatio(request.Size, request.AspectRatio) if err != nil { writeOpenAIError(c, http.StatusBadRequest, "invalid_request", err.Error()) @@ -171,7 +404,11 @@ func handleImageRequest(c *gin.Context, pool *balancer.AccountPool, request Imag writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "response_format must be b64_json or url") return } - setUnsupportedParameters(c, nonEmptyImageParameters(request)) + isGIFModel := false + if resolved, ok := findModel(pool, request.Model); ok && resolved.FormatOption != 0 { + isGIFModel = true + } + setUnsupportedParameters(c, nonEmptyImageParameters(request, isGIFModel)) if !request.Stream { defer startNonstreamKeepalive(c)() @@ -182,10 +419,10 @@ func handleImageRequest(c *gin.Context, pool *balancer.AccountPool, request Imag responseID := fmt.Sprintf("img_%d_%d", time.Now().UnixNano(), index) result, accountID, err := runGeneration( c.Request.Context(), pool, "", sessionContinue, request.Model, responseID, generationMedia{requireImage: true, aspectRatio: aspectRatio}, gemini.ThinkingLow, ToolBridge{}, - func(*gemini.Client, bool) (string, []gemini.FileData, error) { - files := make([]gemini.FileData, 0, len(inputs)) - for _, input := range inputs { - files = append(files, gemini.FileData{Data: input.data, FileName: input.filename}) + func(client *gemini.Client, _ bool) (string, []gemini.FileData, error) { + files, err := resolveImageInputs(c.Request.Context(), client, inputs) + if err != nil { + return "", nil, err } return prompt, files, nil }, nil, nil, @@ -243,10 +480,10 @@ func handleImageRequest(c *gin.Context, pool *balancer.AccountPool, request Imag c.JSON(http.StatusOK, response) } -// resolveImageAspectRatio 解析图片请求的 size 与 aspect_ratio,返回传给上游的宽高比;auto 按未指定处理,格式无效或两者比例矛盾时返回错误 +// resolveImageAspectRatio 解析图片请求的 size 与 aspect_ratio,返回传给上游的宽高比;auto 与 1K/2K/4K 按未指定处理,格式无效或两者比例矛盾时返回错误 func resolveImageAspectRatio(rawSize string, rawAspectRatio string) (string, error) { size := strings.TrimSpace(rawSize) - if strings.EqualFold(size, "auto") { + if strings.EqualFold(size, "auto") || imageResolutionTier(size) { size = "" } aspect := strings.TrimSpace(rawAspectRatio) @@ -303,7 +540,7 @@ func defaultImageModel(pool *balancer.AccountPool) string { return "" } -func nonEmptyImageParameters(request ImageGenerationRequest) []string { +func nonEmptyImageParameters(request ImageGenerationRequest, isGIFModel bool) []string { var result []string if request.Quality != "" { result = append(result, "quality") @@ -314,12 +551,21 @@ func nonEmptyImageParameters(request ImageGenerationRequest) []string { if request.PartialImages != nil { result = append(result, "partial_images") } - if request.OutputFormat != "" { + if request.OutputFormat != "" && !(isGIFModel && strings.EqualFold(strings.TrimSpace(request.OutputFormat), "gif")) { result = append(result, "output_format") } if request.OutputCompression != nil { result = append(result, "output_compression") } + if request.FrameCount != nil { + result = append(result, "frame_count") + } + if request.FrameDurationMS != nil { + result = append(result, "frame_duration_ms") + } + if request.Complexity != "" { + result = append(result, "complexity") + } if request.Background != "" { result = append(result, "background") } diff --git a/internal/adapter/openai_chat.go b/internal/adapter/openai_chat.go index 2377aed..1aa4ff1 100644 --- a/internal/adapter/openai_chat.go +++ b/internal/adapter/openai_chat.go @@ -94,12 +94,22 @@ type ChatRequest struct { N *int `json:"n,omitempty"` WebSearchOptions json.RawMessage `json:"web_search_options,omitempty"` Audio *ChatAudioOptions `json:"audio,omitempty"` + Modalities []string `json:"modalities,omitempty"` + Size string `json:"size,omitempty"` + AspectRatio string `json:"aspect_ratio,omitempty"` + ImageConfig *ChatImageConfig `json:"image_config,omitempty"` ExtraBody ChatExtraBody `json:"extra_body,omitempty"` legacyFunctions bool // TruncateTo 大于 0 时提示词超过这个 token 数就从最早的轮次删起 TruncateTo int `json:"-"` } +// ChatImageConfig 表示部分插件在 Chat Completions 传入的图片尺寸配置 +type ChatImageConfig struct { + AspectRatio string `json:"aspect_ratio,omitempty"` + ImageSize string `json:"image_size,omitempty"` +} + // ChatExtraBody 表示 Gemini OpenAI 兼容层的 extra_body 扩展 type ChatExtraBody struct { Google struct { @@ -187,13 +197,14 @@ func ChatCompletionHandler(pool *balancer.AccountPool) gin.HandlerFunc { responseID := fmt.Sprintf("chatcmpl_%d", time.Now().UnixNano()) created := time.Now().Unix() + chatMedia := generationMedia{aspectRatio: chatImageAspectRatio(request)} generate := func(choice int, onEvent func(gemini.Event) error, projection *streamProjection) (generationResult, error) { key, keyPolicy := sessionKey, policy if choice > 0 { key, keyPolicy = "", sessionCreate } result, accountID, err := runGeneration( - c.Request.Context(), pool, key, keyPolicy, request.Model, responseID, generationMedia{}, thinkingLevel, bridge, + c.Request.Context(), pool, key, keyPolicy, request.Model, responseID, chatMedia, thinkingLevel, bridge, func(client *gemini.Client, continuation bool) (string, []gemini.FileData, error) { return buildOpenAIChatPrompt(c, client, request, continuation, bridge.declared(continuation && isHistoryKey(key))) }, @@ -807,6 +818,23 @@ func unsupportedChatParameters(request ChatRequest) []string { return fields } +// chatImageAspectRatio 从 Chat 请求的 image_config.aspect_ratio、aspect_ratio 或 size 提取可用宽高比,未识别或挡位值按未指定处理 +func chatImageAspectRatio(request ChatRequest) string { + candidates := []string{} + if request.ImageConfig != nil { + candidates = append(candidates, request.ImageConfig.AspectRatio) + } + candidates = append(candidates, request.AspectRatio, request.Size) + for _, raw := range candidates { + if norm := normalizeGeminiAspectRatio(raw); norm != "" { + if _, canonical, ok := gemini.ParseAspectRatio(norm, false); ok { + return canonical + } + } + } + return "" +} + func openAIToolCallResponses(calls []ToolCall, bridge ToolBridge) []gin.H { result := make([]gin.H, 0, len(calls)) for _, call := range calls { diff --git a/internal/adapter/responses_handler.go b/internal/adapter/responses_handler.go index 5915072..f11e1da 100644 --- a/internal/adapter/responses_handler.go +++ b/internal/adapter/responses_handler.go @@ -643,14 +643,18 @@ func responseImageGenerationItems(output CandidateOutput, responseID string) []g if media.Type != gemini.MediaGeneratedImage { continue } - _, data, ok := splitDataURL(media.URL) + mimeType, data, ok := splitDataURL(media.URL) if !ok { continue } - items = append(items, gin.H{ + item := gin.H{ "id": fmt.Sprintf("ig_%s_%d", responseID, len(items)), "type": "image_generation_call", "status": "completed", "result": data, - }) + } + if format, ok := strings.CutPrefix(strings.ToLower(mimeType), "image/"); ok && format != "" { + item["output_format"] = format + } + items = append(items, item) } return items } diff --git a/internal/adapter/stream.go b/internal/adapter/stream.go index 89f949f..c61c63b 100644 --- a/internal/adapter/stream.go +++ b/internal/adapter/stream.go @@ -99,7 +99,7 @@ type streamProjection struct { func newStreamProjection(bridge ToolBridge, includeThought bool) *streamProjection { disallowHostedTools := bridge.disallowsHostedTools() - holdAll := len(bridge.JSONSchema) > 0 || len(bridge.Enum) > 0 || bridge.WebSearch || bridge.RequireImageGeneration || bridge.RequireCodeExecution || bridge.RequireHostedTool || disallowHostedTools || fakeStream.Load() + holdAll := len(bridge.JSONSchema) > 0 || len(bridge.Enum) > 0 || bridge.WebSearch || bridge.RequireImageGeneration || bridge.RequireCodeExecution || bridge.RequireHostedTool || bridge.ImageOnly || disallowHostedTools || fakeStream.Load() return &streamProjection{ bridge: bridge, bufferText: len(bridge.Definitions) > 0 || holdAll, diff --git a/internal/adapter/tool_bridge.go b/internal/adapter/tool_bridge.go index fdce619..55ae761 100644 --- a/internal/adapter/tool_bridge.go +++ b/internal/adapter/tool_bridge.go @@ -47,6 +47,8 @@ type ToolBridge struct { RequireWebSearch bool RequireImageGeneration bool RequireHostedTool bool + // ImageOnly 表示请求显式只要图片模态(如 Gemini responseModalities=["IMAGE"]),产出图片时省略前导纯文本 + ImageOnly bool // AspectRatio 为生图请求的宽高比 AspectRatio string // Enum 为 text/x.enum 响应可选的取值 diff --git a/internal/gemini/channel.go b/internal/gemini/channel.go index 2f7a333..478408e 100644 --- a/internal/gemini/channel.go +++ b/internal/gemini/channel.go @@ -59,7 +59,10 @@ type channel struct { aid int ended bool // responded 表示已取得第一个长轮询的响应头 - responded bool + responded bool + binaryProto bool + ready chan struct{} + readyOnce sync.Once } // streamRecord 是生成流中的一条记录:生成载荷、Bard 错误码、上游状态错误或本轮收尾 @@ -70,12 +73,16 @@ type streamRecord struct { end bool } -// channelHeaders 返回握手时与会话绑定的 $httpHeaders:登录会话带 SAPISIDHASH 授权与账号序号,扩展头写成 base64 protobuf,消息按 JSPB 编码 -func (c *Client) channelHeaders(bootstrap Bootstrap, modelHeader []byte, requestID string) string { +// channelHeaders 返回握手时与会话绑定的 $httpHeaders:登录会话带 SAPISIDHASH 授权与账号序号,扩展头写成 base64 protobuf,binaryProto 为真时使用 Chrome 的 application/x-protobuf 线格式 +func (c *Client) channelHeaders(bootstrap Bootstrap, modelHeader []byte, requestID string, binaryProto bool) string { var lines []string if !c.guest { lines = append(lines, "Authorization:"+c.sapisidHash(time.Now()), "X-Goog-AuthUser:"+strconv.Itoa(c.authUser)) } + contentType := "application/json+protobuf" + if binaryProto { + contentType = "application/x-protobuf" + } encode := base64.StdEncoding.EncodeToString lines = append(lines, "X-Goog-Api-Key:"+bootstrap.APIKey, @@ -84,7 +91,7 @@ func (c *Client) channelHeaders(bootstrap Bootstrap, modelHeader []byte, request "x-goog-ext-73010989-bin:"+encode(encodeJSPB([]any{0})), "x-goog-ext-525005358-bin:"+encode(encodeJSPB([]any{requestID, 1})), "x-goog-ext-73010990-bin:"+encode(encodeJSPB([]any{0, 0, 0})), - "X-WebChannel-Content-Type:application/json+protobuf", + "X-WebChannel-Content-Type:"+contentType, ) return strings.Join(lines, "\r\n") + "\r\n" } @@ -102,7 +109,15 @@ func (c *Client) sapisidHash(now time.Time) string { return "SAPISIDHASH " + hash("SAPISID") + " SAPISID1PHASH " + hash("__Secure-1PAPISID") + " SAPISID3PHASH " + hash("__Secure-3PAPISID") } -// encodeJSPB 把 JSPB 数组按下标 n 对应字段 n+1 编码为 protobuf:null 省略,整数写 varint,字符串写长度字段,整数切片写 packed 字段,其余数组写嵌套消息 +// repeatedMessages 表示 JSPB 中同字段编号的重复嵌套消息,按 JSON 编码为普通二维数组,按 protobuf 编码时逐项写出同字段 BytesType 标签 +type repeatedMessages [][]any + +// MarshalJSON 把 repeatedMessages 按 JSON 编码为二维数组 +func (r repeatedMessages) MarshalJSON() ([]byte, error) { + return json.Marshal([][]any(r)) +} + +// encodeJSPB 把 JSPB 数组按下标 n 对应字段 n+1 编码为 protobuf:null 省略,整数写 varint,字符串写长度字段,整数切片写 packed 字段,repeatedMessages 写重复消息字段,其余数组写嵌套消息 func encodeJSPB(values []any) []byte { var out []byte for index, value := range values { @@ -127,6 +142,10 @@ func encodeJSPB(values []any) []byte { nested[position] = element } out = protowire.AppendBytes(protowire.AppendTag(out, number, protowire.BytesType), encodeJSPB(nested)) + case repeatedMessages: + for _, element := range item { + out = protowire.AppendBytes(protowire.AppendTag(out, number, protowire.BytesType), encodeJSPB(element)) + } case []any: out = protowire.AppendBytes(protowire.AppendTag(out, number, protowire.BytesType), encodeJSPB(item)) default: @@ -194,7 +213,7 @@ func (c *Client) channelRequest(ctx context.Context, method, query, body string, } // openChannel 以握手请求建立 processSession 会话,headers 为与会话绑定的 $httpHeaders -func (c *Client) openChannel(ctx context.Context, headers string) (*channel, error) { +func (c *Client) openChannel(ctx context.Context, headers string, binaryProto bool) (*channel, error) { rid := rand.IntN(100000) query := "VER=8&RID=" + strconv.Itoa(rid) + "&CVER=22&X-HTTP-Session-Id=gsessionid&%24httpHeaders=" + channelEscape(headers) + "&zx=" + channelZX() + "&t=1" resp, err := c.channelRequest(ctx, http.MethodPost, query, "count=0", false) @@ -214,19 +233,30 @@ func (c *Client) openChannel(ctx context.Context, headers string) (*channel, err if match == nil || gsessionid == "" { return nil, retryableProtocolError(fmt.Sprintf("建立生成会话时官网没有返回会话: %s", body), nil) } - return &channel{client: c, gsessionid: gsessionid, sid: string(match[1]), rid: rid + 1}, nil + return &channel{client: c, gsessionid: gsessionid, sid: string(match[1]), rid: rid + 1, binaryProto: binaryProto, ready: make(chan struct{})}, nil } -// send 在一个上行请求中依次发送 JSPB 编码的 messages +// send 在一个上行请求中依次发送编码后的 messages func (ch *channel) send(ctx context.Context, messages ...any) error { ch.mu.Lock() var body strings.Builder body.WriteString("count=" + strconv.Itoa(len(messages)) + "&ofs=" + strconv.Itoa(ch.ofs)) for index, message := range messages { - encoded, err := pageJSON(message) - if err != nil { - ch.mu.Unlock() - return fmt.Errorf("encode processSession message: %w", err) + var encoded string + if ch.binaryProto { + values, ok := message.([]any) + if !ok { + ch.mu.Unlock() + return fmt.Errorf("encode processSession binary message: unexpected %T", message) + } + encoded = base64.StdEncoding.EncodeToString(encodeJSPB(values)) + } else { + var err error + encoded, err = pageJSON(message) + if err != nil { + ch.mu.Unlock() + return fmt.Errorf("encode processSession message: %w", err) + } } body.WriteString("&req" + strconv.Itoa(index) + "___data__=" + channelEscape(encoded)) } @@ -300,6 +330,7 @@ func (ch *channel) records(ctx context.Context, trace *logging.Request, yield fu } if !ch.responded { ch.responded = true + ch.readyOnce.Do(func() { close(ch.ready) }) trace.UpstreamResponse(resp.StatusCode) } done, err := ch.readFrames(ctx, tracedReader{reader: resp.Body, trace: trace}, trace, yield) @@ -346,6 +377,9 @@ func (ch *channel) frame(ctx context.Context, raw json.RawMessage, trace *loggin } if envelope, ok := content.(map[string]any); ok { status, _ := envelope["__sm__"].(map[string]any) + if encoded, ok := status["status"].(string); ok { + return false, yield(channelBinaryStatus(encoded)) + } return false, yield(channelStatus(status["status"])) } values, _ := content.([]any) @@ -355,6 +389,14 @@ func (ch *channel) frame(ctx context.Context, raw json.RawMessage, trace *loggin return false, nil case "close": return true, nil + default: + if ch.binaryProto && tag != "" { + rawProto, err := base64.StdEncoding.DecodeString(tag) + if err != nil { + return false, fmt.Errorf("解析二进制官网回答失败: %w", err) + } + return ch.handleBinaryFrame(ctx, rawProto, yield) + } } message, _ := arrayAt(values, 0) if len(message) == 4 && message[1] == nil { diff --git a/internal/gemini/channel_proto.go b/internal/gemini/channel_proto.go new file mode 100644 index 0000000..5a4907a --- /dev/null +++ b/internal/gemini/channel_proto.go @@ -0,0 +1,521 @@ +package gemini + +import ( + "context" + "encoding/base64" + "fmt" + "strings" + "unicode/utf8" + + "google.golang.org/protobuf/encoding/protowire" +) + +type protoField struct { + num protowire.Number + typ protowire.Type + varint uint64 + bytes []byte +} + +func parseProtoFields(data []byte) ([]protoField, bool) { + var fields []protoField + for len(data) > 0 { + num, typ, n := protowire.ConsumeTag(data) + if n < 0 { + return nil, false + } + data = data[n:] + switch typ { + case protowire.VarintType: + val, m := protowire.ConsumeVarint(data) + if m < 0 { + return nil, false + } + fields = append(fields, protoField{num: num, typ: typ, varint: val}) + data = data[m:] + case protowire.BytesType: + val, m := protowire.ConsumeBytes(data) + if m < 0 { + return nil, false + } + fields = append(fields, protoField{num: num, typ: typ, bytes: val}) + data = data[m:] + default: + m := protowire.ConsumeFieldValue(num, typ, data) + if m < 0 { + return nil, false + } + data = data[m:] + } + } + return fields, true +} + +func protoFirstString(data []byte) string { + if fields, ok := parseProtoFields(data); ok { + for _, field := range fields { + if field.num == 1 && field.typ == protowire.BytesType && utf8.Valid(field.bytes) { + return string(field.bytes) + } + } + } + if utf8.Valid(data) { + return string(data) + } + return "" +} + +func protoNestedInt(data []byte, path ...protowire.Number) (uint64, bool) { + cur := data + for i, target := range path { + fields, ok := parseProtoFields(cur) + if !ok { + return 0, false + } + last := i == len(path)-1 + var matched *protoField + for idx := range fields { + if fields[idx].num == target { + matched = &fields[idx] + break + } + } + if matched == nil { + return 0, false + } + if last { + if matched.typ == protowire.VarintType { + return matched.varint, true + } + if matched.typ == protowire.BytesType { + if val, m := protowire.ConsumeVarint(matched.bytes); m > 0 { + return val, true + } + } + return 0, false + } + if matched.typ != protowire.BytesType { + return 0, false + } + cur = matched.bytes + } + return 0, false +} + +func (ch *channel) handleBinaryFrame(ctx context.Context, raw []byte, yield func(streamRecord) error) (bool, error) { + fields, ok := parseProtoFields(raw) + if !ok { + return false, fmt.Errorf("解析二进制官网回答失败: 无效的 protobuf 帧") + } + var endFrame bool + var listData [][]byte + for _, field := range fields { + switch field.num { + case 2: + if field.typ == protowire.BytesType { + listData = append(listData, field.bytes) + } + case 4: + endFrame = true + } + } + for _, listBytes := range listData { + listFields, ok := parseProtoFields(listBytes) + if !ok { + continue + } + for _, item := range listFields { + if item.num != 7 || item.typ != protowire.BytesType { + continue + } + for _, rootBytes := range extractBinaryRoots(item.bytes) { + root, hasHeartbeat, heartbeatNum := decodeBinaryRoot(rootBytes) + if hasHeartbeat { + if err := yield(streamRecord{payload: []any{map[string]any{"37": []any{float64(heartbeatNum)}}}}); err != nil { + return false, err + } + } + if root != nil { + if err := yield(streamRecord{payload: root}); err != nil { + return false, err + } + } + switch token, ok := jspbString(root, 25); { + case ok && token == channelCommitted: + if err := ch.end(ctx); err != nil { + return false, err + } + case ok: + return true, yield(streamRecord{end: true}) + } + } + } + } + if endFrame { + return true, yield(streamRecord{end: true}) + } + return false, nil +} + +func extractBinaryRoots(f7Bytes []byte) [][]byte { + fields, ok := parseProtoFields(f7Bytes) + if !ok { + return nil + } + var roots [][]byte + for _, f := range fields { + if f.typ != protowire.BytesType { + continue + } + switch f.num { + case 1: + if root := extractBinaryRootFromItem(f.bytes); len(root) > 0 { + roots = append(roots, root) + } + case 4: + innerFields, ok := parseProtoFields(f.bytes) + if !ok { + continue + } + for _, inf := range innerFields { + if inf.num == 4 && inf.typ == protowire.BytesType && len(inf.bytes) > 0 { + roots = append(roots, inf.bytes) + break + } + } + } + } + return roots +} + +func extractBinaryRootFromItem(itemBytes []byte) []byte { + itemFields, ok := parseProtoFields(itemBytes) + if !ok { + return nil + } + for _, f := range itemFields { + if f.num != 4 || f.typ != protowire.BytesType { + continue + } + innerFields, ok := parseProtoFields(f.bytes) + if !ok { + continue + } + for _, inf := range innerFields { + if inf.num == 4 && inf.typ == protowire.BytesType { + return inf.bytes + } + } + } + return nil +} + +func decodeBinaryRoot(data []byte) (root []any, hasHeartbeat bool, heartbeatNum uint64) { + fields, ok := parseProtoFields(data) + if !ok { + return nil, false, 0 + } + root = make([]any, 53) + var candidates []any + hasContent := false + for _, field := range fields { + switch field.num { + case 2: + if field.typ != protowire.BytesType { + continue + } + if session := decodeBinarySession(field.bytes); session != nil { + root[1] = session + hasContent = true + } + case 5: + if field.typ != protowire.BytesType { + continue + } + if candidate := decodeBinaryCandidate(field.bytes); candidate != nil { + candidates = append(candidates, candidate) + hasContent = true + } + case 7: + if field.typ != protowire.BytesType { + continue + } + if progress := decodeBinaryProgress(field.bytes); progress != nil { + root[6] = progress + hasContent = true + } + case 11: + if field.typ != protowire.BytesType { + continue + } + if s := protoFirstString(field.bytes); s != "" { + root[10] = []any{s} + hasContent = true + } + case 21: + if field.typ != protowire.BytesType { + continue + } + if s := protoFirstString(field.bytes); s != "" { + root[20] = []any{s} + hasContent = true + } + case 26: + if field.typ == protowire.BytesType && utf8.Valid(field.bytes) { + root[25] = string(field.bytes) + hasContent = true + } + case 32: + if field.typ == protowire.VarintType { + root[31] = float64(field.varint) + hasContent = true + } + case 38: + if field.typ == protowire.VarintType { + hasHeartbeat, heartbeatNum = true, field.varint + } else if field.typ == protowire.BytesType { + if n, ok := protoNestedInt(field.bytes, 1); ok { + hasHeartbeat, heartbeatNum = true, n + } + } + case 40: + if field.typ == protowire.BytesType && utf8.Valid(field.bytes) { + root[39] = string(field.bytes) + hasContent = true + } + case 43: + if field.typ == protowire.BytesType && utf8.Valid(field.bytes) { + root[42] = string(field.bytes) + hasContent = true + } + case 53: + if field.typ != protowire.BytesType { + continue + } + if notice := decodeBinaryLimitNotice(field.bytes); notice != nil { + root[52] = notice + hasContent = true + } + } + } + if len(candidates) > 0 { + root[4] = candidates + } + if !hasContent { + return nil, hasHeartbeat, heartbeatNum + } + return root, hasHeartbeat, heartbeatNum +} + +func decodeBinarySession(data []byte) []any { + fields, ok := parseProtoFields(data) + if !ok { + return nil + } + var cid, rid string + for _, f := range fields { + if f.typ != protowire.BytesType || !utf8.Valid(f.bytes) { + continue + } + switch f.num { + case 1: + cid = string(f.bytes) + case 2: + rid = string(f.bytes) + } + } + if cid == "" && rid == "" { + return nil + } + return []any{cid, rid} +} + +func decodeBinaryCandidate(data []byte) []any { + fields, ok := parseProtoFields(data) + if !ok { + return nil + } + candidate := make([]any, 38) + var texts []any + for _, f := range fields { + switch f.num { + case 1: + if f.typ == protowire.BytesType && utf8.Valid(f.bytes) { + candidate[0] = string(f.bytes) + } + case 2: + if f.typ == protowire.BytesType { + if s := protoFirstString(f.bytes); s != "" { + texts = append(texts, s) + } + } + case 9: + if f.typ == protowire.VarintType { + candidate[8] = []any{float64(f.varint)} + } else if f.typ == protowire.BytesType { + if phase, ok := protoNestedInt(f.bytes, 1); ok { + candidate[8] = []any{float64(phase)} + } + } + case 38: + if f.typ == protowire.BytesType { + if sub, ok := parseProtoFields(f.bytes); ok { + for _, sf := range sub { + if sf.num == 1 && sf.typ == protowire.BytesType { + if thought := protoFirstString(sf.bytes); thought != "" { + candidate[37] = []any{[]any{thought}} + break + } + } + } + } + } + } + } + if len(texts) > 0 { + candidate[1] = texts + } + return candidate +} + +func decodeBinaryProgress(data []byte) []any { + fields, ok := parseProtoFields(data) + if !ok { + return nil + } + raw := make([]any, 13) + set := false + for _, f := range fields { + switch f.num { + case 2: + if f.typ != protowire.BytesType { + continue + } + sub, ok := parseProtoFields(f.bytes) + if !ok { + continue + } + entry := make([]any, 4) + for _, sf := range sub { + switch sf.num { + case 1: + if sf.typ == protowire.BytesType && utf8.Valid(sf.bytes) { + entry[0] = string(sf.bytes) + } + case 3: + if sf.typ == protowire.VarintType { + entry[2] = float64(sf.varint) + } + case 4: + if sf.typ == protowire.BytesType { + if cat, ok := protoNestedInt(sf.bytes, 2, 8, 1); ok { + cSlice := make([]any, 8) + cSlice[7] = []any{float64(cat)} + entry[3] = []any{nil, cSlice} + } + } + } + } + raw[1] = entry + set = true + case 13: + if f.typ == protowire.BytesType { + if task, ok := protoNestedInt(f.bytes, 5, 1); ok { + tSlice := make([]any, 5) + tSlice[4] = []any{float64(task)} + raw[12] = tSlice + set = true + } + } + } + } + if !set { + return nil + } + return raw +} + +func decodeBinaryLimitNotice(data []byte) []any { + fields, ok := parseProtoFields(data) + if !ok { + return nil + } + var title, detail string + for _, f := range fields { + if f.typ != protowire.BytesType { + continue + } + switch f.num { + case 1: + title = protoFirstString(f.bytes) + case 2: + detail = protoFirstString(f.bytes) + } + } + if title == "" && detail == "" { + return nil + } + return []any{[]any{title}, []any{detail}} +} + +func channelBinaryStatus(encoded string) streamRecord { + raw, err := base64.StdEncoding.DecodeString(encoded) + if err != nil { + raw, err = base64.RawStdEncoding.DecodeString(encoded) + } + if err != nil { + return streamRecord{err: retryableProtocolError(fmt.Sprintf("解析生成会话错误状态失败: %v", err), nil)} + } + fields, ok := parseProtoFields(raw) + if !ok { + return streamRecord{err: retryableProtocolError("解析生成会话错误状态失败: 无效 protobuf", nil)} + } + var code uint64 + var message string + for _, f := range fields { + switch f.num { + case 1: + if f.typ == protowire.VarintType { + code = f.varint + } + case 2: + if f.typ == protowire.BytesType && utf8.Valid(f.bytes) { + message = string(f.bytes) + } + case 3: + if f.typ != protowire.BytesType { + continue + } + detailFields, ok := parseProtoFields(f.bytes) + if !ok { + continue + } + var typeURL string + var valueBytes []byte + for _, df := range detailFields { + switch df.num { + case 1: + if df.typ == protowire.BytesType { + typeURL = string(df.bytes) + } + case 2: + if df.typ == protowire.BytesType { + valueBytes = df.bytes + } + } + } + if len(valueBytes) > 0 && (typeURL == "" || strings.Contains(typeURL, "Bard")) { + if bardCode, ok := protoNestedInt(valueBytes, 1); ok && bardCode > 0 { + return streamRecord{bardCode: int(bardCode)} + } + } + } + } + if code == 16 { + return streamRecord{err: &ProtocolError{ + HTTPStatus: 401, Code: 401, Retryable: true, Cause: ErrSignedOut, + Message: fmt.Sprintf("生成会话显示未登录(状态 16): %s", message), + }} + } + return streamRecord{err: retryableProtocolError(fmt.Sprintf("生成会话返回错误状态 %d: %s", code, message), nil)} +} diff --git a/internal/gemini/client.go b/internal/gemini/client.go index 54d756b..21fd812 100644 --- a/internal/gemini/client.go +++ b/internal/gemini/client.go @@ -400,14 +400,26 @@ func (c *Client) init(ctx context.Context, allowRefresh bool) error { // Stream 执行一次生成并只输出规范事件,Deep Research 按官网计划、确认与报告流程执行 func (c *Client) Stream(ctx context.Context, request GenerateRequest, emit func(Event) error) error { if bootstrap, err := c.bootstrapSnapshot(); err == nil { - if model, err := c.resolveRequestModel(bootstrap.Catalog, request.Model); err == nil && model.Feature == FeatureDeepResearch { - return c.deepResearch(ctx, request, model, emit) + if model, err := c.resolveRequestModel(bootstrap.Catalog, request.Model); err == nil { + if model.Feature == FeatureDeepResearch { + return c.deepResearch(ctx, request, model, emit) + } } } return c.stream(ctx, request, emit, true) } +// PromptRequestsGIF 判断普通对话提示词是否明确要求生成 GIF 或动图,这类请求需走持久会话以支持官网视频/动图模型后台轮询 +func PromptRequestsGIF(prompt string) bool { + lower := strings.ToLower(prompt) + return strings.Contains(lower, "gif") || + strings.Contains(prompt, "动图") || + strings.Contains(prompt, "动态图") || + strings.Contains(lower, "animated") +} + func (c *Client) stream(ctx context.Context, request GenerateRequest, emit func(Event) error, allowRefresh bool) error { + initialCID := request.Conversation.Snapshot().CID version := c.cookieVersion.Load() bootstrap, err := c.bootstrapSnapshot() if err != nil { @@ -422,10 +434,13 @@ func (c *Client) stream(ctx context.Context, request GenerateRequest, emit func( if model.Feature != 0 { request.Feature = model.Feature } + if model.FormatOption != 0 { + request.FormatOption = model.FormatOption + } request.Gem = model.Gem - request.tools = bootstrap.Catalog.toolSelection(request.Feature, request.AspectRatio) + request.tools = bootstrap.Catalog.toolSelection(request.Feature, request.AspectRatio, request.FormatOption) request.personalIntelligence = bootstrap.Catalog.personalIntelligence - temporaryChat := c.TemporaryChats() && !request.Feature.savedChatOnly() && !request.ClientTools + temporaryChat := c.TemporaryChats() && !request.Feature.savedChatOnly() && request.FormatOption == 0 && !request.ClientTools && !(request.Feature == 0 && PromptRequestsGIF(request.Prompt)) if request.Conversation.Snapshot().Saved { temporaryChat = false } @@ -540,17 +555,28 @@ func (c *Client) stream(ctx context.Context, request GenerateRequest, emit func( return err } trace.SetStage("等待官网响应") - session, err := c.openChannel(streamCtx, c.channelHeaders(bootstrap, modelHeader, streamRequestID)) + binaryProto := request.FormatOption != 0 + session, err := c.openChannel(streamCtx, c.channelHeaders(bootstrap, modelHeader, streamRequestID, binaryProto), binaryProto) if err != nil { return failed(err) } pollCtx, stopPoll := context.WithCancelCause(streamCtx) defer stopPoll(nil) go func() { + select { + case <-session.ready: + case <-time.After(1500 * time.Millisecond): + case <-streamCtx.Done(): + return + } err := session.send(streamCtx, []any{[]any{[]any{1, model.Hash, bootstrap.Language, streamRequestID}, 0, nil, nil, nil, nil, nil, []any{nil, nil, nil, nil, []any{inner, nil, nil, 1}}}}, - []any{nil, []any{1, nil, nil, nil, nil, nil, nil, nil, []any{request.Prompt}}}, ) + if err == nil { + err = session.send(streamCtx, + []any{nil, []any{1, nil, nil, nil, nil, nil, nil, nil, []any{request.Prompt}}}, + ) + } if err == nil && taskTerms { err = c.acceptTaskTerms(ctx, bootstrap, model, request.ThinkingLevel) } @@ -619,13 +645,26 @@ func (c *Client) stream(ctx context.Context, request GenerateRequest, emit func( } } } + cleanupFailedChat := func() { + if !temporaryChat && c.TemporaryChats() && initialCID == "" { + if cid := decodeState.Snapshot().CID; cid != "" { + go func(cid string, mode int, variant string, level ThinkingLevel) { + cleanupCtx, cancel := context.WithTimeout(context.Background(), stopTimeout) + defer cancel() + _ = c.DeleteConversation(cleanupCtx, cid, mode, variant, level) + }(cid, model.Mode, model.Variant, request.ThinkingLevel) + } + } + } if err != nil { + cleanupFailedChat() if allowRefresh && !guard.Emitted() && renewable(err) && c.refresh != nil { return c.restream(ctx, version, request, emit) } return err } if err := guard.Complete(); err != nil { + cleanupFailedChat() return err } if request.Conversation != nil { diff --git a/internal/gemini/cookies.go b/internal/gemini/cookies.go index bdbfadc..1290970 100644 --- a/internal/gemini/cookies.go +++ b/internal/gemini/cookies.go @@ -110,6 +110,9 @@ func normalizeCookie(cookie Cookie, requestHost string) Cookie { if cookie.Domain == "" { cookie.Domain = strings.ToLower(requestHost) } + if cookie.Domain == ".google.com" && (cookie.Name == "OSID" || cookie.Name == "__Secure-OSID" || strings.HasPrefix(cookie.Name, "__Host-")) { + cookie.Domain = strings.ToLower(requestHost) + } if cookie.Path == "" { cookie.Path = "/" } diff --git a/internal/gemini/decoder.go b/internal/gemini/decoder.go index 5ac6912..d48d897 100644 --- a/internal/gemini/decoder.go +++ b/internal/gemini/decoder.go @@ -43,6 +43,8 @@ type FrameDecoder struct { sawEnd bool // background 表示生成流以后台生成记录或运行中的 Task 状态结束,成品由 hNvQHb 读取 background bool + // videoBackground 表示生成流已收到 video_generation 后台进度,即使主候选伴随拒答文字先标完成,未收到媒体前仍需进入 hNvQHb 轮询 + videoBackground bool // awaitIncomplete 表示生成流没有完成的候选时按后台生成处理,用于 Deep Research 计划轮 awaitIncomplete bool // continuedCID 是本轮续接的网页会话 ID,新会话为空 @@ -102,7 +104,7 @@ func (d *FrameDecoder) Decode(records func(yield func(streamRecord) error) error return emit(Event{Kind: EventError, Err: protocolErr, FinishReason: FinishError}) case record.end: d.sawEnd = true - if (d.background || d.awaitIncomplete) && !d.sawComplete && !d.sawError { + if ((d.background || d.awaitIncomplete) && !d.sawComplete || d.videoBackground && len(d.media) == 0) && !d.sawError { d.background = true return nil } @@ -219,6 +221,7 @@ func (d *FrameDecoder) reset() { d.sawError = false d.sawEnd = false d.background = false + d.videoBackground = false } // conversationLostError 返回续接的网页会话已失效的 409 错误 @@ -311,6 +314,7 @@ func (d *FrameDecoder) decodeImageProgress(payload []any, emit func(Event) error status, _ := intAt(raw, 1, 2) if tool == "video_generation" { d.background = true + d.videoBackground = true } if task, ok := intAt(raw, 12, 4, 0); ok { d.background = task == 4 @@ -447,7 +451,7 @@ func trimTranscriptEnd(text string) string { // visibleContent 把候选正文原文 raw 转为输出的正文与代码块,返回正文、代码块与引用标记指向的网页来源,代码块偏移为它在正文中的 rune 位置 func visibleContent(candidate []any, raw string) (string, []codeSnapshot, []Citation) { - raw = stripFollowUps(expandImageResults(candidate, renderWidgets(candidate, stripContentCards(candidate, raw)))) + raw = stripTaskImageTags(candidate, stripFollowUps(expandImageResults(candidate, renderWidgets(candidate, stripContentCards(candidate, raw))))) tables := citationTables(candidate) text, codes := parseStructuredContent(markCitations(restoreAutolinks(expandDocuments(candidate, stripChameleon(raw))), tables)) text = trimTranscriptEnd(text) @@ -512,6 +516,11 @@ func (d *FrameDecoder) decodeMedia(candidate []any, candidateIndex int, session } } } + if raw, ok := richContentField(candidate, 58); ok { + if err := d.decodeTaskImages(candidate, candidateIndex, raw, emit); err != nil { + return err + } + } if raw, ok := richContentField(candidate, 59); ok { if err := videoQuotaErrorFromRichContent(raw); err != nil { return err @@ -522,6 +531,9 @@ func (d *FrameDecoder) decodeMedia(candidate []any, candidateIndex int, session if err := d.emitGeneratedFile(candidate, candidateIndex, MediaGeneratedVideo, file, placeholder, emit); err != nil { return err } + if err := d.decodeAnimatedImages(candidate, candidateIndex, raw, emit); err != nil { + return err + } } if raw, ok := richContentField(candidate, 86); ok { audio, _ := valueAt(raw, 0, 1) @@ -575,10 +587,156 @@ var ( structuredCodePattern = regexp.MustCompile("(?m)^```([^?`\\r\\n]*)\\?(code_reference|code_stdout|code_stderr)&code_event_index=(\\d+)\\r?\\n") // generatedImageTagPattern 匹配正文中标出生成图片位置的图片标记,第 1 组为占位地址去掉 http://googleusercontent.com/ 的部分 generatedImageTagPattern = regexp.MustCompile(`[^`) - artifactPattern = regexp.MustCompile("(?m)^(?:https?://googleusercontent\\.com/(?:image_generation_content|generated_video_content|generated_music_content)/\\S+|" + generatedImageTagPattern.String() + ")\\s*") + artifactPattern = regexp.MustCompile("(?m)^(?:https?://googleusercontent\\.com/(?:image_generation_content|generated_video_content|generated_music_content|generated_animated_image)/\\S+|" + generatedImageTagPattern.String() + ")\\s*") generatedVideoPattern = regexp.MustCompile(`https?://googleusercontent\.com/generated_video_content/\S+`) ) +// fullSizeImageAssetURL 给生成图/GIF 的 lh3 地址补上 =s0,避免 prepareGeneratedMediaURL 追加 =s1024-rj 把动图压成静态 JPEG +func fullSizeImageAssetURL(mediaURL, mimeType string) string { + if !strings.HasPrefix(strings.ToLower(mimeType), "image/") || !strings.Contains(mediaURL, "lh3.googleusercontent.com/") { + return mediaURL + } + slash := strings.LastIndexByte(mediaURL, '/') + if slash >= 0 && !strings.Contains(mediaURL[slash+1:], "=") { + return mediaURL + "=s0" + } + return mediaURL +} + +// decodeAnimatedImages 提取视频模型(models/omni_1p5_gif)在富内容第 60 项 [0][0][9] 下输出的循环 GIF 动图 +func (d *FrameDecoder) decodeAnimatedImages(candidate []any, candidateIndex int, raw any, emit func(Event) error) error { + itemsValue, ok := valueAt(raw, 0, 0, 9) + if !ok { + return nil + } + items, ok := itemsValue.([]any) + if !ok { + return nil + } + generator, _ := stringAt(raw, 0, 0, 1, 2, 2) + placeholder, _ := stringAt(raw, 0, 0, 2, 0) + for _, entry := range items { + mediaURL, _ := stringAt(entry, 3) + mimeType, _ := stringAt(entry, 11) + if !strings.Contains(mediaURL, "lh3.googleusercontent.com/gg/") || !strings.HasPrefix(strings.ToLower(mimeType), "image/") { + continue + } + fileName, _ := stringAt(entry, 2) + if fileName == "" { + fileName = "animated_image.gif" + } + width, _ := intAt(entry, 15, 0) + height, _ := intAt(entry, 15, 1) + sizeBytes, _ := intAt(entry, 15, 2) + if err := d.emitMedia(candidateIndex, &Media{ + Type: MediaGeneratedImage, + URL: fullSizeImageAssetURL(mediaURL, mimeType), + Title: fileName, + FileName: fileName, + MIMEType: mimeType, + Generator: generator, + Placeholder: placeholder, + Width: width, + Height: height, + SizeBytes: sizeBytes, + Offset: mediaPlaceholderOffset(candidate, placeholder), + }, emit); err != nil { + return err + } + } + return nil +} + +// taskImageEntry 表示 Task 模式富内容第 59 项中的图片/GIF 文件条目 +type taskImageEntry struct { + tag string + fileName string + url string + mimeType string + width int + height int + sizeBytes int +} + +func collectTaskImageEntries(node any, out *[]taskImageEntry) { + switch typed := node.(type) { + case []any: + if len(typed) >= 3 { + if tag, ok := typed[0].(string); ok && strings.HasPrefix(tag, "[file-tag:") { + if meta, ok := typed[2].([]any); ok { + mediaURL, _ := stringAt(meta, 3) + mimeType, _ := stringAt(meta, 11) + if strings.Contains(mediaURL, "lh3.googleusercontent.com/") && strings.HasPrefix(strings.ToLower(mimeType), "image/") { + fileName, _ := stringAt(meta, 2) + if fileName == "" { + fileName = "image.gif" + } + width, _ := intAt(meta, 15, 0) + height, _ := intAt(meta, 15, 1) + sizeBytes, _ := intAt(meta, 15, 2) + *out = append(*out, taskImageEntry{ + tag: tag, fileName: fileName, url: fullSizeImageAssetURL(mediaURL, mimeType), + mimeType: mimeType, width: width, height: height, sizeBytes: sizeBytes, + }) + return + } + } + } + } + for _, child := range typed { + collectTaskImageEntries(child, out) + } + case map[string]any: + for _, child := range typed { + collectTaskImageEntries(child, out) + } + } +} + +// decodeTaskImages 提取 Task 模式在富内容第 59 项生成的图片与 GIF 动图 +func (d *FrameDecoder) decodeTaskImages(candidate []any, candidateIndex int, raw any, emit func(Event) error) error { + var entries []taskImageEntry + collectTaskImageEntries(raw, &entries) + for _, item := range entries { + if err := d.emitMedia(candidateIndex, &Media{ + Type: MediaGeneratedImage, + URL: item.url, + Title: item.fileName, + FileName: item.fileName, + MIMEType: item.mimeType, + Placeholder: item.tag, + Width: item.width, + Height: item.height, + SizeBytes: item.sizeBytes, + Offset: mediaPlaceholderOffset(candidate, item.tag), + }, emit); err != nil { + return err + } + } + return nil +} + +// stripTaskImageTags 仅去掉已转为内联图片/GIF 媒体的 [file-tag: ...],非图片附件标签保留原样 +func stripTaskImageTags(candidate []any, raw string) string { + if !strings.Contains(raw, "[file-tag:") { + return raw + } + field58, ok := richContentField(candidate, 58) + if !ok { + return raw + } + var entries []taskImageEntry + collectTaskImageEntries(field58, &entries) + if len(entries) == 0 { + return raw + } + pairs := make([]string, 0, len(entries)*4) + for _, item := range entries { + pairs = append(pairs, item.tag+"\n", "", item.tag, "") + } + return strings.NewReplacer(pairs...).Replace(raw) +} + func parseStructuredContent(raw string) (string, []codeSnapshot) { if !strings.Contains(raw, "&code_event_index=") { return normalizeSnapshot(stripArtifacts(raw)), nil diff --git a/internal/gemini/gif_decoder_test.go b/internal/gemini/gif_decoder_test.go new file mode 100644 index 0000000..4ed93f7 --- /dev/null +++ b/internal/gemini/gif_decoder_test.go @@ -0,0 +1,606 @@ +package gemini + +import ( + "context" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "net/url" + "slices" + "strings" + "testing" + + "google.golang.org/protobuf/encoding/protowire" +) + +func TestDecodeAnimatedGIFSparse60(t *testing.T) { + rich := make([]any, 60) + rich[59] = []any{ + []any{ + []any{ + []any{"帮我生成橘猫打滚的GIF"}, + []any{nil, nil, []any{nil, nil, "models/omni_1p5_gif"}}, + []any{"http://googleusercontent.com/generated_animated_image/3189649549508844264"}, + nil, nil, nil, nil, nil, + []any{"omni_context.pb"}, + []any{ + []any{ + nil, 1, "animated_image.gif", + "https://lh3.googleusercontent.com/gg/FAKE_ANIMATED_GIF_TOKEN", + nil, nil, nil, nil, nil, nil, nil, + "image/gif", + nil, nil, nil, + []any{float64(512), float64(288), float64(3231721)}, + }, + }, + }, + }, + } + candidate := make([]any, 13) + candidate[0] = "rc_gif001" + candidate[1] = []any{"你的GIF已准备好!\n\nhttp://googleusercontent.com/generated_animated_image/3189649549508844264"} + candidate[12] = rich + + decoder := NewFrameDecoder() + var events []Event + if err := decoder.decodeMedia(candidate, 0, ConversationSnapshot{CID: "c_1", RID: "r_1"}, func(e Event) error { + events = append(events, e) + return nil + }); err != nil { + t.Fatalf("decodeMedia failed: %v", err) + } + if len(events) != 1 || events[0].Media == nil { + t.Fatalf("expected 1 media event, got %+v", events) + } + media := events[0].Media + if media.Type != MediaGeneratedImage || media.MIMEType != "image/gif" { + t.Fatalf("unexpected media type/mime: %+v", media) + } + if media.Generator != "models/omni_1p5_gif" { + t.Fatalf("unexpected generator: %q", media.Generator) + } + if !strings.HasSuffix(media.URL, "=s0") { + t.Fatalf("expected =s0 suffix on GIF URL, got %q", media.URL) + } + parsedURL, err := url.Parse(media.URL) + if err != nil { + t.Fatal(err) + } + if !prepareGeneratedMediaURL(parsedURL) { + t.Fatal("prepareGeneratedMediaURL rejected GIF URL") + } + if strings.Contains(parsedURL.Path, "=s1024-rj") { + t.Fatalf("prepareGeneratedMediaURL overwrote =s0 with =s1024-rj: %q", parsedURL.String()) + } + + visible, _, _ := visibleContent(candidate, candidate[1].([]any)[0].(string)) + if strings.Contains(visible, "generated_animated_image") { + t.Fatalf("artifact placeholder not stripped: %q", visible) + } + if strings.TrimSpace(visible) != "你的GIF已准备好!" { + t.Fatalf("unexpected visible text: %q", visible) + } +} + +func TestDecodeTaskImageSparse59(t *testing.T) { + rich := make([]any, 59) + rich[58] = []any{ + []any{ + []any{ + "[file-tag: bouncing_red_ball.gif]", + nil, + []any{ + nil, float64(1), "bouncing_red_ball.gif", + "https://lh3.googleusercontent.com/gg/FAKE_TASK_GIF", + nil, nil, nil, nil, nil, nil, nil, + "image/gif", + nil, nil, nil, + []any{float64(400), float64(400), float64(136494)}, + }, + }, + []any{ + "[file-tag: report.pdf]", + nil, + []any{ + nil, float64(2), "report.pdf", nil, nil, nil, nil, + []any{"https://contribution.usercontent.google.com/download?c=xxx"}, + nil, nil, nil, "application/pdf", + }, + }, + }, + } + candidate := make([]any, 13) + candidate[0] = "rc_task001" + candidate[1] = []any{"已完成:\n[file-tag: bouncing_red_ball.gif]\n附件:\n[file-tag: report.pdf]"} + candidate[12] = rich + + decoder := NewFrameDecoder() + var events []Event + if err := decoder.decodeMedia(candidate, 0, ConversationSnapshot{CID: "c_2", RID: "r_2"}, func(e Event) error { + events = append(events, e) + return nil + }); err != nil { + t.Fatalf("decodeMedia failed: %v", err) + } + if len(events) != 1 || events[0].Media == nil { + t.Fatalf("expected 1 task GIF media event (ignoring PDF), got %+v", events) + } + if events[0].Media.FileName != "bouncing_red_ball.gif" || !strings.HasSuffix(events[0].Media.URL, "=s0") { + t.Fatalf("unexpected task GIF media: %+v", events[0].Media) + } + visible, _, _ := visibleContent(candidate, candidate[1].([]any)[0].(string)) + if strings.Contains(visible, "[file-tag: bouncing_red_ball.gif]") { + t.Fatalf("task GIF tag should be stripped: %q", visible) + } + if !strings.Contains(visible, "[file-tag: report.pdf]") { + t.Fatalf("non-image PDF tag should remain: %q", visible) + } +} + +func TestGIFModelCatalogAndGuard(t *testing.T) { + var payload []any + raw := `[1,null,null,null,null,null,null,null,null,null,null,null,null,null,null,[["56fdd199312815e2","Hydrogen",null,null,null,null,null,null,null,null,null,"4 Hydrogen","Fast",null,null,null,null,1]],null,[71,82,140,246,247],null,[[14,248,1,"Aspect ratio","Aspect ratio",null,"Aspect ratio",[[61,248,null,"1:1"],[59,248,null,"9:16"],[60,248,null,"3:4"],[62,248,null,"4:3"],[63,248,null,"16:9"]]],[14,247,1,"Format","Format",null,"Format",[[65,247,null,"Image"],[64,247,null,"GIF"]]]],null,null,null,null,["policy",[[["",1,false,null,"4 Hydrogen","4 Hydrogen","4 Hydrogen",false],null,1,[[1,"Low"]]]]]]` + if err := json.Unmarshal([]byte(raw), &payload); err != nil { + t.Fatal(err) + } + catalog, err := parseModelCatalog(payload) + if err != nil { + t.Fatalf("parseModelCatalog failed: %v", err) + } + gifModel, err := catalog.Resolve(GIFModelID) + if err != nil { + t.Fatalf("gemini-gif not registered: %v", err) + } + if gifModel.Feature != FeatureImage || gifModel.FormatOption != 64 { + t.Fatalf("unexpected gifModel config: %+v", gifModel) + } + if slices.Contains(gifModel.Capabilities, "predictLongRunning") { + t.Fatalf("gemini-gif should not advertise predictLongRunning: %+v", gifModel.Capabilities) + } + if !slices.Contains(gifModel.Capabilities, "predict") { + t.Fatalf("gemini-gif should advertise predict capability: %+v", gifModel.Capabilities) + } + choiceDefault := catalog.toolSelection(gifModel.Feature, "", gifModel.FormatOption) + if choiceDefault == nil || !slices.Equal(choiceDefault.options, []int{64}) { + t.Fatalf("unexpected default toolSelection for gemini-gif: %+v", choiceDefault) + } + choice916 := catalog.toolSelection(gifModel.Feature, "9:16", gifModel.FormatOption) + if choice916 == nil || !slices.Contains(choice916.options, 64) || !slices.Contains(choice916.options, 59) || choice916.aspectRatio != "9:16" { + t.Fatalf("unexpected 9:16 toolSelection for gemini-gif: %+v", choice916) + } + choice11 := catalog.toolSelection(gifModel.Feature, "1:1", gifModel.FormatOption) + if choice11 == nil || slices.Contains(choice11.options, 61) || (!slices.Contains(choice11.options, 59) && !slices.Contains(choice11.options, 63)) { + t.Fatalf("expected 1:1 to snap to 9:16 (59) or 16:9 (63) for gemini-gif: %+v", choice11) + } + + // 1. Pure text reply must be rejected as retryable ErrUpstreamFailureText + textGuard := newModelGuard(gifModel, func(Event) error { return nil }) + _ = textGuard.Emit(Event{Kind: EventMetadata, Metadata: &EventMetadataData{ModelHash: gifModel.Hash}}) + _ = textGuard.Emit(Event{Kind: EventText, Candidate: 0, Snapshot: "午后的阳光穿过树梢..."}) + if err := textGuard.Emit(Event{Kind: EventDone, FinishReason: FinishStop}); err == nil { + t.Fatal("expected pure text reply on gemini-gif to fail modelGuard") + } + if textGuard.Emitted() { + t.Fatal("expected textGuard not to flush pure text reply") + } + + // 2. Static image/jpeg must also be rejected as retryable ErrUpstreamFailureText + jpegGuard := newModelGuard(gifModel, func(Event) error { return nil }) + _ = jpegGuard.Emit(Event{Kind: EventMetadata, Metadata: &EventMetadataData{ModelHash: gifModel.Hash}}) + _ = jpegGuard.Emit(Event{Kind: EventMedia, Candidate: 0, Media: &Media{Type: MediaGeneratedImage, MIMEType: "image/jpeg", URL: "https://lh3.googleusercontent.com/gg/static=s0"}}) + if err := jpegGuard.Emit(Event{Kind: EventDone, FinishReason: FinishStop}); err == nil { + t.Fatal("expected static image/jpeg on gemini-gif to fail modelGuard") + } + if jpegGuard.Emitted() { + t.Fatal("expected jpegGuard not to flush static JPEG") + } + + // 3. Animated image/gif succeeds and flushes events + var emitted []Event + guard := newModelGuard(gifModel, func(e Event) error { + emitted = append(emitted, e) + return nil + }) + _ = guard.Emit(Event{Kind: EventMetadata, Metadata: &EventMetadataData{ModelHash: gifModel.Hash}}) + _ = guard.Emit(Event{Kind: EventMedia, Candidate: 0, Media: &Media{Type: MediaGeneratedImage, MIMEType: "image/gif", URL: "https://lh3.googleusercontent.com/gg/x=s0"}}) + if err := guard.Emit(Event{Kind: EventDone, FinishReason: FinishStop}); err != nil { + t.Fatalf("modelGuard rejected GIF media: %v", err) + } + if err := guard.Complete(); err != nil { + t.Fatalf("modelGuard Complete failed: %v", err) + } + if !guard.Emitted() || len(emitted) == 0 { + t.Fatal("expected guard to flush events for gemini-gif") + } +} + +func TestNormalizeCookieScopesOSIDToRequestHost(t *testing.T) { + osid := normalizeCookie(Cookie{Name: "OSID", Value: "v", Domain: ".google.com"}, "gemini.google.com") + if osid.Domain != "gemini.google.com" { + t.Fatalf("expected OSID domain gemini.google.com, got %q", osid.Domain) + } + secureOSID := normalizeCookie(Cookie{Name: "__Secure-OSID", Value: "v", Domain: ".google.com"}, "gemini.google.com") + if secureOSID.Domain != "gemini.google.com" { + t.Fatalf("expected __Secure-OSID domain gemini.google.com, got %q", secureOSID.Domain) + } + sid := normalizeCookie(Cookie{Name: "SID", Value: "v", Domain: ".google.com"}, "gemini.google.com") + if sid.Domain != ".google.com" { + t.Fatalf("expected SID domain .google.com, got %q", sid.Domain) + } +} + +func TestPromptRequestsGIF(t *testing.T) { + positives := []string{ + "帮我生成GIF", + "做个动图", + "生成动态图", + "create an animated cat", + } + for _, prompt := range positives { + if !PromptRequestsGIF(prompt) { + t.Fatalf("expected PromptRequestsGIF(%q) to be true", prompt) + } + } + negatives := []string{ + "写一段Go代码", + "画一张静态图", + } + for _, prompt := range negatives { + if PromptRequestsGIF(prompt) { + t.Fatalf("expected PromptRequestsGIF(%q) to be false", prompt) + } + } +} + +func TestBuildGeneratePayloadGIFFlags(t *testing.T) { + standardVideo := buildGeneratePayload(GenerateRequest{ + Feature: FeatureVideo, + FormatOption: 0, + tools: &toolChoice{options: []int{16}, aspectOrder: 1}, + }, "zh-CN", Preferences{}, "req2", "ctx2", false, false) + videoBox := standardVideo[0].([]any)[9].([]any)[6].([]any) + if len(videoBox) != 1 { + t.Fatalf("expected standard video mediaBox len 1, got %v", videoBox) + } + if opt, ok := videoBox[0].([]any); !ok || len(opt) != 4 || opt[3] != 1 { + t.Fatalf("expected standard video opt=[nil nil nil 1], got %v", videoBox[0]) + } + + imageGIF := buildGeneratePayload(GenerateRequest{ + Feature: FeatureImage, + FormatOption: 64, + personalIntelligence: true, + tools: &toolChoice{options: []int{64}}, + }, "zh-CN", Preferences{}, "req3", "ctx3", false, false) + if imageGIF[67] != 0 { + t.Fatalf("expected Image->GIF inner[67]==0 when personalIntelligence is enabled, got %v", imageGIF[67]) + } + imageGIFBox := imageGIF[0].([]any)[9].([]any)[6].([]any) + if len(imageGIFBox) != 11 || imageGIFBox[10] != 3 { + t.Fatalf("expected Image->GIF mediaBox[10]==3, got %v", imageGIFBox) + } + if opt, ok := imageGIFBox[1].([]any); !ok || len(opt) != 3 || opt[1] != nil || opt[2] != 1 { + t.Fatalf("expected Image->GIF opt=[nil nil 1], got %v", imageGIFBox[1]) + } +} + +func TestDecodeVideoBackgroundOverridesEarlyRefusalComplete(t *testing.T) { + progressPayload := make([]any, 7) + progressPayload[6] = []any{nil, []any{"video_generation", nil, float64(1)}} + + candidate := make([]any, 9) + candidate[0] = "rc_refusal01" + candidate[1] = []any{"我是一个文本 AI,这超出了我的能力范围。"} + candidate[8] = []any{float64(PhaseComplete)} + + refusalPayload := make([]any, 5) + refusalPayload[4] = []any{candidate} + + decoder := NewFrameDecoder() + state := NewConversationState() + var events []Event + err := decoder.Decode(func(yield func(streamRecord) error) error { + for _, rec := range []streamRecord{ + {payload: progressPayload}, + {payload: refusalPayload}, + {end: true}, + } { + if err := yield(rec); err != nil { + return err + } + } + return nil + }, state, func(e Event) error { + events = append(events, e) + return nil + }) + if err != nil { + t.Fatalf("Decode failed: %v", err) + } + if !decoder.background { + t.Fatal("expected decoder.background=true so awaitTurn polls hNvQHb despite early refusal text") + } + for _, ev := range events { + if ev.Kind == EventDone { + t.Fatalf("unexpected premature EventDone while waiting for video_generation background media: %+v", events) + } + } +} + +func testDecodeProtoBytesFields(t *testing.T, data []byte) map[protowire.Number][]byte { + t.Helper() + fields := make(map[protowire.Number][]byte) + for len(data) > 0 { + num, typ, n := protowire.ConsumeTag(data) + if n < 0 { + t.Fatalf("ConsumeTag failed: %d", n) + } + data = data[n:] + if typ == protowire.BytesType { + val, m := protowire.ConsumeBytes(data) + if m < 0 { + t.Fatalf("ConsumeBytes failed for field %d: %d", num, m) + } + fields[num] = val + data = data[m:] + continue + } + m := protowire.ConsumeFieldValue(num, typ, data) + if m < 0 { + t.Fatalf("ConsumeFieldValue failed for field %d: %d", num, m) + } + data = data[m:] + } + return fields +} + +func TestGeneratePayloadCapabilitiesAndModelHeaderTimezone(t *testing.T) { + inner := buildGeneratePayload(GenerateRequest{ + Feature: FeatureImage, + FormatOption: 64, + tools: &toolChoice{options: []int{64}}, + }, "zh-CN", Preferences{}, "req-cap", "ctx-cap", false, false) + + cap15, ok := inner[15].([]any) + if !ok || len(cap15) != 7 || !slices.Equal(cap15[6].([]int), []int{539}) { + t.Fatalf("unexpected inner[15]: %#v", inner[15]) + } + cap30, ok := inner[30].([]int) + if !ok || !slices.Equal(cap30, []int{4, 27, 28, 16, 19, 12}) { + t.Fatalf("unexpected inner[30]: %#v", inner[30]) + } + + innerFields := testDecodeProtoBytesFields(t, encodeJSPB(inner)) + if got := hex.EncodeToString(innerFields[16]); got != "3a029b04" { + t.Fatalf("expected encoded inner[15] (f16) = 3a029b04, got %s", got) + } + if got := hex.EncodeToString(innerFields[31]); got != "041b1c10130c" { + t.Fatalf("expected encoded inner[30] (f31) = 041b1c10130c, got %s", got) + } + + plainHeader := buildModelHeader(clientFeatures, Model{Hash: "56fdd199312815e2", Mode: 1}, "zh-CN", 0, 2, ThinkingLow, "cid-1", "bl-1", nil) + plainFields := testDecodeProtoBytesFields(t, plainHeader) + if got := string(plainFields[28]); got != hostTimezone { + t.Fatalf("expected modelHeader f28=%q without variant, got %q", hostTimezone, got) + } + if _, hasVariant := plainFields[25]; hasVariant { + t.Fatalf("unexpected variant f25 in plain header: %q", plainFields[25]) + } + + variantHeader := buildModelHeader(clientFeatures, Model{Hash: "test-variant", Mode: 1, Variant: "test-variant"}, "zh-CN", 0, 2, ThinkingLow, "cid-2", "bl-2", nil) + variantFields := testDecodeProtoBytesFields(t, variantHeader) + if got := string(variantFields[25]); got != "test-variant" { + t.Fatalf("expected modelHeader f25=%q, got %q", "test-variant", got) + } + if got := string(variantFields[28]); got != hostTimezone { + t.Fatalf("expected modelHeader f28=%q with variant, got %q", hostTimezone, got) + } +} + +func TestBinaryChannelEncodeAndDecode(t *testing.T) { + if got := base64.StdEncoding.EncodeToString(encodeJSPB(channelEndMessage)); got != "IgIIAQ==" { + t.Fatalf("expected channelEndMessage == IgIIAQ==, got %s", got) + } + + payload := buildGeneratePayload(GenerateRequest{ + Feature: FeatureImage, + FormatOption: 64, + Files: []FileData{ + {URL: "https://example.com/a.png", FileName: "a.png", MimeType: "image/png"}, + {URL: "https://example.com/b.png", FileName: "b.png", MimeType: "image/png"}, + }, + tools: &toolChoice{options: []int{64}}, + }, "zh-CN", Preferences{}, "req-bin", "ctx-bin", false, false) + + jsonEncoded, err := pageJSON(payload[0]) + if err != nil { + t.Fatalf("pageJSON failed: %v", err) + } + if !strings.Contains(jsonEncoded, `"a.png"`) || !strings.Contains(jsonEncoded, `"b.png"`) { + t.Fatalf("unexpected JSON serialization of repeatedMessages attachments: %s", jsonEncoded) + } + msgBytes := encodeJSPB(payload[0].([]any)) + msgFields, ok := parseProtoFields(msgBytes) + if !ok { + t.Fatal("failed to parse encoded message[0]") + } + attachmentTags := 0 + for _, f := range msgFields { + if f.num == 4 && f.typ == protowire.BytesType { + attachmentTags++ + } + } + if attachmentTags != 2 { + t.Fatalf("expected 2 repeated field-4 attachment tags, got %d", attachmentTags) + } + + ch := &channel{binaryProto: true} + root := make([]any, 40) + root[1] = []any{"c_bin12345", "r_bin12345"} + root[4] = repeatedMessages{ + []any{"rc_bin01", []any{"你好,正在处理"}, nil, nil, nil, nil, nil, nil, []any{int(PhaseComplete)}}, + } + root[6] = []any{nil, []any{"video_generation", nil, 1}} + root[20] = []any{"ctrl_tok_1"} + root[25] = channelCommitted + root[37] = []any{3} + root[39] = "56fdd199312815e2" + rootBytes := encodeJSPB(root) + + var inner4 []byte + inner4 = protowire.AppendBytes(protowire.AppendTag(inner4, 4, protowire.BytesType), rootBytes) + var item4 []byte + item4 = protowire.AppendBytes(protowire.AppendTag(item4, 4, protowire.BytesType), inner4) + var item1 []byte + item1 = protowire.AppendBytes(protowire.AppendTag(item1, 1, protowire.BytesType), item4) + var list2 []byte + list2 = protowire.AppendBytes(protowire.AppendTag(list2, 7, protowire.BytesType), item1) + var rne []byte + rne = protowire.AppendBytes(protowire.AppendTag(rne, 2, protowire.BytesType), list2) + + ch.ended = true + decoder := NewFrameDecoder() + state := NewConversationState() + heartbeats := 0 + decoder.heartbeat = func() { heartbeats++ } + + var records []streamRecord + done, err := ch.handleBinaryFrame(context.Background(), rne, func(rec streamRecord) error { + records = append(records, rec) + return nil + }) + if err != nil || done { + t.Fatalf("unexpected handleBinaryFrame result done=%v err=%v", done, err) + } + endDone, err := ch.handleBinaryFrame(context.Background(), encodeJSPB(channelEndMessage), func(rec streamRecord) error { + records = append(records, rec) + return nil + }) + if err != nil || !endDone { + t.Fatalf("expected end frame to mark done=true, got done=%v err=%v", endDone, err) + } + err = decoder.Decode(func(yield func(streamRecord) error) error { + for _, rec := range records { + if err := yield(rec); err != nil { + return err + } + } + return nil + }, state, func(Event) error { return nil }) + if err != nil { + t.Fatalf("FrameDecoder.Decode failed: %v", err) + } + if !decoder.background || !decoder.videoBackground { + t.Fatalf("expected background=true videoBackground=true, got %v/%v", decoder.background, decoder.videoBackground) + } + if heartbeats != 1 { + t.Fatalf("expected 1 heartbeat, got %d", heartbeats) + } + snap := state.Snapshot() + if snap.CID != "c_bin12345" || snap.RID != "r_bin12345" || snap.RCID != "rc_bin01" { + t.Fatalf("unexpected decoded snapshot: %+v", snap) + } + if decoder.metadata.ModelHash != "56fdd199312815e2" || decoder.metadata.ControlToken != "ctrl_tok_1" { + t.Fatalf("unexpected decoded metadata: %+v", decoder.metadata) + } + + var bardVal []byte + bardVal = protowire.AppendVarint(protowire.AppendTag(bardVal, 1, protowire.VarintType), 1037) + var anyMsg []byte + anyMsg = protowire.AppendString(protowire.AppendTag(anyMsg, 1, protowire.BytesType), "type.googleapis.com/BardErrorInfo") + anyMsg = protowire.AppendBytes(protowire.AppendTag(anyMsg, 2, protowire.BytesType), bardVal) + var status1037 []byte + status1037 = protowire.AppendVarint(protowire.AppendTag(status1037, 1, protowire.VarintType), 8) + status1037 = protowire.AppendBytes(protowire.AppendTag(status1037, 3, protowire.BytesType), anyMsg) + rec1037 := channelBinaryStatus(base64.StdEncoding.EncodeToString(status1037)) + if rec1037.bardCode != 1037 { + t.Fatalf("expected bardCode 1037, got %+v", rec1037) + } + + var status16 []byte + status16 = protowire.AppendVarint(protowire.AppendTag(status16, 1, protowire.VarintType), 16) + status16 = protowire.AppendString(protowire.AppendTag(status16, 2, protowire.BytesType), "unauthenticated") + rec16 := channelBinaryStatus(base64.StdEncoding.EncodeToString(status16)) + if !errors.Is(rec16.err, ErrSignedOut) { + t.Fatalf("expected ErrSignedOut for status 16, got %+v", rec16) + } +} + +func TestBinaryChannelRealCapturedFrames(t *testing.T) { + wrapRealRoot := func(rootBytes []byte) []byte { + var inner4 []byte + inner4 = protowire.AppendBytes(protowire.AppendTag(inner4, 4, protowire.BytesType), rootBytes) + var item4 []byte + item4 = protowire.AppendBytes(protowire.AppendTag(item4, 4, protowire.BytesType), inner4) + var item1 []byte + item1 = protowire.AppendBytes(protowire.AppendTag(item1, 1, protowire.BytesType), item4) + var list7 []byte + list7 = protowire.AppendBytes(protowire.AppendTag(list7, 7, protowire.BytesType), item1) + var rne []byte + return protowire.AppendBytes(protowire.AppendTag(rne, 2, protowire.BytesType), list7) + } + + root4 := make([]any, 21) + root4[1] = []any{"c_edd36f8859655f22", "r_ab1f45ca0916648a"} + root4[20] = []any{"+7AK5IoUcByB5ESkBF4i_vm7qCwkbjDO71BU70L9FKGY"} + root5 := make([]any, 7) + root5[1] = []any{"c_edd36f8859655f22", "r_ab1f45ca0916648a"} + root5[6] = []any{"正在生成GIF,这可能需要几分钟时间,请稍后回来查看完成状态。", []any{"video_generation", nil, 1}} + + framesB64 := []string{ + "CgA=", + "EkwIATpICkYIABImCiRhNDE1YzlmZC1lZmQ4LTQzNzctODYzZC0xODE5OTk1ZTA0ZWUiGiIYEhYKEmNfZWRkMzZmODg1OTY1NWYyMhIA", + base64.StdEncoding.EncodeToString(wrapRealRoot(encodeJSPB(root4))), + base64.StdEncoding.EncodeToString(wrapRealRoot(encodeJSPB(root5))), + "EmIIBDpeClwIABIUChJyX2FiMWY0NWNhMDkxNjY0OGEiQiJAEigKEmNfZWRkMzZmODg1OTY1NWYyMhIScl9hYjFmNDVjYTA5MTY2NDhhWhQKEuiNieWcsOS4iueahOapmOeMqw==", + "Ek8IBTpLCkkIABIUChJyX2FiMWY0NWNhMDkxNjY0OGEiLyItEigKEmNfZWRkMzZmODg1OTY1NWYyMhIScl9hYjFmNDVjYTA5MTY2NDhhogMA", + "IgA=", + } + + ch := &channel{binaryProto: true, ended: true} + var records []streamRecord + doneSeen := false + for _, b64 := range framesB64 { + raw, err := base64.StdEncoding.DecodeString(b64) + if err != nil { + t.Fatalf("decode b64: %v", err) + } + done, err := ch.handleBinaryFrame(context.Background(), raw, func(rec streamRecord) error { + records = append(records, rec) + return nil + }) + if err != nil { + t.Fatalf("handleBinaryFrame err: %v", err) + } + if done { + doneSeen = true + } + } + if !doneSeen { + t.Fatal("expected IgA= frame to mark done=true") + } + + decoder := NewFrameDecoder() + state := NewConversationState() + if err := decoder.Decode(func(yield func(streamRecord) error) error { + for _, rec := range records { + if err := yield(rec); err != nil { + return err + } + } + return nil + }, state, func(Event) error { return nil }); err != nil { + t.Fatalf("Decode failed: %v", err) + } + if !decoder.background || !decoder.videoBackground { + t.Fatalf("expected background=true videoBackground=true, got %v/%v", decoder.background, decoder.videoBackground) + } + snap := state.Snapshot() + if snap.CID != "c_edd36f8859655f22" || snap.RID != "r_ab1f45ca0916648a" { + t.Fatalf("unexpected snapshot: %+v", snap) + } + if decoder.metadata.Title != "草地上的橘猫" { + t.Fatalf("unexpected metadata title: %q", decoder.metadata.Title) + } +} diff --git a/internal/gemini/model_guard.go b/internal/gemini/model_guard.go index 2e14421..eca808b 100644 --- a/internal/gemini/model_guard.go +++ b/internal/gemini/model_guard.go @@ -30,11 +30,15 @@ func newModelGuard(expected Model, emit func(Event) error) *modelGuard { return &modelGuard{expected: expected, emit: emit} } +func (g *modelGuard) expectsMedia() bool { + return g.expected.Feature == FeatureVideo || g.expected.FormatOption != 0 +} + func (g *modelGuard) Emit(event Event) error { - if g.expected.Feature == FeatureVideo && !g.videoChecked { + if g.expectsMedia() && !g.videoChecked { g.observeVideoEvent(event) } - if g.validated && (g.expected.Feature != FeatureVideo || g.videoChecked) { + if g.validated && (!g.expectsMedia() || g.videoChecked) { g.emitted = true return g.emit(event) } @@ -44,7 +48,7 @@ func (g *modelGuard) Emit(event Event) error { } g.validated = true } - if g.expected.Feature != FeatureVideo { + if !g.expectsMedia() { g.pending = append(g.pending, event) if !g.validated { return nil @@ -87,7 +91,9 @@ func (g *modelGuard) observeVideoEvent(event Event) { g.limitNotice = event.Metadata.LimitNotice } g.failureReply = event.Metadata.FailureReply - case event.Kind == EventMedia && event.Candidate == 0 && event.Media != nil && event.Media.Type == MediaGeneratedVideo: + case event.Kind == EventMedia && event.Candidate == 0 && event.Media != nil && + ((g.expected.FormatOption == 0 && event.Media.Type == MediaGeneratedVideo) || + (g.expected.FormatOption != 0 && event.Media.Type == MediaGeneratedImage && strings.EqualFold(event.Media.MIMEType, "image/gif"))): g.hasVideo = true } } @@ -99,6 +105,12 @@ func (g *modelGuard) checkVideoReply() error { return nil case g.limitNotice != "" || isVideoQuotaText(g.text): return videoQuotaError(g.text, g.limitNotice, parseVideoResetTime(time.Now(), g.limitNotice, g.text)) + case g.expected.FormatOption != 0: + message := "官网未返回生成的 GIF 动图,请稍后重试" + if trimmed := strings.TrimSpace(g.text); trimmed != "" { + message = "官网未生成 GIF 动图,返回了文字回复:" + trimmed + } + return &ProtocolError{HTTPStatus: 502, Code: 502, Message: message, Retryable: true, Cause: ErrUpstreamFailureText} case isVideoRefusalText(g.text): return videoRefusalError(g.text) } @@ -119,7 +131,7 @@ func (g *modelGuard) flush() error { } func (g *modelGuard) Complete() error { - if g.expected.Feature == FeatureVideo && !g.videoChecked && !g.hasVideo { + if g.expectsMedia() && !g.videoChecked && !g.hasVideo { if err := g.checkVideoReply(); err != nil { return err } @@ -132,7 +144,7 @@ func (g *modelGuard) Complete() error { Retryable: true, } } - if g.expected.Feature == FeatureVideo && !g.videoChecked { + if g.expectsMedia() && !g.videoChecked { g.videoChecked = true return g.flush() } diff --git a/internal/gemini/models.go b/internal/gemini/models.go index b365629..f020857 100644 --- a/internal/gemini/models.go +++ b/internal/gemini/models.go @@ -25,6 +25,8 @@ type Model struct { ThinkingLevels []ThinkingLevel // Feature 为该 ID 在生成请求中选中的官网工具,普通对话模型为零 Feature Feature + // FormatOption 为工具菜单中强制选中的选项 ID(如 GIF 格式 64),零表示使用默认选项 + FormatOption int // Gem 为 Gem 条目的 Gem ID,写入生成请求 19 槽 Gem string // PredefinedGem 表示该条目是官网 CNgdBe 类型 3 的 Google 预置 Gem @@ -38,6 +40,9 @@ type Model struct { // ImageModelID 是官网 Create image 工具的公开模型 ID const ImageModelID = "gemini-3.1-flash-image" +// GIFModelID 是官网视频/动图工具的 GIF 公开模型 ID +const GIFModelID = "gemini-gif" + // featureTool 是以独立公开 ID 提供、由账户默认模型协调的官网输入框工具 type featureTool struct { id string @@ -46,16 +51,19 @@ type featureTool struct { feature Feature // capabilities 为账户能力表 payload[17] 中启用该工具需要的全部能力号 capabilities []int + // formatOption 为工具子菜单中需强制选中的格式选项 ID(0 表示使用官网默认) + formatOption int } // featureTools 是公开为独立模型 ID 的官网工具 var featureTools = []featureTool{ - {ImageModelID, "Nano Banana 2", "Gemini Web image generation and editing", FeatureImage, []int{82}}, - {"gemini-video", "Video", "Gemini Web video generation", FeatureVideo, []int{71, 140}}, - {"gemini-music", "Music", "Gemini Web music generation", FeatureMusic, []int{139}}, - {"gemini-canvas", "Canvas", "Gemini Web Canvas documents and code", FeatureCanvas, []int{51}}, - {"gemini-deep-research", "Deep Research", "Gemini Web Deep Research reports", FeatureDeepResearch, []int{50}}, - {"gemini-guided-learning", "Guided Learning", "Gemini Web Guided Learning", FeatureLearning, []int{117}}, + {ImageModelID, "Nano Banana 2", "Gemini Web image generation and editing", FeatureImage, []int{82}, 0}, + {"gemini-video", "Video", "Gemini Web video generation", FeatureVideo, []int{71, 140}, 0}, + {GIFModelID, "GIF", "Gemini Web animated GIF generation", FeatureImage, []int{82, 247}, 64}, + {"gemini-music", "Music", "Gemini Web music generation", FeatureMusic, []int{139}, 0}, + {"gemini-canvas", "Canvas", "Gemini Web Canvas documents and code", FeatureCanvas, []int{51}, 0}, + {"gemini-deep-research", "Deep Research", "Gemini Web Deep Research reports", FeatureDeepResearch, []int{50}, 0}, + {"gemini-guided-learning", "Guided Learning", "Gemini Web Guided Learning", FeatureLearning, []int{117}, 0}, } // ModelCatalog 表示单个账号当前可用的模型目录 @@ -131,20 +139,39 @@ type toolChoice struct { durationOrder int } -// toolSelection 返回工具选中的选项:各组默认项,请求宽高比时 Aspect ratio 组换成比例最接近的一项;工具没有选项组时为 nil -func (c ModelCatalog) toolSelection(feature Feature, aspectRatio string) *toolChoice { +// toolSelection 返回工具选中的选项:各组默认项,请求宽高比时 Aspect ratio 组换成比例最接近的一项,指定 formatOption 时强制选中对应格式选项;工具没有选项组时为 nil +func (c ModelCatalog) toolSelection(feature Feature, aspectRatio string, formatOption int) *toolChoice { options, ok := c.options[feature] if !ok { return nil } + overrideGroup := "" + if formatOption > 0 { + for _, option := range options { + if option.id == formatOption { + overrideGroup = option.group + break + } + } + } requested, hasRatio := parseAspectRatio(aspectRatio) choice := &toolChoice{options: make([]int, 0)} closest, closestDistance, closestOrder := toolOption{id: -1}, math.Inf(1), 0 order := make(map[string]int) for _, option := range options { order[option.group]++ + if formatOption > 0 && option.id == formatOption { + choice.options = append(choice.options, option.id) + continue + } + if overrideGroup != "" && option.group == overrideGroup { + continue + } ratio, isRatio := parseAspectRatio(option.label) if hasRatio && option.group == "Aspect ratio" && isRatio { + if formatOption == 64 && option.id != 59 && option.id != 63 { + continue + } if distance := math.Abs(math.Log(ratio / requested)); distance < closestDistance { closest, closestDistance, closestOrder = option, distance, order[option.group] } @@ -166,7 +193,7 @@ func (c ModelCatalog) toolSelection(feature Feature, aspectRatio string) *toolCh if closest.id >= 0 { choice.options = append(choice.options, closest.id) choice.aspectRatio, choice.aspectOrder = closest.label, closestOrder - if slices.Contains(nativeImageRatios, aspectRatio) { + if formatOption == 0 && slices.Contains(nativeImageRatios, aspectRatio) { choice.aspectRatio = aspectRatio } } @@ -375,10 +402,17 @@ func parseModelCatalog(payload []any) (ModelCatalog, error) { continue } entry := defaultModel - entry.ID, entry.DisplayName, entry.Description, entry.Default, entry.Feature, entry.Position = tool.id, tool.displayName, tool.description, false, tool.feature, fmt.Sprintf("tool/%d", tool.feature) - if tool.feature == FeatureVideo { + pos := fmt.Sprintf("tool/%d", tool.feature) + if tool.formatOption > 0 { + pos = fmt.Sprintf("tool/%d/%d", tool.feature, tool.formatOption) + } + entry.ID, entry.DisplayName, entry.Description, entry.Default, entry.Feature, entry.FormatOption, entry.Position = tool.id, tool.displayName, tool.description, false, tool.feature, tool.formatOption, pos + if tool.feature == FeatureVideo && tool.formatOption == 0 { entry.Capabilities = append(slices.Clone(entry.Capabilities), "predictLongRunning") } + if tool.feature == FeatureImage { + entry.Capabilities = append(slices.Clone(entry.Capabilities), "predict") + } catalog.add(entry) } taskPolicy := parsePolicy(payload, 2) diff --git a/internal/gemini/payload.go b/internal/gemini/payload.go index f44e518..037c67f 100644 --- a/internal/gemini/payload.go +++ b/internal/gemini/payload.go @@ -6,7 +6,7 @@ func buildGeneratePayload(request GenerateRequest, language string, preferences attachments := any(nil) if len(request.Files) > 0 { - values := make([]any, 0, len(request.Files)) + values := make(repeatedMessages, 0, len(request.Files)) for _, file := range request.Files { values = append(values, []any{[]any{file.URL, attachmentType(file.MimeType, file.FileName), nil, file.MimeType, file.FileID}, file.FileName, nil, nil, nil, nil, nil, nil, []any{0}}) } @@ -23,6 +23,14 @@ func buildGeneratePayload(request GenerateRequest, language string, preferences duration = request.tools.durationOrder } message = append(message, nil, nil, []any{nil, nil, nil, nil, nil, nil, []any{[]any{nil, nil, duration, orientation}}}) + case request.Feature == FeatureImage && request.FormatOption == 64: + var ratio any + if request.tools != nil && request.tools.aspectRatio != "" { + ratio = request.tools.aspectRatio + } + imageOpt := []any{nil, ratio, 1} + mediaBox := []any{nil, imageOpt, nil, nil, nil, nil, nil, nil, nil, nil, 3} + message = append(message, nil, nil, []any{nil, nil, nil, nil, nil, nil, mediaBox}) case request.Feature == FeatureDeepResearch: message = append(message, nil, nil, []any{nil, nil, nil, nil, nil, nil, []any{}}) case request.tools != nil && request.tools.aspectRatio != "": @@ -48,12 +56,13 @@ func buildGeneratePayload(request GenerateRequest, language string, preferences inner[7] = 1 inner[10] = 1 inner[11] = 0 + inner[15] = []any{nil, nil, nil, nil, nil, nil, []int{539}} inner[18] = 0 if request.Gem != "" { inner[19] = request.Gem } inner[27] = 1 - inner[30] = []any{4, 27, 28, 16, 19, 12} + inner[30] = []int{4, 27, 28, 16, 19, 12} inner[41] = []any{2} if preferences.Bool(preferenceSlot41) { inner[41] = []any{1} @@ -81,7 +90,7 @@ func buildGeneratePayload(request GenerateRequest, language string, preferences inner[61] = []any{} if request.personalIntelligence { inner[67] = 1 - if temporaryChat { + if temporaryChat || request.FormatOption != 0 { inner[67] = 0 } } diff --git a/internal/gemini/request.go b/internal/gemini/request.go index db2ba31..794ec9f 100644 --- a/internal/gemini/request.go +++ b/internal/gemini/request.go @@ -70,6 +70,7 @@ type GenerateRequest struct { ModelMode int ThinkingLevel ThinkingLevel Feature Feature + FormatOption int // Gem 为在 Gem 中对话时的 Gem ID Gem string // AspectRatio 为生成媒体请求的宽高比,例如 16:9 或 1536x1024,空值使用官网默认 diff --git a/internal/gemini/research.go b/internal/gemini/research.go index 0b4f841..3270b51 100644 --- a/internal/gemini/research.go +++ b/internal/gemini/research.go @@ -14,6 +14,9 @@ import ( // turnPollInterval 是读取会话中后台生成回答的轮询间隔 var turnPollInterval = 30 * time.Second +// gifPollInterval 是 GIF 动图后台生成的轮询间隔,比 Deep Research / 视频更短以降低成品检出延迟 +var gifPollInterval = 5 * time.Second + // turnMissingPolls 是会话中连续读不到本轮回答时放弃等待的轮询次数 const turnMissingPolls = 4 @@ -132,7 +135,13 @@ func (c *Client) awaitTurn(ctx context.Context, state *ConversationState, decode if err != nil { return err } - ticker := time.NewTicker(turnPollInterval) + interval := turnPollInterval + missingLimit := turnMissingPolls + if model.FormatOption != 0 { + interval = gifPollInterval + missingLimit = 12 + } + ticker := time.NewTicker(interval) defer ticker.Stop() started := time.Now() missing := 0 @@ -159,7 +168,7 @@ func (c *Client) awaitTurn(ctx context.Context, state *ConversationState, decode } turns, _ := arrayAt(payload, 0) if !slices.ContainsFunc(turns, func(turn any) bool { rid, _ := stringAt(turn, 0, 1); return rid == session.RID }) { - if missing++; missing >= turnMissingPolls { + if missing++; missing >= missingLimit { return retryableProtocolError("官网会话中没有本次请求的回答", nil) } continue