diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 2a8428a47..ed5f50713 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -1036,6 +1036,48 @@ user group and auto group, over Chat, Responses and Messages) and `TestImageRefused` ([`vision_refused_test.go`](../../internal/gateway/vision_refused_test.go)). +## An image the describer can't describe + +`seer` names one describer, and before kelvinjason11 on X ("图片识别好像只支持一个模型识别 没有fallback") that was the only one asked: when it +failed (a 5xx, out of its allowance, a timeout, an image it turned away, an +empty answer) the latest turn's image failed the request, though other +models that see were enabled. `describe` now asks through `describeWith`: +the describer first, always, and when it fails, the next model that sees, +as `AutoVision` ranks them (`seersRanked`, the ranking `autoVision` takes +its first from), passing over the models already asked and any that +turned an image away (`sightRefused`). Up to `visionTries` (3) models are +asked, within `visionWaitMost` all told (each try is given what is left, +`askVisionWith`'s `most`). A model out of its allowance is not asked in +another's place: `seersRanked` puts those last, so the first being out +means every one is. A request whose context ended (the agent canceled it) +asks no other. + +- The description's header names the model that described it (`seenBody`, + `sight.by`). +- The Routing row of a description asked in another's place carries + `CallFor.Instead` (the one asked before it), `Why` (its error) and + `Picked` (it was Settings' pick), and says so (`kindWhy`), as a search + in another searcher's place does. Each try is a row of its own. +- When none answers, the error is the first's reason as before, then + "nor could X, asked in its place: why" for each other one + (`visionFailed`). +- `sights` keeps a description under the describer asked first, whichever + model answered: the image sent again next turn is asked of no one, and a + new image is asked of the pick first again, so a pick that failed once is + not given up for good. A failure is still not kept. + +This differs from a searcher named in Settings, which gives way to no other +provider: a failed search still leaves the search APIs and the model's own +answer, while an image that isn't described fails the turn. + +Covered by `TestPickedDescriberThatFailsGivesWayToTheNextThatSees`, +`TestAutoDescriberThatFailsGivesWayToTheNext`, +`TestNoDescriberAnswersNamesEach`, +`TestPickedDescriberThatAnswersIsTheOnlyOneAsked`, +`TestCanceledDescriptionAsksNoOther` +([`vision_fallback_test.go`](../../internal/gateway/vision_fallback_test.go)) +and `vision-instead.test.cjs`. + ## Image recognition as an MCP server `VisionMCPPath`, `/mcp/magpie/vision`, serves the model that describes @@ -1046,8 +1088,9 @@ is answered, guarded and Origin-checked the same way, with a 32 MB body so an image fits as a data URL, and each call reserves the calling key's limit (`budget.Reserve`). The tool takes `image` and an optional `prompt`. With no prompt it is described as a model's image is (`describe`, the same cache and -`visionSystem`); with one, `askVisionWith` asks the prompt beside it under -`visionAskSystem`. `image` is an http(s) URL or a `data:image/…;base64,` URL, +`visionSystem`); with one, `describeWith` asks the prompt beside it under +`visionAskSystem`, with the same fallback as a description (see "An image +the describer can't describe"). `image` is an http(s) URL or a `data:image/…;base64,` URL, passed on as they are, or an absolute file path (`~/` and `file://` taken), read into a data URL up to 20 MB when `http.DetectContentType` says it is an image. A path is read only for a `local` caller: another machine's path @@ -1167,7 +1210,9 @@ agents what magpie offers, don't flip with a window. Such a pick isn't asked: `askVisionWith` (`autoSpent`) answers with the reason and when it is back, and `modelSearch` (`searcherSpent`) skips it, puts spent searchers after the others and joins the reason into its error. A model named in -Settings is asked as before, and a searcher named there is not handed on +Settings is asked as before (an image it can't describe goes on to the next +model that sees, see "An image the describer can't describe"), and a +searcher named there is not handed on to another provider when it fails (see "A searcher that fails or finds nothing"). Image and video generation (`AutoDrawer`, `AutoVideomaker`) are not held this way. diff --git a/internal/gateway/vision.go b/internal/gateway/vision.go index 48200b08f..df39781d2 100644 --- a/internal/gateway/vision.go +++ b/internal/gateway/vision.go @@ -218,6 +218,25 @@ func AutoVision() string { // autoVision is AutoVision's pick, and whether it has allowance left. func autoVision() (string, bool) { + if r := seersRanked(nil); len(r) > 0 { + return r[0].model, r[0].ready + } + return "", false +} + +// rankedSeer is a model seersRanked names, and whether it has allowance. +type rankedSeer struct { + model string + ready bool +} + +// seersRanked is each switched-on provider's small model that sees, in +// the order AutoVision picks among them: allowance left first, then a +// Claude account's, a Codex account's, an API key's, another account's, +// then the cheaper, then the provider listed first. A model skip holds is +// passed over for the provider's next one (the describers a failed +// description already asked, describeWith). +func seersRanked(skip func(string) bool) []rankedSeer { tier := func(p provider.Provider) int { switch { case p.Account != nil && p.Account.Agent == "claude": @@ -229,29 +248,47 @@ func autoVision() (string, bool) { } return 3 } - best, bestTier, bestCost, bestReady := "", 0, 0.0, false + type ranked struct { + rankedSeer + tier int + cost float64 + } + var rs []ranked for _, p := range provider.All() { if !p.On() || p.DecideOnly() { continue } - t := tier(p) - if bestReady && t > bestTier { + cs := keptSmallCands(p, "sees", seesAt(p.ID)) + if skip != nil { + cs = slices.DeleteFunc(slices.Clone(cs), func(c smallCand) bool { return skip(p.ID + "/" + c.id) }) + } + c, ready := smallReadyOf(p, cs, provider.Chat) + if c.id == "" { continue } - m, cost, ready := smallModelWhere(p, "sees", seesAt(p.ID)) - if m == "" { - continue - } - switch { - case best == "", ready && !bestReady: - case ready != bestReady, t > bestTier: - continue - case t == bestTier && cost >= bestCost: - continue - } - best, bestTier, bestCost, bestReady = p.ID+"/"+m, t, cost, ready + rs = append(rs, ranked{rankedSeer{p.ID + "/" + c.id, ready}, tier(p), c.cost}) } - return best, bestReady + slices.SortStableFunc(rs, func(a, b ranked) int { + switch { + case a.ready != b.ready: + if a.ready { + return -1 + } + return 1 + case a.tier != b.tier: + return a.tier - b.tier + case a.cost < b.cost: + return -1 + case a.cost > b.cost: + return 1 + } + return 0 + }) + out := make([]rankedSeer, len(rs)) + for i, r := range rs { + out[i] = r.rankedSeer + } + return out } // autoSpent is why AutoVision's model isn't asked to describe an image: @@ -307,13 +344,21 @@ func seesAt(pid string) func(catalog.Model) bool { type sight struct { done chan struct{} text string + by string // the model that described it: model, or one in its place err error } // describe is what model says of the image at src, asked once for each // image: a request that sends it again, or sends it while it is being -// described, is given the same description. -func (s *Server) describe(ctx context.Context, model, src string) (string, error) { +// described, is given the same description. by is the model that +// described it: model, or the next that sees when model couldn't +// (describeWith). +// +// A description is kept under model, whichever described it: the image +// sent again on the next turn isn't asked of anyone, while a new image is +// asked of model first again, so a pick that failed once is tried on each +// new image and not given up for good (kelvinjason11 on X). +func (s *Server) describe(ctx context.Context, model, src string) (text, by string, err error) { // a level picked since is asked again, not given what was said at the last sum := sha256.Sum256([]byte(model + "\x00" + visionEffort(model) + "\x00" + src)) key := hex.EncodeToString(sum[:]) @@ -328,9 +373,13 @@ func (s *Server) describe(ctx context.Context, model, src string) (string, error s.sightMu.Unlock() select { case <-e.done: - return e.text, e.err + by := e.by + if by == "" { + by = model + } + return e.text, by, e.err case <-ctx.Done(): - return "", ctx.Err() + return "", model, ctx.Err() } } if s.sights == nil { @@ -344,7 +393,7 @@ func (s *Server) describe(ctx context.Context, model, src string) (string, error s.sightOrder = s.sightOrder[1:] } s.sightMu.Unlock() - e.text, e.err = s.askVision(ctx, model, src) + e.text, e.by, e.err = s.describeWith(ctx, model, src, visionSystem, "Describe this image.") if e.err != nil { // a failure isn't kept: the next request asks again s.sightMu.Lock() @@ -354,22 +403,118 @@ func (s *Server) describe(ctx context.Context, model, src string) (string, error s.sightMu.Unlock() } close(e.done) - return e.text, e.err + return e.text, e.by, e.err +} + +// visionTries is how many models are asked about one image, the first +// with those in its place. +const visionTries = 3 + +// describeWith asks model about the image at src (askVisionWith), and +// when it fails, the next model that sees, as AutoVision ranks them, up +// to visionTries in all and visionWaitMost all told. by is the model that +// answered. kelvinjason11 on X: the one model picked to describe images +// failing failed every turn with an image, though other models that see +// were enabled. +// +// The model picked in Settings is always asked first; the others are +// asked only once it fails, and the Routing view's row of the one that +// answered names the one asked before it and why (CallFor.Instead). A +// model out of its allowance isn't asked in another's place. A request +// its agent canceled asks no other. +func (s *Server) describeWith(ctx context.Context, model, src, system, text string) (said, by string, err error) { + deadline := time.Now().Add(visionWaitMost) + tried := []string{model} + var fails []visionTry + ask, askCtx := model, ctx + for { + said, err = s.askVisionWith(askCtx, ask, src, system, text, time.Until(deadline)) + if err == nil { + return said, ask, nil + } + fails = append(fails, visionTry{ask, err}) + if ctx.Err() != nil || len(tried) >= visionTries || !time.Now().Before(deadline) { + break + } + // those with allowance go first, so the first is out of it only + // when every one is + r := seersRanked(func(m string) bool { + if slices.Contains(tried, m) { + return true + } + pid, id, _ := strings.Cut(m, "/") + return s.sightRefused(pid, id) + }) + if len(r) == 0 || !r[0].ready { + break + } + next := r[0].model + askCtx = describingInstead(ctx, ask, model, err) + tried = append(tried, next) + ask = next + } + return "", model, visionFailed(fails) +} + +// visionTry is a model asked about an image, and why it didn't answer. +type visionTry struct { + model string + err error +} + +// visionFailed is why no model asked about an image answered: the first +// one's reason as it was, then each asked in its place, by name. +type visionFailed []visionTry + +func (f visionFailed) Error() string { + var b strings.Builder + for i, t := range f { + if i == 0 { + b.WriteString(t.err.Error()) + continue + } + fmt.Fprintf(&b, "; nor could %s, asked in its place: %v", t.model, t.err) + } + return b.String() +} + +func (f visionFailed) Unwrap() []error { + out := make([]error, len(f)) + for i, t := range f { + out[i] = t.err + } + return out +} + +// describingInstead is ctx for a model asked about an image in failed's +// place: the Routing view's row says which was asked before and why, and +// whether that was the one picked in Settings (first, as Settings names it). +func describingInstead(ctx context.Context, failed, first string, err error) context.Context { + f, _ := ctx.Value(describeForKey{}).(describeFor) + g := CallFor{} + if f.call != nil { + g = *f.call + } + g.Instead, g.Why = failed, err.Error() + g.Picked = failed == first && !autoDescribes() + f.call = &g + return context.WithValue(ctx, describeForKey{}, f) } // askVision asks model through the gateway itself, as a client would, what // the image at src shows. func (s *Server) askVision(ctx context.Context, model, src string) (string, error) { - return s.askVisionWith(ctx, model, src, visionSystem, "Describe this image.") + return s.askVisionWith(ctx, model, src, visionSystem, "Describe this image.", visionWaitMost) } // askVisionWith asks model about the image at src: system, and the user's -// text beside the image. -func (s *Server) askVisionWith(ctx context.Context, model, src, system, text string) (string, error) { +// text beside the image. most is how long it may take, the waits for a +// slot or a resting provider with it: what describeWith has left. +func (s *Server) askVisionWith(ctx context.Context, model, src, system, text string, most time.Duration) (string, error) { if err := autoSpent(model); err != nil { return "", err } - ctx, cancel := sideDeadline(context.WithValue(ctx, describingKey{}, true), "image description", visionTimeout, visionWaitMost) + ctx, cancel := sideDeadline(context.WithValue(ctx, describingKey{}, true), "image description", visionTimeout, most) defer cancel() req := map[string]any{ "model": model, @@ -453,8 +598,8 @@ func (s *Server) seenBody(ctx context.Context, proto provider.Protocol, body []b return nil, nil }) type result struct { - text string - err error + text, by string + err error } results := make([]result, len(srcs)) var wg sync.WaitGroup @@ -465,8 +610,8 @@ func (s *Server) seenBody(ctx context.Context, proto provider.Protocol, body []b defer wg.Done() slots <- struct{}{} defer func() { <-slots }() - text, err := s.describe(ctx, model, src) - results[i] = result{text, err} + text, by, err := s.describe(ctx, model, src) + results[i] = result{text, by, err} }() } wg.Wait() @@ -489,7 +634,7 @@ func (s *Server) seenBody(ctx context.Context, proto provider.Protocol, body []b return textBlock(proto, "[Image omitted: this model accepts text only, and the image couldn't be described.]"), nil } // on its own lines: a translation may join it to the text around it - return textBlock(proto, "\n[Image, as "+model+" describes it for this model, which can't see images:]\n"+r.text+"\n[End of the image's description]\n"), nil + return textBlock(proto, "\n[Image, as "+r.by+" describes it for this model, which can't see images:]\n"+r.text+"\n[End of the image's description]\n"), nil }) } diff --git a/internal/gateway/vision_fallback_test.go b/internal/gateway/vision_fallback_test.go new file mode 100644 index 000000000..83611fb10 --- /dev/null +++ b/internal/gateway/vision_fallback_test.go @@ -0,0 +1,221 @@ +package gateway + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// twoEyed is eyed with a second provider whose model sees, other/bigeye, +// on an upstream of its own; vision names the Image recognition model +// picked in Settings ("" for magpie's own pick). +func twoEyed(t *testing.T, vision string) (*Server, *eyeUp, *eyeUp) { + t.Helper() + s, u := eyed(t) + u2 := &eyeUp{} + srv := httptest.NewServer(u2) + t.Cleanup(srv.Close) + if err := provider.Save(provider.Provider{ID: "other", Name: "Other", Chat: srv.URL + "/v1", Key: "key", Models: []string{"bigeye"}}); err != nil { + t.Fatal(err) + } + if err := catalog.SaveLive("other", srv.URL+"/v1", []catalog.Model{{ID: "bigeye", Images: true, ImageInput: imageInputBool(true)}}); err != nil { + t.Fatal(err) + } + st := settings.Load() + st.Vision = vision + if err := settings.Save(st); err != nil { + t.Fatal(err) + } + return s, u, u2 +} + +func failing(u *eyeUp, fail bool) { + u.mu.Lock() + u.fail = fail + u.mu.Unlock() +} + +// the Routing row of the description model answered +func visionRow(t *testing.T, s *Server, model string) *CallFor { + t.Helper() + for _, r := range s.Trace(context.Background(), 0, 0).Routes { + if r.Kind == "vision" && r.Model == model && r.Status == 200 { + return r.For + } + } + t.Fatalf("no answered vision row for %s in %+v", model, s.Trace(context.Background(), 0, 0).Routes) + return nil +} + +// kelvinjason11 on X: "图片识别好像只支持一个模型识别 没有fallback". The +// Image recognition model picked in Settings failing (a 500) failed the +// turn, though another model that sees was enabled. It is described by +// that one instead; the pick is still asked first for each new image. +func TestPickedDescriberThatFailsGivesWayToTheNextThatSees(t *testing.T) { + s, u, u2 := twoEyed(t, "probe/eye") + failing(u, true) + code, body := postAs(t, s, "", pastedImage) + if code != 200 { + t.Fatalf("picked describer down: %d %s", code, body) + } + if got := u.sent("text"); len(got) != 1 || !strings.Contains(got[0], "HELLO") || !strings.Contains(got[0], "other/bigeye describes it") { + t.Fatalf("text model was sent %v", got) + } + // routing tries a 500 again on its own before the description fails + asked := len(u.sent("eye")) + if asked == 0 || len(u2.sent("bigeye")) != 1 { + t.Fatalf("eye asked %d times, bigeye %d", asked, len(u2.sent("bigeye"))) + } + f := visionRow(t, s, "other/bigeye") + if f == nil || f.Instead != "probe/eye" || !f.Picked || !strings.Contains(f.Why, "eye is down") || f.Model != "probe/text" { + t.Fatalf("the answering description's row is for %+v", f) + } + // the same image sent again is described already, by whichever model + if code, body := postAs(t, s, "", pastedImage); code != 200 || len(u.sent("eye")) != asked || len(u2.sent("bigeye")) != 1 { + t.Fatalf("image sent again: %d %s; eye asked %d, bigeye %d", code, body, len(u.sent("eye")), len(u2.sent("bigeye"))) + } + // a new image asks the pick first again, and it answers once it is back + failing(u, false) + if code, body := postAs(t, s, "", strings.Replace(pastedImage, "aGVsbG8=", "d29ybGQ=", 1)); code != 200 || len(u.sent("eye")) != asked+1 || len(u2.sent("bigeye")) != 1 { + t.Fatalf("new image: %d %s; eye asked %d, bigeye %d", code, body, len(u.sent("eye")), len(u2.sent("bigeye"))) + } +} + +// magpie's own pick failing gives way to its next one too. +func TestAutoDescriberThatFailsGivesWayToTheNext(t *testing.T) { + s, u, u2 := twoEyed(t, "") + first, next, down := AutoVision(), "other/bigeye", u + if first == "other/bigeye" { + next, down = "probe/eye", u2 + } + failing(down, true) + if code, body := postAs(t, s, "", pastedImage); code != 200 { + t.Fatalf("auto describer down: %d %s", code, body) + } + if got := u.sent("text"); len(got) != 1 || !strings.Contains(got[0], next+" describes it") { + t.Fatalf("text model was sent %v", got) + } + if f := visionRow(t, s, next); f == nil || f.Instead != first || f.Picked { + t.Fatalf("the answering description's row is for %+v", f) + } +} + +// Every model that sees failing: the error names each one and why. +func TestNoDescriberAnswersNamesEach(t *testing.T) { + s, u, u2 := twoEyed(t, "probe/eye") + failing(u, true) + failing(u2, true) + code, body := postAs(t, s, "", pastedImage) + if code != 502 || !strings.Contains(body, "probe/eye couldn't describe the image for it: Probe: eye is down") || !strings.Contains(body, "nor could other/bigeye, asked in its place: Other: eye is down") { + t.Fatalf("every describer down: %d %s", code, body) + } + if len(u.sent("text")) != 0 || len(u.sent("eye")) == 0 || len(u2.sent("bigeye")) == 0 { + t.Fatalf("text sent %d, eye asked %d, bigeye %d", len(u.sent("text")), len(u.sent("eye")), len(u2.sent("bigeye"))) + } +} + +// The picked model answering is all that is asked. +func TestPickedDescriberThatAnswersIsTheOnlyOneAsked(t *testing.T) { + s, u, u2 := twoEyed(t, "probe/eye") + if code, body := postAs(t, s, "", pastedImage); code != 200 { + t.Fatalf("%d %s", code, body) + } + if len(u.sent("eye")) != 1 || len(u2.sent("bigeye")) != 0 { + t.Fatalf("eye asked %d times, bigeye %d", len(u.sent("eye")), len(u2.sent("bigeye"))) + } + if got := u.sent("text"); len(got) != 1 || !strings.Contains(got[0], "probe/eye describes it") { + t.Fatalf("text model was sent %v", got) + } + if f := visionRow(t, s, "probe/eye"); f == nil || f.Instead != "" { + t.Fatalf("the description's row is for %+v", f) + } +} + +// heldEye holds a description until its request ends, saying when one +// has arrived. +type heldEye struct { + eyeUp + arrived chan struct{} +} + +func (u *heldEye) ServeHTTP(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + if strings.HasSuffix(modelOf(body), "eye") { + u.arrived <- struct{}{} + <-r.Context().Done() + return + } + r.Body = io.NopCloser(strings.NewReader(string(body))) + u.eyeUp.ServeHTTP(w, r) +} + +// A request its agent canceled asks no other model to describe its image. +func TestCanceledDescriptionAsksNoOther(t *testing.T) { + fresh(t) + u := &heldEye{arrived: make(chan struct{}, 1)} + up := httptest.NewServer(u) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "probe", Name: "Probe", Chat: up.URL + "/v1", Key: "key", Models: []string{"text", "eye"}}); err != nil { + t.Fatal(err) + } + if err := catalog.SaveLive("probe", up.URL+"/v1", []catalog.Model{ + {ID: "text", ImageInput: imageInputBool(false)}, + {ID: "eye", Images: true, ImageInput: imageInputBool(true)}, + }); err != nil { + t.Fatal(err) + } + u2 := &eyeUp{} + srv := httptest.NewServer(u2) + t.Cleanup(srv.Close) + if err := provider.Save(provider.Provider{ID: "other", Name: "Other", Chat: srv.URL + "/v1", Key: "key", Models: []string{"bigeye"}}); err != nil { + t.Fatal(err) + } + if err := catalog.SaveLive("other", srv.URL+"/v1", []catalog.Model{{ID: "bigeye", Images: true, ImageInput: imageInputBool(true)}}); err != nil { + t.Fatal(err) + } + st := settings.Load() + st.Vision = "probe/eye" + if err := settings.Save(st); err != nil { + t.Fatal(err) + } + s := New() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + done := make(chan int, 1) + go func() { + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(pastedImage)).WithContext(ctx)) + done <- rec.Code + }() + select { + case <-u.arrived: + case <-time.After(10 * time.Second): + t.Fatal("the picked describer was never asked") + } + cancel() + select { + case <-done: + case <-time.After(10 * time.Second): + t.Fatal("the canceled request never ended") + } + if n := len(u2.sent("bigeye")); n != 0 { + t.Fatalf("a canceled request asked bigeye %d times", n) + } + // not even begun: a try on the canceled context is a row of its own + for _, r := range s.Trace(context.Background(), 0, 0).Routes { + if r.Kind == "vision" && r.Model == "other/bigeye" { + t.Fatalf("a canceled request had bigeye describe: %+v", r) + } + } + if n := len(u.sent("text")); n != 0 { + t.Fatalf("a canceled request reached the text model %d times", n) + } +} diff --git a/internal/gateway/vision_mcp.go b/internal/gateway/vision_mcp.go index bda19b20e..823516400 100644 --- a/internal/gateway/vision_mcp.go +++ b/internal/gateway/vision_mcp.go @@ -131,9 +131,9 @@ func (s *Server) visionMCPRun(r *http.Request, image, prompt string) (string, er ctx := context.WithValue(r.Context(), describeForKey{}, describeFor{call: &CallFor{Agent: callerOf(r).agent, Missing: VisionMissing(), MCP: true}}) var said string if prompt == "" { - said, err = s.describe(ctx, model, src) + said, _, err = s.describe(ctx, model, src) } else { - said, err = s.askVisionWith(ctx, model, src, visionAskSystem, prompt) + said, _, err = s.describeWith(ctx, model, src, visionAskSystem, prompt) } if err != nil { if r.Context().Err() == nil { diff --git a/internal/gateway/vision_test.go b/internal/gateway/vision_test.go index 427244f99..6b0782e6b 100644 --- a/internal/gateway/vision_test.go +++ b/internal/gateway/vision_test.go @@ -191,15 +191,16 @@ func TestGroupsTextOnlyMemberIsGivenTheDescription(t *testing.T) { func TestDescriberThatCantSeeIsntAskedToDescribe(t *testing.T) { s, u := eyed(t) // the setting names a text-only model: its own request is turned away, - // not described by itself again and again + // not described by itself again and again, and the next model that + // sees describes the image in its place (kelvinjason11 on X) st := settings.Load() st.Vision = "probe/text" if err := settings.Save(st); err != nil { t.Fatal(err) } code, body := postAs(t, s, "", `{"model":"probe/text","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,aGVsbG8="}}]}]}`) - if code != 502 || len(u.sent("text")) != 0 { - t.Fatalf("%d %s; text model sent %d", code, body, len(u.sent("text"))) + if got := u.sent("text"); code != 200 || len(got) != 1 || !strings.Contains(got[0], "probe/eye describes it") { + t.Fatalf("%d %s; text model sent %v", code, body, got) } } diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index 23d5b8e24..2f6839a79 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -3153,6 +3153,19 @@ function routingPage(part) { // went to Codex's GPT, and nothing said why or where to change it) // the Image recognition model the user picked is missing: the one // magpie picks described in its place, and the row says so + // the model asked first couldn't describe the image, and this one + // did in its place: say which and why (kelvinjason11 on X: one + // describer failing failed every turn with an image) + if (r.kind === "vision" && r.for?.instead) { + const f = r.for; + const whom = f.mcp ? t("{agent}'s call to magpie's analyze_image MCP tool", { agent: agentName(f.agent) }) + : f.model ? t("{agent}'s {model}", { agent: agentName(f.agent), model: f.model }) + : t("a model that can't see images"); + const why = f.why || t("it failed"); + return f.picked + ? t("{failed}, the Image recognition model picked in Settings › Models, couldn't describe an image for {whom}: {why}. So magpie had {describer}, the next model it can use that sees, describe it in its place. Not a turn of the conversation.", { failed: f.instead, whom, why, describer: r.model }) + : t("{failed}, the model magpie picked to describe images, couldn't describe an image for {whom}: {why}. So magpie had {describer}, the next model it can use that sees, describe it in its place. Not a turn of the conversation.", { failed: f.instead, whom, why, describer: r.model }); + } // the agent called magpie's image recognition MCP server itself if (r.kind === "vision" && r.for?.mcp) return t("{agent} called magpie's analyze_image MCP tool: {describer} looked at the image for it. Not a turn of the conversation.", { agent: agentName(r.for.agent), describer: r.model }); if (r.kind === "vision" && r.for?.missing) return t("{picked}, the Image recognition model picked in Settings, isn't set up any more, so magpie had {describer}, its automatic choice, describe an image for {agent}'s {model} in its place. Pick another in Settings › Models › Image recognition. Not a turn of the conversation.", { picked: r.for.missing, agent: agentName(r.for.agent), model: r.for.model, describer: r.model }); diff --git a/internal/gui/assets/plugins/routing/i18n.js b/internal/gui/assets/plugins/routing/i18n.js index ef5b873cb..b29d6a759 100644 --- a/internal/gui/assets/plugins/routing/i18n.js +++ b/internal/gui/assets/plugins/routing/i18n.js @@ -13,6 +13,10 @@ magpie.strings({ "heard from in the last 30 days": "近 30 天有请求", "The subagent effort set in magpie is {effort}; the model's supported levels and a routing group's fixed member effort still apply.": "magpie 为子代理设定的推理强度是 {effort};仍按模型支持的等级适配,并保留路由组成员的固定强度。", "{agent}'s call to magpie's web_search MCP tool": "{agent} 对 magpie 的 web_search MCP 工具的调用", + "{agent}'s call to magpie's analyze_image MCP tool": "{agent} 对 magpie 的 analyze_image MCP 工具的调用", + "a model that can't see images": "一个看不了图片的模型", + "{failed}, the Image recognition model picked in Settings › Models, couldn't describe an image for {whom}: {why}. So magpie had {describer}, the next model it can use that sees, describe it in its place. Not a turn of the conversation.": "{failed} 是在 设置 › 模型 里选的识图模型,但它没能为 {whom} 描述图片:{why}。所以 magpie 改让下一个可用的识图模型 {describer} 来描述。不属于对话轮次。", + "{failed}, the model magpie picked to describe images, couldn't describe an image for {whom}: {why}. So magpie had {describer}, the next model it can use that sees, describe it in its place. Not a turn of the conversation.": "{failed} 是 magpie 自动选的识图模型,但它没能为 {whom} 描述图片:{why}。所以 magpie 改让下一个可用的识图模型 {describer} 来描述。不属于对话轮次。", "{agent}'s {model}": "{agent} 的 {model}", "a model that can't search the web by itself": "一个自己不能联网搜索的模型", "{failed}, the searcher picked in Settings › Models › Web search, didn't search for {whom}: {why}. So magpie had {searcher}, the next searcher it can use, search in its place. Not a turn of the conversation.": "{failed} 是在 设置 › 模型 › 联网搜索 里选的代搜模型,但它没能为 {whom} 搜索:{why}。所以 magpie 改让下一个可用的代搜模型 {searcher} 来搜。不属于对话轮次。", @@ -613,6 +617,10 @@ magpie.strings({ "The subagent effort set in magpie is {effort}; the model's supported levels and a routing group's fixed member effort still apply.": "magpie 為子代理設定的推理強度是 {effort};仍按模型支援的等級適配,並保留路由群組成員的固定強度。", "{agent} guessed your next message for its composer by itself, reading the whole conversation again. Not a turn of the conversation; Codex composer predictions, under Settings in Codex's row on the Agents page, picks its model, and Codex's Settings › General › Show predictions turns it off.": "{agent} 自行為輸入框猜測你的下一則訊息,每次都把整段對話重讀一遍。不屬於對話輪次;在 Agent 頁 Codex 那一列的設定裡,用 Codex 輸入框預測 選它用的模型,在 Codex 的 設定 › 一般 › 顯示預測內容 裡可以關掉。", "{agent}'s call to magpie's web_search MCP tool": "{agent} 對 magpie 的 web_search MCP 工具的呼叫", + "{agent}'s call to magpie's analyze_image MCP tool": "{agent} 對 magpie 的 analyze_image MCP 工具的呼叫", + "a model that can't see images": "一個看不了圖片的模型", + "{failed}, the Image recognition model picked in Settings › Models, couldn't describe an image for {whom}: {why}. So magpie had {describer}, the next model it can use that sees, describe it in its place. Not a turn of the conversation.": "{failed} 是在 設定 › 模型 裡選的識圖模型,但它沒能為 {whom} 描述圖片:{why}。所以 magpie 改讓下一個可用的識圖模型 {describer} 來描述。不屬於對話輪次。", + "{failed}, the model magpie picked to describe images, couldn't describe an image for {whom}: {why}. So magpie had {describer}, the next model it can use that sees, describe it in its place. Not a turn of the conversation.": "{failed} 是 magpie 自動選的識圖模型,但它沒能為 {whom} 描述圖片:{why}。所以 magpie 改讓下一個可用的識圖模型 {describer} 來描述。不屬於對話輪次。", "{agent}'s {model}": "{agent} 的 {model}", "a model that can't search the web by itself": "一個自己不能聯網搜尋的模型", "{failed}, the searcher picked in Settings › Models › Web search, didn't search for {whom}: {why}. So magpie had {searcher}, the next searcher it can use, search in its place. Not a turn of the conversation.": "{failed} 是在 設定 › 模型 › 聯網搜尋 裡選的代搜模型,但它沒能為 {whom} 搜尋:{why}。所以 magpie 改讓下一個可用的代搜模型 {searcher} 來搜。不屬於對話輪次。", @@ -1211,6 +1219,10 @@ magpie.strings({ "heard from in the last 30 days": "過去 30 日にリクエストあり", "The subagent effort set in magpie is {effort}; the model's supported levels and a routing group's fixed member effort still apply.": "magpie で設定したサブエージェントの推論レベルは {effort} です。モデルが対応するレベルへの調整と、ルーティンググループのメンバーに固定されたレベルは引き続き適用されます。", "{agent}'s call to magpie's web_search MCP tool": "{agent} による magpie の web_search MCP ツールの呼び出し", + "{agent}'s call to magpie's analyze_image MCP tool": "{agent} による magpie の analyze_image MCP ツールの呼び出し", + "a model that can't see images": "画像を見られないモデル", + "{failed}, the Image recognition model picked in Settings › Models, couldn't describe an image for {whom}: {why}. So magpie had {describer}, the next model it can use that sees, describe it in its place. Not a turn of the conversation.": "設定 › モデル で選んだ画像認識モデル {failed} は {whom} のための画像を説明できませんでした:{why}。そのため magpie は次に使える画像を見られるモデル {describer} に代わりに説明させました。会話のターンではありません。", + "{failed}, the model magpie picked to describe images, couldn't describe an image for {whom}: {why}. So magpie had {describer}, the next model it can use that sees, describe it in its place. Not a turn of the conversation.": "magpie が自動で選んだ画像認識モデル {failed} は {whom} のための画像を説明できませんでした:{why}。そのため magpie は次に使える画像を見られるモデル {describer} に代わりに説明させました。会話のターンではありません。", "{agent}'s {model}": "{agent} の {model}", "a model that can't search the web by itself": "自分ではウェブ検索できないモデル", "{failed}, the searcher picked in Settings › Models › Web search, didn't search for {whom}: {why}. So magpie had {searcher}, the next searcher it can use, search in its place. Not a turn of the conversation.": "設定 › モデル › ウェブ検索 で選んだ検索モデル {failed} は {whom} の代わりに検索できませんでした:{why}。そのため magpie は次に使える検索モデル {searcher} に代わりに検索させました。会話のターンではありません。", @@ -1810,6 +1822,10 @@ magpie.strings({ "heard from in the last 30 days": "in den letzten 30 Tagen gesehen", "The subagent effort set in magpie is {effort}; the model's supported levels and a routing group's fixed member effort still apply.": "Der in magpie gesetzte Reasoning-Effort der Subagenten ist {effort}; die unterstützten Stufen des Modells und die feste Stufe eines Mitglieds der Routing-Gruppe gelten weiterhin.", "{agent}'s call to magpie's web_search MCP tool": "den Aufruf von {agent} an magpies MCP-Werkzeug web_search", + "{agent}'s call to magpie's analyze_image MCP tool": "den Aufruf von {agent} an magpies MCP-Werkzeug analyze_image", + "a model that can't see images": "ein Modell, das keine Bilder sehen kann", + "{failed}, the Image recognition model picked in Settings › Models, couldn't describe an image for {whom}: {why}. So magpie had {describer}, the next model it can use that sees, describe it in its place. Not a turn of the conversation.": "{failed}, das unter Einstellungen › Modelle gewählte Bilderkennungsmodell, konnte kein Bild für {whom} beschreiben: {why}. Daher ließ magpie {describer}, das nächste nutzbare Modell, das Bilder sieht, es an seiner Stelle beschreiben. Keine Runde des Gesprächs.", + "{failed}, the model magpie picked to describe images, couldn't describe an image for {whom}: {why}. So magpie had {describer}, the next model it can use that sees, describe it in its place. Not a turn of the conversation.": "{failed}, das von magpie gewählte Modell zum Beschreiben von Bildern, konnte kein Bild für {whom} beschreiben: {why}. Daher ließ magpie {describer}, das nächste nutzbare Modell, das Bilder sieht, es an seiner Stelle beschreiben. Keine Runde des Gesprächs.", "{agent}'s {model}": "{model} von {agent}", "a model that can't search the web by itself": "ein Modell, das nicht selbst im Web suchen kann", "{failed}, the searcher picked in Settings › Models › Web search, didn't search for {whom}: {why}. So magpie had {searcher}, the next searcher it can use, search in its place. Not a turn of the conversation.": "{failed}, der unter Einstellungen › Modelle › Websuche gewählte Sucher, hat nicht für {whom} gesucht: {why}. Daher ließ magpie {searcher}, den nächsten nutzbaren Sucher, an seiner Stelle suchen. Keine Runde des Gesprächs.", diff --git a/internal/gui/tests/vision-instead.test.cjs b/internal/gui/tests/vision-instead.test.cjs new file mode 100644 index 000000000..4dc3108ea --- /dev/null +++ b/internal/gui/tests/vision-instead.test.cjs @@ -0,0 +1,119 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// An image described for a model that can't see, after the model asked +// first to describe it failed, says so in its Routing row: which model was +// asked first, for whom, why it couldn't, and which one described it in its +// place (kelvinjason11 on X: one describer failing failed every turn with +// an image). In every language, in both engines, at a narrow width too. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const words = { + en: { + picked: /probe\/eye, the Image recognition model picked in Settings › Models, couldn't describe an image for Codex's zai\/glm-5\.2: 502 upstream closed\. So magpie had other\/bigeye, the next model it can use that sees, describe it in its place\. Not a turn of the conversation\.$/, + auto: /probe\/eye, the model magpie picked to describe images, couldn't describe an image for Codex's call to magpie's analyze_image MCP tool: it failed\. So magpie had other\/bigeye/, + }, + zh: { + picked: /probe\/eye 是在 设置 › 模型 里选的识图模型,但它没能为 Codex 的 zai\/glm-5\.2 描述图片:502 upstream closed。所以 magpie 改让下一个可用的识图模型 other\/bigeye 来描述。不属于对话轮次。$/, + auto: /probe\/eye 是 magpie 自动选的识图模型,但它没能为 Codex 对 magpie 的 analyze_image MCP 工具的调用 描述图片:它出错了。/, + }, + "zh-TW": { + picked: /probe\/eye 是在 設定 › 模型 裡選的識圖模型,但它沒能為 Codex 的 zai\/glm-5\.2 描述圖片:502 upstream closed。所以 magpie 改讓下一個可用的識圖模型 other\/bigeye 來描述。不屬於對話輪次。$/, + auto: /probe\/eye 是 magpie 自動選的識圖模型,但它沒能為 Codex 對 magpie 的 analyze_image MCP 工具的呼叫 描述圖片:它出錯了。/, + }, + ja: { + picked: /設定 › モデル で選んだ画像認識モデル probe\/eye は Codex の zai\/glm-5\.2 のための画像を説明できませんでした:502 upstream closed。そのため magpie は次に使える画像を見られるモデル other\/bigeye に代わりに説明させました。会話のターンではありません。$/, + auto: /magpie が自動で選んだ画像認識モデル probe\/eye は Codex による magpie の analyze_image MCP ツールの呼び出し のための画像を説明できませんでした:エラーになりました。/, + }, + de: { + picked: /probe\/eye, das unter Einstellungen › Modelle gewählte Bilderkennungsmodell, konnte kein Bild für zai\/glm-5\.2 von Codex beschreiben: 502 upstream closed\. Daher ließ magpie other\/bigeye, das nächste nutzbare Modell, das Bilder sieht, es an seiner Stelle beschreiben\. Keine Runde des Gesprächs\.$/, + auto: /probe\/eye, das von magpie gewählte Modell zum Beschreiben von Bildern, konnte kein Bild für den Aufruf von Codex an magpies MCP-Werkzeug analyze_image beschreiben: es ist fehlgeschlagen\./, + }, +}; + +const now = new Date(); +const day = [now.getFullYear(), now.getMonth() + 1, now.getDate()].map((n) => String(n).padStart(2, "0")).join("-"); +const route = (id, f) => ({ + id, seq: id, time: new Date(now.getTime() - id * 60e3).toISOString(), agent: "magpie", model: "other/bigeye", provider: "other", + kind: "vision", for: { agent: "codex", instead: "probe/eye", ...f }, + order: [{ id: "other", provider: "other", name: "Other", who: "a@b.c", kind: "account", model: "bigeye" }], + tries: [{ id: "other", model: "bigeye", start: new Date(now.getTime() - id * 60e3).toISOString(), done: true, status: 200, ms: 900 }], + done: true, status: 200, ms: 900, tokens: 1200, +}); +// newest first: the picked describer that failed, and magpie's own pick +// that failed an agent's analyze_image call with no reason kept +const routes = [route(1, { model: "zai/glm-5.2", picked: true, why: "502 upstream closed" }), route(2, { mcp: true })]; + +function serve(lang) { + const settings = { lang, theme: "light", vision: "probe/eye", gateway: "http://127.0.0.1:3999", port: 3999 }; + const state = { + agents: [], profiles: [], settings, + clients: [{ id: "codex", name: "Codex", icon: "codex" }, { id: "magpie", name: "magpie", icon: "magpie" }], + }; + return async (r) => { + const url = new URL(r.request().url()); + const json = (data) => r.fulfill({ json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/settings") return json(settings); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) await new Promise((res) => setTimeout(res, 20e3)); + return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + } + if (url.pathname === "/api/gateway/history") { + return json({ cut: false, days: [{ day, requests: routes.length }], routes: url.searchParams.get("day") ? routes : [] }); + } + if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await r.fulfill({ body: await fs.readFile(file), contentType }); } catch { await r.fulfill({ status: 404, body: "" }); } + }; +} + +async function open(t, engine, lang, width) { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + await page.goto("http://magpie.test/?view=routing"); + return { page, errors }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + const w = words[lang]; + test(`${engine} ${lang}: an image described in place of the model asked first says which and why`, async (t) => { + for (const width of [1100, 520]) { + const { page, errors } = await open(t, engine, lang, width); + await page.locator(".rt-days .rt-day").nth(1).click(); + // each row's story, read once its own is drawn + const said = []; + for (const i of [0, 1]) { + const req = page.locator(".rt-req").nth(i); + await req.waitFor(); + await req.click(); + const h = await page.waitForFunction((prev) => { + const s = document.querySelector(".rt-steps li.kind")?.textContent.trim(); + return s && s !== prev && s; + }, said.at(-1) || ""); + said.push(await h.jsonValue()); + } + for (const want of [w.picked, w.auto]) { + assert(said.some((s) => want.test(s)), `${width}px: ${want} in\n${said.join("\n")}`); + } + assert(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth + 1), `no sideways scroll at ${width}px`); + assert.deepEqual(errors, []); + } + }); + } +}