diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index ab53adf20..549a43f78 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -609,6 +609,9 @@ func callKind(h http.Header) string { if v == "" && h.Get("User-Agent") == SearchAgent { v = "web_search" } + if v == "" && h.Get("User-Agent") == VisionAgent { + v = "vision" + } if v == "" && h.Get("x-openai-codex-luna-reserve") != "" { v = "luna_reserve" } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 2bc02b10b..cb8809506 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -983,8 +983,11 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro defer discardArchive(capture) r, telemetry := beginOTelRequest(r, call.Kind, body) defer func() { telemetry.end(call, time.Since(start).Milliseconds()) }() - if call.Kind == "web_search" { + switch call.Kind { + case "web_search": call.For = searchFor(r.Context()) + case "vision": + call.For = describedFor(r.Context()) } usage.Saw(agent) finishCapture := func() { @@ -1125,10 +1128,19 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } return seer() }) + // a model its list says nothing of is text-only to a describer, as + // agents are told: while one describes images they are told every + // model takes them, and send the images on to be described + if imageInput == nil && !isGroup && hasImage(from, body) && blindTo(p.ID, model, nil) { + if _, ok := seeing(); ok { + no := false + imageInput = &no + } + } if imageInput != nil && !*imageInput { var currentImage bool if see, ok := seeing(); ok && hasImage(from, body) { - seen, err := s.seenBody(r.Context(), from, body, see) + seen, err := s.seenBody(withDescribeFor(r.Context(), call.Agent, call.Model, sessionOf(r.Header)), from, body, see) if err != nil { call.Status, call.Error = 502, "image not described" writeError(w, from, 502, fmt.Sprintf("model %q can't see images, and %s couldn't describe the image for it: %v", call.Model, see, err)) @@ -1247,7 +1259,9 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro var seenGroup func() ([]byte, error) if isGroup && hasImage(from, body) { if see, ok := seeing(); ok { - seenGroup = sync.OnceValues(func() ([]byte, error) { return s.seenBody(r.Context(), from, body, see) }) + seenGroup = sync.OnceValues(func() ([]byte, error) { + return s.seenBody(withDescribeFor(r.Context(), call.Agent, call.Model, sessionOf(r.Header)), from, body, see) + }) } } if isGroup && seenGroup == nil { @@ -1329,25 +1343,24 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } } if isGroup { - if in := membersImageInput([]provider.Member{{Provider: c.p, Model: c.model}}, nil); in != nil && !*in { - if seenGroup != nil { - b, err := seenGroup() - if err != nil { - // only an image of the latest turn fails to be described - call.Error = "image not described" - if !last { - skipped = append(skipped, c.label()+": "+call.Error) - continue - } - see, _ := seeing() - call.Status = 502 - writeError(w, from, 502, fmt.Sprintf("model %q can't see images, and %s couldn't describe the image for it: %v", c.p.ID+"/"+c.model, see, err)) - break + in := membersImageInput([]provider.Member{{Provider: c.p, Model: c.model}}, nil) + if seenGroup != nil && blindTo(c.p.ID, c.model, in) { + b, err := seenGroup() + if err != nil { + // only an image of the latest turn fails to be described + call.Error = "image not described" + if !last { + skipped = append(skipped, c.label()+": "+call.Error) + continue } - attemptBody = b - } else { - attemptBody, _ = textOnlyBody(from, body) // omit images in prior turns and tool results + see, _ := seeing() + call.Status = 502 + writeError(w, from, 502, fmt.Sprintf("model %q can't see images, and %s couldn't describe the image for it: %v", c.p.ID+"/"+c.model, see, err)) + break } + attemptBody = b + } else if in != nil && !*in { + attemptBody, _ = textOnlyBody(from, body) // omit images in prior turns and tool results } } picked := false // the effort asked for in place of the agent's diff --git a/internal/gateway/vision.go b/internal/gateway/vision.go index 655ffb459..7d56f6724 100644 --- a/internal/gateway/vision.go +++ b/internal/gateway/vision.go @@ -63,6 +63,36 @@ func describing(ctx context.Context) bool { return v } +// describeForKey holds the request an image is described for: the Routing +// view names it by the description's row, in that request's session. +type describeForKey struct{} + +type describeFor struct { + call *CallFor + session string +} + +func withDescribeFor(ctx context.Context, agent, model, session string) context.Context { + return context.WithValue(ctx, describeForKey{}, describeFor{&CallFor{Agent: agent, Model: model}, session}) +} + +func describedFor(ctx context.Context) *CallFor { + f, _ := ctx.Value(describeForKey{}).(describeFor) + return f.call +} + +// blindTo is whether a describer is to describe images for pid/model: its +// list says it takes none (in), or says nothing and magpie counts it +// text-only — as agents were told before Vision had them told every model +// takes images (provider.Described): models.dev doesn't say it sees either. +func blindTo(pid, model string, in *bool) bool { + if in != nil { + return !*in + } + e, ok := provider.ServedEntryOf(pid + "/" + model) + return ok && !e.Images +} + // seer is the model that describes images: the Settings' Vision while it // resolves, else AutoVision's. None when Vision is off or no model sees. func seer() (string, bool) { @@ -194,6 +224,10 @@ func (s *Server) askVision(ctx context.Context, model, src string) (string, erro } r.Header.Set("Content-Type", "application/json") r.Header.Set("User-Agent", VisionAgent) + if f, _ := ctx.Value(describeForKey{}).(describeFor); f.session != "" { + // in the Routing view beside the request it describes for + r.Header.Set(SessionHeader, f.session) + } w := httptest.NewRecorder() s.serve(w, r, provider.Chat, body) if ctx.Err() != nil { diff --git a/internal/gateway/vision_unknown_test.go b/internal/gateway/vision_unknown_test.go new file mode 100644 index 000000000..0e3a2e43e --- /dev/null +++ b/internal/gateway/vision_unknown_test.go @@ -0,0 +1,111 @@ +package gateway + +import ( + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// unknownEyed is eyed with the text model's list saying nothing of images, +// as most vendors' /models lists don't: magpie counts it text-only (agents +// were told so before Vision told them every model takes images). +func unknownEyed(t *testing.T) (*Server, *eyeUp) { + t.Helper() + s, u := eyed(t) + p, err := provider.Find("probe") + if err != nil { + t.Fatal(err) + } + if err := catalog.SaveLive("probe", p.Chat, []catalog.Model{ + {ID: "text"}, + {ID: "eye", Images: true, ImageInput: imageInputBool(true)}, + }); err != nil { + t.Fatal(err) + } + return s, u +} + +func TestModelNotKnownToSeeIsGivenTheDescription(t *testing.T) { + s, u := unknownEyed(t) + cases := []struct{ path, body string }{ + {"/v1/responses", `{"model":"probe/text","input":[{"role":"user","content":[{"type":"input_text","text":"read"},{"type":"input_image","image_url":"data:image/png;base64,aGVsbG8="}]}]}`}, + {CodexPath + "/responses", `{"model":"probe/text","stream":true,"input":[{"role":"user","content":[{"type":"input_text","text":"read"},{"type":"input_image","image_url":"https://example.com/a.png"}]}]}`}, + {"/v1/chat/completions", `{"model":"probe/text","messages":[{"role":"user","content":[{"type":"text","text":"read"},{"type":"image_url","image_url":{"url":"data:image/png;base64,aGVsbG8="}}]}]}`}, + } + for _, tc := range cases { + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", tc.path, strings.NewReader(tc.body))) + if rec.Code != 200 { + t.Errorf("%s: %d %s", tc.path, rec.Code, rec.Body.String()) + } + } + got := u.sent("text") + if len(got) != len(cases) { + t.Fatalf("text model sent %d requests, want %d", len(got), len(cases)) + } + for i, b := range got { + if !strings.Contains(b, "HELLO") || strings.Contains(b, "aGVsbG8=") || strings.Contains(b, "example.com/a.png") { + t.Errorf("%s: text model was sent %s", cases[i].path, b) + } + } + if n := len(u.sent("eye")); n != 2 { + t.Fatalf("the describer was asked %d times, want 2 (two images)", n) + } +} + +// A Codex function_call_output's image, an older turn's and a routing +// group's member whose list says nothing of images are described too. +func TestModelNotKnownToSeeToolAndGroupImages(t *testing.T) { + s, u := unknownEyed(t) + body := `{"model":"probe/text","stream":true,"input":[{"role":"user","content":[{"type":"input_text","text":"open a.png"}]},{"type":"function_call","call_id":"call_1","name":"view_image","arguments":"{}"},{"type":"function_call_output","call_id":"call_1","output":[{"type":"input_text","text":"a.png"},{"type":"input_image","image_url":"data:image/png;base64,dG9vbA=="}]}]}` + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(body))) + if rec.Code != 200 { + t.Fatalf("tool image: %d %s", rec.Code, rec.Body.String()) + } + if got := u.sent("text"); len(got) != 1 || !strings.Contains(got[0], "HELLO") || strings.Contains(got[0], "dG9vbA==") { + t.Fatalf("tool image: text model was sent %v", got) + } + if err := provider.SaveGroup(provider.Group{Name: "Mixed", Members: []string{"probe/text", "probe/eye"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + code, out := postAs(t, s, "", `{"model":"group/mixed","messages":[{"role":"user","content":[{"type":"text","text":"read"},{"type":"image_url","image_url":{"url":"data:image/png;base64,Z3JvdXA="}}]}]}`) + if code != 200 { + t.Fatalf("group: %d %s", code, out) + } + if got := u.sent("text"); len(got) != 2 || !strings.Contains(got[1], "HELLO") || strings.Contains(got[1], "Z3JvdXA=") { + t.Fatalf("group: text member was sent %v", got) + } +} + +// The description is in the Routing view as a call of its own, on the +// model that described, for the request and in its session. +func TestDescriptionIsInRouting(t *testing.T) { + s, _ := eyed(t) + req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"probe/text","stream":true,"input":[{"role":"user","content":[{"type":"input_text","text":"read"},{"type":"input_image","image_url":"data:image/png;base64,aGVsbG8="}]}]}`)) + req.Header.Set("session_id", "s-1") + req.Header.Set("User-Agent", "codex_cli_rs/0.50.0") + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body.String()) + } + var vision, turn *Route + for _, r := range s.trace.routes { + switch r.Model { + case "probe/eye": + vision = r + case "probe/text": + turn = r + } + } + if vision == nil || turn == nil { + t.Fatalf("routes: vision %v, turn %v", vision, turn) + } + if vision.Kind != "vision" || vision.For == nil || vision.For.Model != "probe/text" || vision.For.Agent != turn.Agent || vision.Session != turn.Session || turn.Session == "" { + t.Fatalf("vision route: kind %q for %+v session %q; turn agent %q session %q", vision.Kind, vision.For, vision.Session, turn.Agent, turn.Session) + } +} diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index b29c6294d..fbad404d2 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2034,6 +2034,9 @@ const I18N = { "Web search": "联网搜索", "magpie ran this web search for {agent}'s {model}, which can't search the web by itself: {searcher} searched, and {model} goes on answering once it has what was found. Not a turn of the conversation.": "这是 magpie 替 {agent} 的 {model} 发起的联网搜索:{model} 自己不能搜索网页,由 {searcher} 去搜,{model} 拿到搜索结果后才接着回答。它不是对话中的一轮。", "magpie ran this web search for a model that can't search the web by itself: {searcher} searched, and that model goes on answering once it has what was found. Not a turn of the conversation.": "这是 magpie 替一个自己不能搜索网页的模型发起的联网搜索:由 {searcher} 去搜,那个模型拿到搜索结果后才接着回答。它不是对话中的一轮。", + "Image description": "图片描述", + "magpie had {describer} describe an image for {agent}'s {model}, which can't see images: {model} is given the description in the image's place. Not a turn of the conversation.": "这是 magpie 让 {describer} 替 {agent} 的 {model} 描述的图片:{model} 看不了图片,收到的是图片位置上的这段描述。它不是对话中的一轮。", + "magpie had {describer} describe an image for a model that can't see images, which is given the description in the image's place. Not a turn of the conversation.": "这是 magpie 让 {describer} 替一个看不了图片的模型描述的图片:那个模型收到的是图片位置上的这段描述。它不是对话中的一轮。", "{agent} sent this turn on Luna Reserve, which it turns to once the plan's own allowance is used up; it picks the model itself.": "{agent} 用 Luna 储备发出了这一轮:套餐自己的额度用完后它会改用 Luna 储备,模型由它自己决定。", "{agent} made this call itself ({kind}), not as a turn of the conversation, and picks its model itself.": "这是 {agent} 自己发起的调用({kind}),不是对话中的一轮,模型由它自己决定。", "Nothing was tried: {error}": "没有尝试任何账号:{error}", diff --git a/internal/gui/assets/routing.js b/internal/gui/assets/routing.js index 249e4f395..7713b8808 100644 --- a/internal/gui/assets/routing.js +++ b/internal/gui/assets/routing.js @@ -1156,6 +1156,7 @@ collab_spawn: "Subagent", thread_spawn: "Subagent", agent_job: "Subagent", luna_reserve: "Luna Reserve", web_search: "Web search", + vision: "Image description", }; const kindName = (k) => KIND[k] ? t(KIND[k]) : k; function kindTag(r) { @@ -1189,6 +1190,9 @@ if (r.kind === "web_search") return r.for ? t("magpie ran this web search for {agent}'s {model}, which can't search the web by itself: {searcher} searched, and {model} goes on answering once it has what was found. Not a turn of the conversation.", { agent: agentName(r.for.agent), model: r.for.model, searcher: r.model }) : t("magpie ran this web search for a model that can't search the web by itself: {searcher} searched, and that model goes on answering once it has what was found. Not a turn of the conversation.", { searcher: r.model }); + if (r.kind === "vision") return r.for + ? t("magpie had {describer} describe an image for {agent}'s {model}, which can't see images: {model} is given the description in the image's place. Not a turn of the conversation.", { agent: agentName(r.for.agent), model: r.for.model, describer: r.model }) + : t("magpie had {describer} describe an image for a model that can't see images, which is given the description in the image's place. Not a turn of the conversation.", { describer: r.model }); return t("{agent} made this call itself ({kind}), not as a turn of the conversation, and picks its model itself.", { agent, kind: kindName(r.kind) }); }