From 6c46e5561c4e839ab99f25b742e757ce0ce3f1fb Mon Sep 17 00:00:00 2001 From: SadWood <24450652+SadWood@users.noreply.github.com> Date: Sat, 3 Oct 2026 22:33:43 +0800 Subject: [PATCH] =?UTF-8?q?fix(gateway):=20=E4=BF=AE=E5=A4=8D=20Anthropic?= =?UTF-8?q?=20=E5=9B=BE=E7=89=87=E6=9D=A5=E6=BA=90=E5=AD=97=E6=AE=B5?= =?UTF-8?q?=E6=B7=B7=E7=94=A8=20(#677)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 图片来源按 base64 或 URL 输出各自字段,避免空的互斥字段导致 Factory 拒绝请求。 补充图片编码及已迁移 Factory 插件链路的回归测试,覆盖历史截图和后续文字请求。 --- internal/gateway/anthropic.go | 12 +- .../gateway/anthropic_image_source_test.go | 139 ++++++++++++++++++ 2 files changed, 145 insertions(+), 6 deletions(-) create mode 100644 internal/gateway/anthropic_image_source_test.go diff --git a/internal/gateway/anthropic.go b/internal/gateway/anthropic.go index a614f6bb7..9463b398e 100644 --- a/internal/gateway/anthropic.go +++ b/internal/gateway/anthropic.go @@ -23,9 +23,9 @@ type aBlock struct { // image Source *struct { Type string `json:"type"` - MediaType string `json:"media_type"` - Data string `json:"data"` - URL string `json:"url"` + MediaType string `json:"media_type,omitempty"` + Data string `json:"data,omitempty"` + URL string `json:"url,omitempty"` } `json:"source,omitempty"` // tool_use ID string `json:"id,omitempty"` @@ -312,9 +312,9 @@ func imageBlock(p Part) aBlock { b := aBlock{Type: "image"} b.Source = &struct { Type string `json:"type"` - MediaType string `json:"media_type"` - Data string `json:"data"` - URL string `json:"url"` + MediaType string `json:"media_type,omitempty"` + Data string `json:"data,omitempty"` + URL string `json:"url,omitempty"` }{} if p.URL != "" && p.Data == "" { b.Source.Type, b.Source.URL = "url", p.URL diff --git a/internal/gateway/anthropic_image_source_test.go b/internal/gateway/anthropic_image_source_test.go new file mode 100644 index 000000000..260cf4bec --- /dev/null +++ b/internal/gateway/anthropic_image_source_test.go @@ -0,0 +1,139 @@ +package gateway + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + + "github.com/yetone/magpie/internal/catalog" +) + +func TestAnthropicImageSourceFields(t *testing.T) { + for _, tc := range []struct { + name string + part Part + want map[string]string + }{ + {"base64", Part{Kind: Image, MediaType: "image/png", Data: pngA}, map[string]string{"type": "base64", "media_type": "image/png", "data": pngA}}, + {"dataURL", Part{Kind: Image, MediaType: "image/png", Data: pngA, URL: "data:image/png;base64," + pngA}, map[string]string{"type": "base64", "media_type": "image/png", "data": pngA}}, + {"url", Part{Kind: Image, URL: "https://example.test/screenshot.png"}, map[string]string{"type": "url", "url": "https://example.test/screenshot.png"}}, + } { + t.Run(tc.name, func(t *testing.T) { + body, err := json.Marshal(imageBlock(tc.part)) + if err != nil { + t.Fatal(err) + } + var block struct { + Type string `json:"type"` + Source map[string]string `json:"source"` + } + if err := json.Unmarshal(body, &block); err != nil { + t.Fatal(err) + } + if block.Type != "image" || !reflect.DeepEqual(block.Source, tc.want) { + t.Fatalf("image source includes missing or extra fields: %s; want %v", body, tc.want) + } + }) + } +} + +func TestMovedAnthropicImagesKeepSourceVariant(t *testing.T) { + for _, source := range []struct { + name string + url string + want map[string]string + }{ + {"base64", "data:image/png;base64," + pngA, map[string]string{"type": "base64", "media_type": "image/png", "data": pngA}}, + {"url", "https://example.test/screenshot.png", map[string]string{"type": "url", "url": "https://example.test/screenshot.png"}}, + } { + for _, history := range []bool{false, true} { + name := source.name + "/user" + if history { + name = source.name + "/toolHistory" + } + t.Run(name, func(t *testing.T) { + // The catalog caches data across movedFake's temporary homes. + catalog.Reset() + t.Cleanup(catalog.Reset) + seen := make(chan map[string]any, 1) + movedFake(t, "factory", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + var request map[string]any + if err := json.Unmarshal(body, &request); err != nil { + http.Error(w, err.Error(), 400) + return + } + var images []map[string]string + var walk func(any) + walk = func(value any) { + switch x := value.(type) { + case []any: + for _, child := range x { + walk(child) + } + case map[string]any: + if x["type"] == "image" { + b, _ := json.Marshal(x["source"]) + var image map[string]string + json.Unmarshal(b, &image) + images = append(images, image) + } + walk(x["content"]) + } + } + walk(request["messages"]) + select { + case seen <- request: + default: + } + if len(images) != 1 || !reflect.DeepEqual(images[0], source.want) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + io.WriteString(w, `{"type":"error","error":{"type":"invalid_request_error","message":"image.source contains fields from another variant: Extra inputs are not permitted"}}`) + return + } + w.Header().Set("Content-Type", "text/event-stream") + for _, event := range []string{ + `{"type":"message_start","message":{"id":"m","type":"message","role":"assistant","model":"fake-claude","content":[],"usage":{"input_tokens":1,"output_tokens":0}}}`, + `{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ok"}}`, + `{"type":"content_block_stop","index":0}`, + `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`, + `{"type":"message_stop"}`, + } { + fmt.Fprintf(w, "data: %s\n\n", event) + } + })) + image := map[string]any{"type": "input_image", "image_url": source.url} + input := []any{map[string]any{"role": "user", "content": []any{image}}} + if history { + input = []any{ + map[string]any{"role": "user", "content": "view the screenshot"}, + map[string]any{"type": "function_call", "name": "view_image", "call_id": "call_1", "arguments": "{}"}, + map[string]any{"type": "function_call_output", "call_id": "call_1", "output": []any{map[string]any{"type": "input_text", "text": "screenshot"}, image}}, + map[string]any{"role": "assistant", "content": "image received"}, + map[string]any{"role": "user", "content": "continue with text"}, + } + } + body, _ := json.Marshal(map[string]any{"model": "factory/fake-claude", "input": input, "max_output_tokens": 32}) + rec := httptest.NewRecorder() + New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(string(body)))) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"text":"ok"`) { + t.Fatalf("translated image rejected by moved provider: %d %s", rec.Code, rec.Body.String()) + } + request := <-seen + if history { + wire, _ := json.Marshal(request["messages"]) + if !strings.Contains(string(wire), `"tool_use_id":"call_1"`) || !strings.Contains(string(wire), `"text":"screenshot"`) || !strings.Contains(string(wire), `"text":"continue with text"`) { + t.Fatalf("tool history or subsequent text lost: %s", wire) + } + } + }) + } + } +}