routing: a group's intent classifier can be a routing group, failing over as any request to it does (lantern2077 on Discord: 意图分类模型能否也选择路由组?现在只能选择单个模型,缺乏回退保障) — the classifier was one model, and when it was down no intent matched. It can now be group/<id>, asked through magpie as before, so its first model failing the next is asked. A group can't be its own classifier, one that classifies for another can't be removed until that one chooses another, a rename carries over, and a classifier's own call asks no classifier in turn, so two groups classifying with each other don't loop. The GUI and TUI pickers list the other groups. Tested: the classifier group's first model 500s and the next answers and the rule matches; two groups set to classify with each other finish at once; checked in a sandbox magpie web that the picker lists Cls and not the group being edited, and via the CLI that self-classifying and removing a classifier group are refused

This commit is contained in:
yetone
2026-09-29 10:25:41 +08:00
parent 1963f7f262
commit c286c218e3
10 changed files with 120 additions and 27 deletions
+1 -1
View File
@@ -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=<provider/model>
effort=agent (the agent's again), classifier=<provider/model>|group/<id>
magpie group rm <id> remove a group (one magpie found is hidden instead)
magpie group restore <id> bring back a group magpie found that you removed
magpie group rule add|rm|mv <id> … rules: which model a turn goes to first, by its length, an image,
+3 -2
View File
@@ -21,7 +21,8 @@ const ruleUsage = `usage:
magpie group rule rm <group> <n> remove rule n
magpie group rule mv <group> <n> <to> move rule n to place <to>
magpie group rule classifier <group> <model>
the model that tells which intent a message is
the model that tells which intent a message is, or
group/<id>: 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
+44
View File
@@ -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))
}
}
+9 -2
View File
@@ -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
+6 -5
View File
@@ -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 {
+1
View File
@@ -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}),所以带意图的规则都不命中。",
+10 -3
View File
@@ -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)
+22 -8
View File
@@ -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/<id>", 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)
}
+21 -3
View File
@@ -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)
}
+3 -3
View File
@@ -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 {