From c286c218e3e2d9b7bd397cbc92451a33ea3ff5d3 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 29 Sep 2026 10:25:41 +0800 Subject: [PATCH] =?UTF-8?q?routing:=20a=20group's=20intent=20classifier=20?= =?UTF-8?q?can=20be=20a=20routing=20group,=20failing=20over=20as=20any=20r?= =?UTF-8?q?equest=20to=20it=20does=20(lantern2077=20on=20Discord:=20?= =?UTF-8?q?=E6=84=8F=E5=9B=BE=E5=88=86=E7=B1=BB=E6=A8=A1=E5=9E=8B=E8=83=BD?= =?UTF-8?q?=E5=90=A6=E4=B9=9F=E9=80=89=E6=8B=A9=E8=B7=AF=E7=94=B1=E7=BB=84?= =?UTF-8?q?=EF=BC=9F=E7=8E=B0=E5=9C=A8=E5=8F=AA=E8=83=BD=E9=80=89=E6=8B=A9?= =?UTF-8?q?=E5=8D=95=E4=B8=AA=E6=A8=A1=E5=9E=8B=EF=BC=8C=E7=BC=BA=E4=B9=8F?= =?UTF-8?q?=E5=9B=9E=E9=80=80=E4=BF=9D=E9=9A=9C)=20=E2=80=94=20the=20class?= =?UTF-8?q?ifier=20was=20one=20model,=20and=20when=20it=20was=20down=20no?= =?UTF-8?q?=20intent=20matched.=20It=20can=20now=20be=20group/,=20aske?= =?UTF-8?q?d=20through=20magpie=20as=20before,=20so=20its=20first=20model?= =?UTF-8?q?=20failing=20the=20next=20is=20asked.=20A=20group=20can't=20be?= =?UTF-8?q?=20its=20own=20classifier,=20one=20that=20classifies=20for=20an?= =?UTF-8?q?other=20can't=20be=20removed=20until=20that=20one=20chooses=20a?= =?UTF-8?q?nother,=20a=20rename=20carries=20over,=20and=20a=20classifier's?= =?UTF-8?q?=20own=20call=20asks=20no=20classifier=20in=20turn,=20so=20two?= =?UTF-8?q?=20groups=20classifying=20with=20each=20other=20don't=20loop.?= =?UTF-8?q?=20The=20GUI=20and=20TUI=20pickers=20list=20the=20other=20group?= =?UTF-8?q?s.=20Tested:=20the=20classifier=20group's=20first=20model=20500?= =?UTF-8?q?s=20and=20the=20next=20answers=20and=20the=20rule=20matches;=20?= =?UTF-8?q?two=20groups=20set=20to=20classify=20with=20each=20other=20fini?= =?UTF-8?q?sh=20at=20once;=20checked=20in=20a=20sandbox=20magpie=20web=20t?= =?UTF-8?q?hat=20the=20picker=20lists=20Cls=20and=20not=20the=20group=20be?= =?UTF-8?q?ing=20edited,=20and=20via=20the=20CLI=20that=20self-classifying?= =?UTF-8?q?=20and=20removing=20a=20classifier=20group=20are=20refused?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- groups_cli.go | 2 +- groups_rules_cli.go | 5 ++-- internal/gateway/classify_test.go | 44 +++++++++++++++++++++++++++++ internal/gateway/gateway.go | 11 ++++++-- internal/gateway/rules.go | 11 ++++---- internal/gui/assets/i18n.js | 1 + internal/gui/assets/routing.js | 13 +++++++-- internal/provider/group.go | 30 ++++++++++++++------ internal/provider/grouprule_test.go | 24 ++++++++++++++-- internal/tui/routing.go | 6 ++-- 10 files changed, 120 insertions(+), 27 deletions(-) diff --git a/groups_cli.go b/groups_cli.go index 0b09bc356..7caa1c659 100644 --- a/groups_cli.go +++ b/groups_cli.go @@ -28,7 +28,7 @@ const groupUsage = `usage: id (what agents pick it as: id=gpt-6-astra drops auto-; the groups it is in follow; an agent set to the old id needs setting again), effort=auto (the classifier picks each turn's reasoning; needs classifier=), - effort=agent (the agent's again), classifier= + effort=agent (the agent's again), classifier=|group/ magpie group rm remove a group (one magpie found is hidden instead) magpie group restore bring back a group magpie found that you removed magpie group rule add|rm|mv … rules: which model a turn goes to first, by its length, an image, diff --git a/groups_rules_cli.go b/groups_rules_cli.go index 6cda2b1f5..20803ef47 100644 --- a/groups_rules_cli.go +++ b/groups_rules_cli.go @@ -21,7 +21,8 @@ const ruleUsage = `usage: magpie group rule rm remove rule n magpie group rule mv move rule n to place magpie group rule classifier - the model that tells which intent a message is + the model that tells which intent a message is, or + group/: another group, its models tried in turn Rules are looked at top first when you send a message (a new turn); the first that matches puts its model first, and the group's others stay behind it if it fails. @@ -34,7 +35,7 @@ const ruleUsage = `usage: agents it comes from one of these agents (claude, codex, opencode, … as magpie usage names them) intent the user's message is of this kind, in your words ("writing or fixing tests", "a quick question"): as the turn begins, the group's classifier — any model magpie has, best a small - fast one without reasoning — is asked which of the intents that may match the message is, + fast one without reasoning, or another group of them to fail over — is asked which of the intents that may match the message is, once; if it fails or can't say, no intent matches. Its call shows in the usage as magpie's own e.g. magpie group rule add opus-anywhere use=openrouter/google/gemini-3-pro tokens=200k diff --git a/internal/gateway/classify_test.go b/internal/gateway/classify_test.go index 1edcfc0e8..de31d6234 100644 --- a/internal/gateway/classify_test.go +++ b/internal/gateway/classify_test.go @@ -381,3 +381,47 @@ func TestChatClassifierPicksTheEffort(t *testing.T) { t.Fatalf("both: %+v %+v %d", r.Rule, r.Rule.Classified, c.n()) } } + +// A group classifies as any request to it goes: its first model down, the +// next answers. One whose classifier is, round about, the group asking +// isn't asked again from within its own call: it goes by its other rules. +func TestIntentClassifierGroup(t *testing.T) { + s, _, _, c := intented(t, provider.Rule{Use: "b/big", Intent: "refactoring"}) + d := &clsUp{} + d.set("", 500) + srv := httptest.NewServer(d) + t.Cleanup(srv.Close) + if err := provider.Save(provider.Provider{ID: "d", Name: "D", Key: "kd", Models: []string{"cls"}, Chat: srv.URL + "/v1"}); err != nil { + t.Fatal(err) + } + if err := catalog.SaveLive("d", srv.URL+"/v1", []catalog.Model{{ID: "cls", Context: 32000}}); err != nil { + t.Fatal(err) + } + if err := provider.SaveGroup(provider.Group{Name: "Cls", Members: []string{"d/cls", "c/cls"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + g, _, _ := provider.FindGroup("group/r") + g.Classifier = "group/cls" + if err := provider.SaveGroup(g); err != nil { + t.Fatal(err) + } + c.set("1", 0) + out, r := postOK(t, s, "g1", chat("rename this package", nil, 0, "")) + if !strings.Contains(out, "from kb") || r.Rule.N != 1 || r.Rule.Classified.By != "group/cls" || r.Rule.Classified.Error != "" { + t.Fatalf("failover: %s %+v %+v", out, r.Rule, r.Rule.Classified) + } + if d.n() == 0 || c.n() != 1 { + t.Fatalf("asked d %d, c %d times", d.n(), c.n()) + } + // cls classifies with r, r with cls: cls's own call for r asks nobody + cg, _, _ := provider.FindGroup("group/cls") + cg.Rules, cg.Classifier = []provider.Rule{{Use: "c/cls", Intent: "anything"}}, "group/r" + if err := provider.SaveGroup(cg); err != nil { + t.Fatal(err) + } + t0 := time.Now() + out, r = postOK(t, s, "g2", chat("rename that package", nil, 0, "")) + if !strings.Contains(out, "from kb") || r.Rule.N != 1 || r.Rule.Classified.Error != "" || c.n() != 2 || time.Since(t0) > 3*time.Second { + t.Fatalf("loop: %s %+v %+v %d %s", out, r.Rule, r.Rule.Classified, c.n(), time.Since(t0)) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 29fc0b060..8e492c8b2 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -691,6 +691,13 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro var ruled []provider.Member var ruleAt, words string var ruleReq *Request // parsed for the rules of the group or a group in it + // a classifier's own call to a group (a group's classifier may be one) + // asks no classifier in turn: one that is, however far round, the group + // asking would ask itself for ever + ask := s.askClassifier + if r.Header.Get("User-Agent") == RouterAgent { + ask = nil + } if isGroup && slices.ContainsFunc(ms, func(m provider.Member) bool { return g.Ruled() || slices.ContainsFunc(m.Via, provider.Group.Ruled) }) { @@ -699,7 +706,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } } if ruleReq != nil && g.Ruled() { - hit = ruleFor(ruleAt, g, ms, ruleReq, call.Agent, s.askClassifier) + hit = ruleFor(ruleAt, g, ms, ruleReq, call.Agent, ask) ruled = ruleMembers(hit, ms) } // Some clients send images even when the selected model is known to @@ -805,7 +812,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro var nested []NestedRule var nestedAt []string if ruleReq != nil { - nested, nestedAt, cands, pl = s.nestedRules(ruleAt, ruleReq, call.Agent, ms, cands, pl, aff) + nested, nestedAt, cands, pl = s.nestedRules(ruleAt, ruleReq, call.Agent, ask, ms, cands, pl, aff) } // the effort a group's decision model picked for the turn: the // outermost group's that did diff --git a/internal/gateway/rules.go b/internal/gateway/rules.go index bc13ef117..1651d5297 100644 --- a/internal/gateway/rules.go +++ b/internal/gateway/rules.go @@ -209,7 +209,7 @@ func ruleFor(key string, g provider.Group, ms []provider.Member, req *Request, a case g.Classifier == "": c.Error = "the group has no classifier" case ask == nil: - c.Error = "nothing to ask the classifier with" + c.Error = "nothing to ask the classifier with: this is a classifier's own call" case text == "": c.Error = "the message has no words to classify" default: @@ -313,9 +313,10 @@ func ruleAnswered(key string, u Usage) { // nestedRules looks at the rules of each group in the group that the one // going first is of, outermost first: a group's rules pick among its own // members as the group's do, keeping what they decided for the turn by -// their own key (at, the group's, and the group's way down). It gives -// what each decided and their keys. -func (s *Server) nestedRules(at string, req *Request, agent string, ms []provider.Member, cands []candidate, pl planned, aff *Affinity) ([]NestedRule, []string, []candidate, planned) { +// their own key (at, the group's, and the group's way down), asking ask +// of the message as the group's own rules do. It gives what each decided +// and their keys. +func (s *Server) nestedRules(at string, req *Request, agent string, ask classifier, ms []provider.Member, cands []candidate, pl planned, aff *Affinity) ([]NestedRule, []string, []candidate, planned) { var out []NestedRule var keys []string for depth := 0; ; depth++ { // as deep as the one going first is @@ -335,7 +336,7 @@ func (s *Server) nestedRules(at string, req *Request, agent string, ms []provide subMs = append(subMs, m.Below(depth+1)) } } - h := ruleFor(at, sub, subMs, req, agent, s.askClassifier) + h := ruleFor(at, sub, subMs, req, agent, ask) keys = append(keys, at) out = append(out, NestedRule{Group: sub.ID, Name: sub.Name, Rule: h}) if h == nil || h.Use == "" || h.Held && aff != nil && aff.Kept { diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 22ef7c613..a3b671ac8 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -852,6 +852,7 @@ const I18N = { "As a turn begins, this model is asked which of the intents the message is — once; a small, fast one without reasoning is best. If it fails or can't say, no intent matches. Its calls show in the usage as magpie’s own.": "每一轮开始时,问这个模型一次:用户这条消息属于哪个意图。建议选小而快、不带推理的模型。它出错或给不出答案时,所有意图条件都不命中。它的调用在用量里显示为 magpie 自己的调用。", "Choose the model that tells which intent a message is": "请选择用来判断消息意图的模型", "the classifier": "意图判断模型", + "A routing group classifies as any request to it goes: if its first model fails, the next is asked.": "路由组作判断模型时,与发给它的任何请求一样:第一个模型失败,就换下一个来问。", "said before, for the same message": "同一条消息之前已判断过", "in {ms}": "用时 {ms}", "{by} was to tell which of {kinds} turn {turn} is, but couldn't — {err} — so no rule with an intent matches it.": "{by} 本应判断第 {turn} 轮属于 {kinds} 中的哪一个,但没能给出答案({err}),所以带意图的规则都不命中。", diff --git a/internal/gui/assets/routing.js b/internal/gui/assets/routing.js index cfbd2209e..5eb5d04e5 100644 --- a/internal/gui/assets/routing.js +++ b/internal/gui/assets/routing.js @@ -1840,14 +1840,21 @@ if (!on) return; const intents = d.rules.some((r) => r.intent?.trim()); clabel.textContent = t(auto && !intents ? "Decided by" : "Intent told by"); - const m = [...deciders, ...groups.models].find((x) => x.id === d.classifier); + // a model, or another group: its models are asked in turn, failing + // over as any request to it does (never this group: it would ask + // itself) + const m = [...deciders, ...groups.models].find((x) => x.id === d.classifier), sg = subOf(d.classifier); const cb = el("button", "rt-cond" + (d.classifier ? " on" : "")); - if (d.classifier) cb.append(icon(m?.icon || "generic"), el("span", "", m ? `${m.name || m.id} · ${m.providerName}` : d.classifier)); + if (sg) cb.append(stackIcon(groupIcons(sg)), el("span", "", `${sg.name} · ${t("routing group")}`)); + else if (d.classifier) cb.append(icon(m?.icon || "generic"), el("span", "", m ? `${m.name || m.id} · ${m.providerName}` : d.classifier)); else cb.append(el("span", "", t("choose a model"))); const opt = (x) => ({ value: x.id, label: x.name || x.id, note: x.providerName, icon: x.icon, group: x.providerName, ref: x.id }); - cb.onclick = (ev) => openPicker({ id: "", name: "", fields: [] }, { key: "classifier", label: "model", value: d.classifier, options: [...deciders.map(opt), ...groups.models.map(opt)], + const subs = groups.groups.filter((x) => !x.hidden && x.id !== g?.id) + .map((x) => ({ value: "group/" + x.id, label: x.name, note: "group/" + x.id, icons: groupIcons(x), group: ROUTING_GROUPS, ref: "group/" + x.id })); + cb.onclick = (ev) => openPicker({ id: "", name: "", fields: [] }, { key: "classifier", label: "model", value: d.classifier, options: [...deciders.map(opt), ...subs, ...groups.models.map(opt)], onPick: (id) => { if (id) d.classifier = id; drawClassifier(); } }, cb, ev); cls.replaceChildren(cb, + ...(sg ? [el("div", "hint", t("A routing group classifies as any request to it goes: if its first model fails, the next is asked."))] : []), el("div", "hint", t(isJev(d.classifier) && !intents ? "Jev is asked once as each turn begins, with the message and what it said of the turn before. Its calls show in the usage as magpie’s own." : isJev(d.classifier) diff --git a/internal/provider/group.go b/internal/provider/group.go index f6d4d6655..3758b631c 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -58,9 +58,11 @@ type Group struct { // Rules send the requests they match to one member first, in order: // the first that matches decides (see Rule). Rules []Rule `json:"rules,omitempty"` - // Classifier is the model ("provider/model", not a group) asked which - // of the rules' intents a user's message is. Rules with an intent need - // one; a small, fast model without reasoning does. + // Classifier is the model ("provider/model") asked which of the rules' + // intents a user's message is, or a group ("group/", never this + // one) whose models are asked in turn, failing over as for any request. + // Rules with an intent need one; a small, fast model without reasoning + // does. Classifier string `json:"classifier,omitempty"` // Effort "auto" has the classifier — Jev, from TypeSafe's decision API, // or any model, asked in words — judge how hard each turn is to think @@ -395,8 +397,8 @@ func SaveGroup(g Group) error { switch { case g.Effort != "" && g.Effort != EffortAuto: return fmt.Errorf("a group's effort is %q or left to the agent, not %q", EffortAuto, g.Effort) - case strings.HasPrefix(g.Classifier, GroupPrefix): - return fmt.Errorf("the classifier is a model, not a group (%s)", g.Classifier) + case g.Classifier == GroupPrefix+g.ID: + return fmt.Errorf("%s can't be its own classifier: asking it would ask it again", g.Name) case intents && g.Classifier == "": return errors.New("a rule with an intent needs the group's classifier: the model that tells which intent a message is") case g.Effort == EffortAuto && g.Classifier == "": @@ -404,7 +406,11 @@ func SaveGroup(g Group) error { case !intents && g.Effort == "": g.Classifier = "" // nothing to ask it } - if g.Classifier != "" { + if gid, ok := strings.CutPrefix(g.Classifier, GroupPrefix); ok { + if _, ok := groupOf(groupsIn(providerEntries()), gid); !ok { + return fmt.Errorf("magpie has no group %q to classify with", gid) + } + } else if g.Classifier != "" { if _, _, ok := Resolve(g.Classifier); !ok { return fmt.Errorf("magpie knows no model %q to classify with", g.Classifier) } @@ -496,8 +502,8 @@ func GroupsWith(id string) []Group { } // DeleteGroup removes a group of the user's; one magpie found is hidden, -// to come back with ShowGroup. A group another has in it stays until it is -// taken out of that one. +// to come back with ShowGroup. A group another has in it, or classifies +// with, stays until it is taken out of that one. func DeleteGroup(id string) error { if in := GroupsWith(id); len(in) > 0 { var names []string @@ -506,6 +512,11 @@ func DeleteGroup(id string) error { } return fmt.Errorf("%s is in %s: take it out first", id, strings.Join(names, ", ")) } + for _, g := range groupsIn(providerEntries()) { + if !g.Hidden && g.Classifier == GroupPrefix+id { + return fmt.Errorf("%s is %s's classifier: choose another first", id, g.Name) + } + } f := load() found := false f.Groups = slices.DeleteFunc(f.Groups, func(g Group) bool { @@ -587,6 +598,9 @@ func RenameGroup(from, to string) error { f.Groups[i].Rules[j].Use = now } } + if f.Groups[i].Classifier == old { + f.Groups[i].Classifier = now + } } return store(f) } diff --git a/internal/provider/grouprule_test.go b/internal/provider/grouprule_test.go index 286b7566b..ce5baf398 100644 --- a/internal/provider/grouprule_test.go +++ b/internal/provider/grouprule_test.go @@ -247,8 +247,8 @@ func TestSaveGroupRules(t *testing.T) { } } -// A group with an intent needs a classifier: a model magpie knows, not a -// group. Without intents it keeps none. +// A group with an intent needs a classifier: a model magpie knows, or +// another group, never itself. Without intents it keeps none. func TestSaveGroupClassifier(t *testing.T) { t.Setenv("HOME", t.TempDir()) t.Setenv("XDG_CONFIG_HOME", t.TempDir()) @@ -262,7 +262,8 @@ func TestSaveGroupClassifier(t *testing.T) { classifier, err string }{ {"", "needs the group's classifier"}, - {"group/other", "not a group"}, + {"group/other", "no group"}, + {"group/r", "its own classifier"}, {"z/nothing", "knows no model"}, } { err := SaveGroup(Group{Name: "R", Members: []string{"a/m", "b/big"}, Rules: intent, Classifier: tc.classifier}) @@ -277,6 +278,23 @@ func TestSaveGroupClassifier(t *testing.T) { if g.Classifier != "a/m" || g.Rules[0].Intent != "planning" { t.Fatalf("%+v", g) } + // another group classifies with its failover; renamed, it is followed, + // and it can't be removed while it does + if err := SaveGroup(Group{Name: "Fast", Members: []string{"a/m", "b/m"}}); err != nil { + t.Fatal(err) + } + if err := SaveGroup(Group{Name: "R", Members: []string{"a/m", "b/big"}, Rules: intent, Classifier: "group/fast"}); err != nil { + t.Fatal(err) + } + if err := RenameGroup("fast", "quick"); err != nil { + t.Fatal(err) + } + if g, _, _ := FindGroup(GroupPrefix + "r"); g.Classifier != "group/quick" { + t.Fatalf("classifier %q after the rename", g.Classifier) + } + if err := DeleteGroup("quick"); err == nil || !strings.Contains(err.Error(), "classifier") { + t.Fatalf("%v", err) + } if err := SaveGroup(Group{Name: "R", Members: []string{"a/m", "b/big"}, Rules: []Rule{{Use: "b/big", Tokens: 5}}, Classifier: "a/m"}); err != nil { t.Fatal(err) } diff --git a/internal/tui/routing.go b/internal/tui/routing.go index a7ea3e06c..11be9a710 100644 --- a/internal/tui/routing.go +++ b/internal/tui/routing.go @@ -224,12 +224,12 @@ func (m *model) openMemberPicker(p pickMsg) { } // openClassifier picks the model that tells which intent a message is: -// a model, not a group. +// a model, or another group whose models are tried in turn. func (m *model) openClassifier(g provider.Group) { var items []agent.Option for _, e := range provider.Catalog() { - if e.Group != "" { - continue + if e.Group == g.ID { + continue // it can't classify for itself } note := e.Name if e.ID == g.Classifier {