diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index edcff95b4..a3dca0584 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -6605,6 +6605,7 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. // an earlier turn's reasoning_content, which Mistral turns // away, as the thinking part it takes (#494) body = mistralThinking(body) + body = mistralImageLimit(body) } if isKimi(p, proto) { // another vendor's reasoning_details (MiMo's, with a stream's @@ -8164,6 +8165,7 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to // it; every follow-up of a Codex tool loop was refused, 422 // extra_forbidden (#4906) body = mistralThinking(body) + body = mistralImageLimit(body) } if to == provider.Responses && !keepsLoneNone(p) { // the "none" buildResponses keeps for a request that turned diff --git a/internal/gateway/mistral_images.go b/internal/gateway/mistral_images.go new file mode 100644 index 000000000..fcd44da6d --- /dev/null +++ b/internal/gateway/mistral_images.go @@ -0,0 +1,81 @@ +package gateway + +import ( + "bytes" + "encoding/json" +) + +// mistralMaxImages is the most images Mistral takes in one request: past +// it the API answers 400 "Total number of images exceeds the maximum +// allowed of 20." (regain4125 on X, Codex after 20+ screenshots). Mistral's +// docs say only that the count depends on the model, so the number is the +// one its error names. +const mistralMaxImages = 20 + +// mistralImagesLeft is the text that stands where an image was dropped. +const mistralImagesLeft = "[An earlier image is left out of this request.]" + +// mistralImageLimit keeps a Chat request bound for Mistral within its image +// limit: the oldest images past the last mistralMaxImages are replaced by a +// short text part, in place, so the turns around them stay. A request +// within the limit comes back byte for byte. +func mistralImageLimit(body []byte) []byte { + if bytes.Count(body, []byte(`"image_url"`)) <= mistralMaxImages { + return body + } + var q map[string]json.RawMessage + if decodeJSON(body, &q) != nil { + return body + } + var msgs []json.RawMessage + if decodeJSON(q["messages"], &msgs) != nil { + return body + } + type slot struct{ msg, part int } + var images []slot + parsed := make([]map[string]json.RawMessage, len(msgs)) + lists := make([][]json.RawMessage, len(msgs)) + for i, raw := range msgs { + var m map[string]json.RawMessage + if decodeJSON(raw, &m) != nil { + continue + } + c := bytes.TrimSpace(m["content"]) + var list []json.RawMessage + if len(c) == 0 || c[0] != '[' || decodeJSON(c, &list) != nil { + continue + } + parsed[i], lists[i] = m, list + for j, part := range list { + var t struct { + Type string `json:"type"` + } + if decodeJSON(part, &t) == nil && t.Type == "image_url" { + images = append(images, slot{i, j}) + } + } + } + if len(images) <= mistralMaxImages { + return body + } + text, _ := marshalPlain(map[string]string{"type": "text", "text": mistralImagesLeft}) + touched := map[int]bool{} + for _, s := range images[:len(images)-mistralMaxImages] { + lists[s.msg][s.part] = text + touched[s.msg] = true + } + for i := range touched { + parsed[i]["content"], _ = marshalPlain(lists[i]) + nb, err := marshalPlain(parsed[i]) + if err != nil { + return body + } + msgs[i] = nb + } + q["messages"], _ = marshalPlain(msgs) + nb, err := marshalPlain(q) + if err != nil { + return body + } + return nb +} diff --git a/internal/gateway/mistral_images_test.go b/internal/gateway/mistral_images_test.go new file mode 100644 index 000000000..44c405962 --- /dev/null +++ b/internal/gateway/mistral_images_test.go @@ -0,0 +1,127 @@ +package gateway + +import ( + "bytes" + "fmt" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +const mistralTooMany = `{"object":"error","message":"Total number of images exceeds the maximum allowed of 20.","type":"invalid_request_error","param":null,"code":null}` + +// mistralImageRefuse answers as Mistral does a request with more than 20 +// images (regain4125 on X). +func mistralImageRefuse(body []byte) (int, string) { + if bytes.Count(body, []byte(`data:image/png`)) > 20 { + return 400, mistralTooMany + } + return 0, "" +} + +// shots is n turns of a Codex conversation that each read one screenshot, +// as a Chat client sends them. +func chatShots(n int) string { + var b strings.Builder + b.WriteString(`{"model":"m1","stream":false,"messages":[`) + for i := 0; i < n; i++ { + if i > 0 { + b.WriteString(",") + } + fmt.Fprintf(&b, `{"role":"user","content":[{"type":"text","text":"shot %d"},{"type":"image_url","image_url":{"url":"data:image/png;base64,AAAA%d"}}]}`, i, i) + } + b.WriteString(`]}`) + return b.String() +} + +func responsesShots(n int) string { + var b strings.Builder + b.WriteString(`{"model":"m1","stream":false,"input":[`) + for i := 0; i < n; i++ { + if i > 0 { + b.WriteString(",") + } + fmt.Fprintf(&b, `{"type":"message","role":"user","content":[{"type":"input_text","text":"shot %d"},{"type":"input_image","image_url":"data:image/png;base64,AAAA%d"}]}`, i, i) + } + b.WriteString(`]}`) + return b.String() +} + +func sentImages(f *fake) int { return bytes.Count(f.got, []byte(`data:image/png`)) } + +const mistralImgStreamOK = "data: {\"id\":\"c1\",\"object\":\"chat.completion.chunk\",\"model\":\"m1\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"No.\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n" + +// replyFor is a fake's good reply on a route: whole for Chat, streamed for +// the Responses route, which the gateway asks its Chat upstream to stream. +func replyFor(path string) (string, string) { + if path == "/v1/responses" { + return mistralImgStreamOK, "text/event-stream" + } + return chatWholeOK, "application/json" +} + +// Past 20 images a request to Mistral loses its oldest ones to a short +// text, on the Chat route and on the Responses route Codex uses; the +// newest 20 and every turn's text stay. The same conversation to another +// vendor goes with every image, and one of 20 or fewer is untouched. +func TestMistralImageLimit(t *testing.T) { + for _, route := range []struct { + name, path string + proto provider.Protocol + body func(int) string + }{ + {"chat", "/v1/chat/completions", provider.Chat, chatShots}, + {"responses", "/v1/responses", provider.Chat, responsesShots}, + } { + t.Run(route.name, func(t *testing.T) { + reply, ctype := replyFor(route.path) + f := &fake{t: t, reply: reply, ctype: ctype, refuse: mistralImageRefuse} + up := setup(t, route.proto, f) + if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, + Preset: "mistral", Chat: up.URL + "/v1"}); err != nil { + t.Fatal(err) + } + srv := New() + code, body := postTo(t, srv, route.path, route.body(26)) + if code != 200 { + t.Fatalf("%d: %s", code, body) + } + if n := sentImages(f); n != 20 { + t.Errorf("%d images sent, want 20", n) + } + sent := string(f.got) + for _, want := range []string{"shot 0", "shot 5", "shot 25", "AAAA25", "AAAA6"} { + if !strings.Contains(sent, want) { + t.Errorf("sent lacks %q: %s", want, sent) + } + } + if strings.Contains(sent, `AAAA5"`) || !strings.Contains(sent, mistralImagesLeft) { + t.Errorf("oldest image kept or no placeholder: %s", sent) + } + // within the limit: unchanged + f.calls = 0 + if code, _ := postTo(t, srv, route.path, route.body(20)); code != 200 || sentImages(f) != 20 || strings.Contains(string(f.got), mistralImagesLeft) { + t.Errorf("20 images: %s", f.got) + } + }) + } + + t.Run("another vendor", func(t *testing.T) { + f := &fake{t: t, reply: chatWholeOK, ctype: "application/json"} + up := setup(t, provider.Chat, f) + if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, + Chat: up.URL + "/v1"}); err != nil { + t.Fatal(err) + } + code, body := postTo(t, New(), "/v1/chat/completions", chatShots(26)) + if code != 200 || sentImages(f) != 26 || strings.Contains(string(f.got), mistralImagesLeft) { + t.Errorf("%d: %d images, %s", code, sentImages(f), body) + } + f.reply, f.ctype = mistralImgStreamOK, "text/event-stream" + code, body = postTo(t, New(), "/v1/responses", responsesShots(26)) + if code != 200 || sentImages(f) != 26 { + t.Errorf("responses %d: %d images, %s", code, sentImages(f), body) + } + }) +}