gateway: a group's classifier asks on the group's accounts (AWilsonPeng on X)

A ruled group whose intent classifier (意图判断模型, "Intent told by")
is a model, not a group, asked that model with a fresh request that
carried no identity, so it went out on any signed-in account of the
subscription. AWilsonPeng held the found group GPT-6 Luna to one of two
ChatGPT accounts and picked its own member GPT-6-Luna · Codex as the
classifier (a group can't classify with itself, so it isn't offered),
and the classifier's questions still went to the other account.

The classifier is now asked under the caller's identity held to the
group (classifierHeld in rules.go): the group's Accounts, a gateway
key's accounts, and, when the classifier is one of the group's members,
that member's pinned account. askChat, askDecider and
askDecisionGroup pass the identity on, so every route a classifier
takes (a single model, a decision group, the least-busy pick) keeps
to those accounts. A failed classifier rests only for those accounts.
A group-ref classifier was already held (round 1).

Tests: TestClassifierModelHeldToItsGroupsAccount (the reporter's case,
held by the group's Accounts and by the member's #account pin) and
TestClassifierModelHeldToTheKeysAccount (a key held to one Codex
account).

Run (mica):
- red on b4968d444 with the new tests: all three cases asked on acct-1;
- go test ./internal/gateway -run 'Classif|Decide|Rule|Intent|Nested'
  ok (mote, 46s);
- go test ./internal/gateway ./internal/access ./internal/provider
  -count=1 -timeout 45m: all ok (gateway 917s);
- GOOS=linux and GOOS=windows go vet ./internal/gateway: ok; gofmt clean.

Not tried: real ChatGPT accounts or the GUI; the union case where the
classifier model is a member once per account (it then keeps to the
union of those pins). The picker is unchanged: its chip already names
the model chosen.
This commit is contained in:
yetone
2026-11-15 16:45:06 +08:00
parent bf14062def
commit 993c8a7267
9 changed files with 220 additions and 44 deletions
+1 -1
View File
@@ -232,7 +232,7 @@ recorded as a prediction failure (`noPrediction`).
- A classifier's timeout is global (`Settings.ClassifyTimeout`, JSON `classifyTimeout`, seconds, in [`settings.go`](../../internal/settings/settings.go)). Missing or 0 keeps the 8-second default; saving accepts 1–60 seconds or 0 and rejects negative values or values above 60. `Settings.ClassifyWait` bounds a hand-edited value above 60 to 60 seconds and uses the default for a value below 1. `classifyTimeout()` reads it for each call: both `askChat` in [`classify.go`](../../internal/gateway/classify.go) and `askJev` in [`decide.go`](../../internal/gateway/decide.go) give the classifier that time, including its provider's failover. A request shares one such wait across every routing group it goes through (`Server.askWaited`, from the first classifier asked): a nested ruled group asked with less left gets only that, one asked once it is spent goes by its order at once (`waitSpent`, "spent by the routing group above"), and a classifier or decision key cut short that way is not rested (`cutShort`). Each nested level had a whole wait of its own before, so three ruled levels whose classifiers didn't answer held a request past the unrouted watch's 2 minutes, a 504 (heatonz on Discord, v0.1.2215; `TestNestedGroupsShareTheClassifierWait`, `TestDecisionKeyCutShortIsNotRested`). Settings → Models → Replies → *Intent classifier timeout* (`renderReplies` in [`app.js`](../../internal/gui/assets/app.js)) offers 8, 15, 30 and 60 seconds and shows a custom valid value as its own choice. A change applies to the next classifier call, with no restart; the existing fallback, 30-second cooldown (`classifyRest`) and 10-minute answer cache (`classifyKeep`) still apply.
- A classifier that can't say which kind a turn is (an error, no answer within `classifyTimeout()`, an answer that isn't a number, or resting `classifyRest` after a failure) leaves a turn whose conversation had an intent, still one of this turn's, with that intent (`Classified.Fallback` is `previous`, its `Error` kept), so the turn goes where the turn before went rather than to the group's first member; with no intent before, no rule with an intent matches, as before. The Routing page says the turn kept it (`classWhy`). The turn's decision itself (`turnRules`) is kept in memory only: after a restart a turn under way waits for the next one and the stick holds it meanwhile. `TestIntentClassifierFailsKeepsThePreviousIntent`, `routing-intent-fallback.test.cjs`.
- A group's classifier is asked only for that group's own turns: a request whose model is the group (`group/<id>`, its bare name, or a stand-in an agent's config names it by: Claude Code's tiers, Codex's bare name), or a group in it that its rules or order put first (`nestedRules`). A request for another model or group asks it nothing. The Routing groups page's card says why the classifier couldn't say the last time *that group* asked it (`GroupClassifierFailure`, kept by `classifiedFor` in `ruleFor`): the classifier's own words and time, resting or not, until it answers that group, and nothing once the group's classifier changed. Keyed by the classifier model alone, a group nothing reached showed another group's failure on a classifier they share (jjt on Discord). A classifier on a subscription out of its quota is not asked of the vendor again until the reset: out of quota, its account rests until the quota comes back (`restAfter`: the time the refusal names, else when the account's window renews), and the classifier's call meanwhile gets that refusal back from magpie, at most once each `classifyRest`. `TestClassifierFailureIsTheGroupsOwn`.
- The classifier's requests are magpie's own (#1839). Asked in words, they go out with `RouterAgent`'s User-Agent (`magpie-router/1`), so their records' agent is magpie and `callKind` marks them `routing`; a decision model's (Jev, System One) record is written with `Kind: "routing"` too. They go to the same key or account as any other request and count in its totals, while `usage.Group.Own` (`Record.ByMagpie`: agent `magpie` or one of its `magpie-` User-Agents, with search's and image description's) says how many of an account's, key's or model's calls, tokens and cost were magpie's own. A classifier set to a subscription's model (`modelRef.Sub`, or a group whose first member is one) asks that subscription as every turn begins, twice when it picks both intent and effort in words; the Routing page says so beside it (`classifierSub` in `plugins/routing/client.js`). `TestIntentRoutesATurn`, `TestJevPicksTheIntent`, `TestSummaryCountsMagpiesOwnCallsApart`, `TestByMagpie`, `TestServedRefSaysASubscription`, `own-requests.test.cjs`.
- The classifier's requests are magpie's own (#1839). Asked in words, they go out with `RouterAgent`'s User-Agent (`magpie-router/1`), so their records' agent is magpie and `callKind` marks them `routing`; a decision model's (Jev, System One) record is written with `Kind: "routing"` too. They go to the same key or account as any other request and count in its totals, while `usage.Group.Own` (`Record.ByMagpie`: agent `magpie` or one of its `magpie-` User-Agents, with search's and image description's) says how many of an account's, key's or model's calls, tokens and cost were magpie's own. A classifier set to a subscription's model (`modelRef.Sub`, or a group whose first member is one) asks that subscription as every turn begins, twice when it picks both intent and effort in words; the Routing page says so beside it (`classifierSub` in `plugins/routing/client.js`). Its questions are the group's spend, so they are held to the accounts the turn is (`classifierHeld` in [`rules.go`](../../internal/gateway/rules.go), carried by `askWaited` to `askChat`, `askDecider` and `askDecisionGroup`; AWilsonPeng on X: a group held to one of two ChatGPT accounts whose classifier was its own member asked on both): the group's `Accounts`, the account its member names when the classifier is that member (each one's, for a model in it once per account), and the caller's (a gateway key's, a group above), never a key's models. A failure rests the classifier for those accounts alone (`classify`'s `rest`). `TestClassifierModelHeldToItsGroupsAccount`, `TestClassifierModelHeldToTheKeysAccount`, `TestIntentRoutesATurn`, `TestJevPicksTheIntent`, `TestSummaryCountsMagpiesOwnCallsApart`, `TestByMagpie`, `TestServedRefSaysASubscription`, `own-requests.test.cjs`.
- A rule may name several members (`Rule.More` after `Rule.Use`, `more` in the group's JSON, `use=a,b` typed; monkeyin_92 on X: one rule, several models, not a rule each). They go first in that order, ahead of the later matching rules' members (`ThenUses` leaves out every one the rule names) and the group's others: when the first fails or rests the rule's next takes the request, and the hit says so (`RuleHit.More`; `Instead` is that next one with `Unready` false, where an `Instead` from a later rule comes with `Unready` true). `Uses`, `SetUses`, `MapUses`, `Without` and `Names` in [`grouprule.go`](../../internal/provider/grouprule.go) are how every reader goes through them: `cleanRules` (each must be the group's, each named once, a pause names one), the turn's hold, the tool rounds and compaction (`ruleFor`, the rule's first that takes the summary), `nestedRules` and `ruleLed` (the one of them a nested group's turn stays on), `ruleEffort` (the rule's `useEffort` asked of each), `ruledEntry` (what a group takes is what every one of them takes), a model's rename and removal (a rule goes with its last), `ShareGroup` and its import (one this magpie hasn't is left out of the rule), the CLI's `groups rules` and the TUI. The editor draws a chip per member with a + for the next and an × on each while there is more than one (`rUses`/`setUses` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js)). A rule of one member writes no `more`, so a group saved before it reads and saves as it was. A magpie from before it reads `use` alone: its requests go to the first, and the others are plain members in the group's order; if it saves the group, `more` is dropped. `TestRuleSeveralModelsInOrder`, `TestCleanRulesSeveralModels`, `routing-rule-models.test.cjs`.
- The editor's rules are checked top first, so their order is theirs to set: a rule's number is its handle (`ruleHandle`, `.rt-rhandle`), dragged (`dragRows`, as the members are) or moved a place with Alt+↑/↓, the rules renumbered at once; the grip beside it shows on hover only, and Move up and down stay under its ⋯ (`moveRule`). Saved as the group's `rules` in their new order. `routing-rule-drag.test.cjs`.
- A rule can set the reasoning its member is asked for (`Rule.UseEffort`, `useEffort` in the group's JSON, `use-effort=low` typed; #2633, dengtongcai: an intent picks the model and the effort as a pair). It is an output like `Use`, not a condition like `Effort`. `ruleFor` copies it onto the hit (`RuleHit.UseEffort`) from the rule that put a member first, outer or nested; `ruleOver` keeps that rule's members, and `ruleEffort` gives each candidate of them the level fitted to its model's own (`fitLevel`), which `withFixedEffort` writes into the request's field for its protocol (Chat's `reasoning_effort`, Responses' `reasoning.effort`, Anthropic's thinking budget or `output_config.effort`) even when the agent asked none. A member fixed at an effort keeps its own; otherwise the rule's beats the model's suffix, the turn's pick and the agent's pick, and isn't bounded by the group's levels. A model whose levels aren't known (`Efforts` empty) is asked as the agent asked, as with the auto verdict. The members the group fails over to are asked it too (#3664): the effort is the turn's decision, so when the rule's own member is turned away the member that takes the request over is asked the same level, fitted to its model, rather than the agent's. A rule that names the candidate goes before one it only fails over from, and a nested group's rule decides for that group's members only: when the whole nested group fails, the outer group's member outside it is asked as the agent asked, or by the outer group's rule (`TestIntentEffortSurvivesTheGroupsFailover`, `TestNestedRuleEffortStaysInItsGroup`). A Gemini-protocol client's request is left as it came, as for every effort magpie sets. `cleanRules` refuses a value outside `provider.Efforts` and a pause with one. The try records it (`Try.RuleEffort`), and the Routing page says the rule set it. `rule_effort_test.go`, `grouprule_useeffort_test.go`, `routing-rule-effort.test.cjs`.
@@ -0,0 +1,110 @@
package gateway
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
)
// A group held to one ChatGPT account whose classifier is a model, not a
// group (AWilsonPeng on X, second round: the found group GPT-6 Luna held
// to one of two Codex accounts, its 意图判断模型 GPT-6-Luna · Codex — its
// own member, as a group can't classify with itself): the classifier's
// questions are the group's spend too, so they go on the group's account
// alone, as the turn does, never on the subscription's other account.
// Held by the group's Accounts, or by the member naming its account.
func TestClassifierModelHeldToItsGroupsAccount(t *testing.T) {
for _, held := range []bool{true, false} {
t.Run(fmt.Sprint("held=", held), func(t *testing.T) {
codexSignedIn(t, "spare@example.com")
asked := lunaBackend(t)
user := provider.LoginID("codex", "spare@example.com")
relay := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Errorf("the relay, switched off in the group, was asked")
w.WriteHeader(500)
}))
t.Cleanup(relay.Close)
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Chat: relay.URL + "/v1", Key: "sk-r", Models: []string{"gpt-6-luna"}}); err != nil {
t.Fatal(err)
}
id := provider.AutoGroupID("gpt-6-luna")
g, _, ok := provider.FindGroup("group/" + id)
if !ok {
t.Fatal("no found group")
}
g.Members, g.Off, g.Accounts = []string{"relay/gpt-6-luna", "codex/gpt-6-luna"}, []string{"relay/gpt-6-luna"}, []string{"codex/" + user}
if !held {
g.Members, g.Off, g.Accounts = []string{"relay/gpt-6-luna", "codex/gpt-6-luna#" + user}, []string{"relay/gpt-6-luna"}, nil
}
g.Classifier = "codex/gpt-6-luna"
g.Rules = []provider.Rule{{Use: g.Members[1], Intent: "feature"}}
if err := provider.SaveGroup(g); err != nil {
t.Fatal(err)
}
s := New()
for i := range 3 {
noRests()
code, out := postAs(t, s, fmt.Sprint("s", i), `{"model":"group/`+id+`","messages":[{"role":"user","content":"add feature `+fmt.Sprint(i)+`"}]}`)
r := lastRoute(s)
if code != 200 {
t.Fatalf("turn %d: %d %s", i, code, out)
}
if r.Rule == nil || r.Rule.Classified == nil || r.Rule.Classified.Error != "" {
t.Fatalf("turn %d: the classifier didn't answer: %+v", i, r.Rule)
}
a := asked()
if len(a) < 2 {
t.Fatalf("turn %d: %d requests reached the backend, not the classifier's and the turn's", i, len(a))
}
for _, a := range a {
if a != "acct-2" {
t.Fatalf("turn %d: sent on %q, not the group's acct-2", i, a)
}
}
}
})
}
}
// A gateway key held to one account holds what the classifier is asked
// for its turns too, as it holds magpie's other calls for the key (a web
// search, a title): a ruled group whose classifier is a Codex model asks
// it on the key's account, as the turn itself is sent.
func TestClassifierModelHeldToTheKeysAccount(t *testing.T) {
codexSignedIn(t, "spare@example.com")
asked := lunaBackend(t)
if err := provider.SaveGroup(provider.Group{Name: "R", Members: []string{"codex/gpt-6-luna", "codex/gpt-6-luna:high"}, Routing: provider.Ordered,
Classifier: "codex/gpt-6-luna", Rules: []provider.Rule{{Use: "codex/gpt-6-luna:high", Intent: "feature"}}}); err != nil {
t.Fatal(err)
}
s := New()
keys, secrets := newCaller(t, "Held")
if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{"codex/spare@example.com"}}); err != nil {
t.Fatal(err)
}
for i := range 3 {
noRests()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"group/r","messages":[{"role":"user","content":"add feature `+fmt.Sprint(i)+`"}]}`))
req.Header.Set("Authorization", "Bearer "+secrets[0])
req.Header.Set("x-session-id", fmt.Sprint("k", i))
s.Handler().ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("turn %d: %d %s", i, rec.Code, rec.Body.String())
}
a := asked()
if len(a) < 2 {
t.Fatalf("turn %d: %d requests reached the backend, not the classifier's and the turn's", i, len(a))
}
for _, a := range a {
if a != "acct-2" {
t.Fatalf("turn %d: the classifier was asked on %q, not the key's acct-2", i, a)
}
}
}
}
+44 -20
View File
@@ -25,6 +25,7 @@ import (
"sync"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/lazyre"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
@@ -53,8 +54,10 @@ var classifyUnit = time.Second
// classifier asks a model which of intents text is — the intent, or ""
// for none of them — and, when effort, how much reasoning the turn wants. prev is what
// the conversation's turn before was said to be: a message that only
// carries on from it is the same.
type classifier func(model string, intents []string, prev before, effort bool, text string) (verdict, error)
// carries on from it is the same. held is the accounts the group asking
// holds the call to (classifierHeld): its question is the group's spend,
// so it goes on the group's accounts as the turn does (AWilsonPeng on X).
type classifier func(held access.Identity, model string, intents []string, prev before, effort bool, text string) (verdict, error)
// before is what the classifier said of a conversation's turn before, and
// what was said in it (turnBefore): a short follow-up (继续, fix that) says
@@ -149,7 +152,16 @@ func cutShort(model string, wait, full time.Duration) error {
// classifier that failed is left to rest for classifyRest rather than
// making every turn wait out its timeout. Concurrent calls asking the
// same question share the answer in flight.
func classify(ask classifier, model string, intents []string, prev before, effort bool, text string) (v verdict, cached bool, err error) {
//
// An answer is the same on whichever account it was asked, so held
// doesn't part the answers kept; a failure is the accounts' it was asked
// on, so one account's limit rests the classifier for the groups held to
// it alone.
func classify(ask classifier, held access.Identity, model string, intents []string, prev before, effort bool, text string) (v verdict, cached bool, err error) {
rest := model
if len(held.Accounts) > 0 {
rest += "\x00" + strings.Join(held.Accounts, "\x00")
}
h := sha256.New()
h.Write([]byte(model + "\x00" + strings.ToLower(strings.Join(intents, "\x00")) + "\x00" + prev.Intent + "\x00" + prev.Effort + "\x00" + prev.User + "\x00" + prev.Reply + "\x00" + strconv.FormatBool(effort) + "\x00" + text))
key := hex.EncodeToString(h.Sum(nil))
@@ -164,7 +176,7 @@ func classify(ask classifier, model string, intents []string, prev before, effor
<-c.done
return c.v, c.err == nil, c.err
}
if f, ok := classified.failed[model]; ok && now.Sub(f.at) < classifyRest {
if f, ok := classified.failed[rest]; ok && now.Sub(f.at) < classifyRest {
classified.Unlock()
return verdict{}, false, fmt.Errorf("%s failed %s ago (%s); not asked again for now", model, now.Sub(f.at).Round(time.Second), f.err)
}
@@ -178,14 +190,14 @@ func classify(ask classifier, model string, intents []string, prev before, effor
close(c.done)
classified.Unlock()
}()
v, err = ask(model, intents, prev, effort, text)
v, err = ask(held, model, intents, prev, effort, text)
classified.Lock()
defer classified.Unlock()
c.err = err
if err != nil {
f := classifyFailure{err: err.Error(), at: time.Now()}
if !errors.As(err, new(answerError)) && !errors.As(err, new(waitSpent)) {
classified.failed[model] = f
classified.failed[rest] = f
}
if was, ok := classified.last[model]; !ok || was.err != f.err {
// said once in the log, not at every turn it fails the same way
@@ -195,7 +207,7 @@ func classify(ask classifier, model string, intents []string, prev before, effor
return verdict{}, false, err
}
c.v = v
delete(classified.failed, model)
delete(classified.failed, rest)
delete(classified.last, model)
classified.m[key] = classifiedAs{v: v, at: time.Now()}
if len(classified.m) > 4096 {
@@ -446,13 +458,13 @@ func classifierEffortField(model string) string { return "classifier effort\x00"
// relay that knows no reasoning_effort, one that takes none of the
// levels — is asked again without it, as before, and from then on: the
// classifier answers wherever it did.
func (s *Server) askLeast(wait time.Duration, model string, body func(effort string) []byte) (string, error) {
func (s *Server) askLeast(wait time.Duration, held access.Identity, model string, body func(effort string) []byte) (string, error) {
effort := classifyEffort(model)
p, m, ok := provider.Resolve(model)
if effort != "" && ok && !s.fits(p.ID, classifierEffortField(m), provider.Chat) {
effort = ""
}
a, err := s.askChat(wait, model, body(effort))
a, err := s.askChat(wait, held, model, body(effort))
var f chatFailed
if effort == "" || !errors.As(err, &f) {
return a, err
@@ -461,7 +473,7 @@ func (s *Server) askLeast(wait time.Duration, model string, body func(effort str
return a, err
}
s.markUnfit(p.ID, classifierEffortField(m), provider.Chat)
return s.askChat(wait, model, body(""))
return s.askChat(wait, held, model, body(""))
}
// chatFailed is a classifier's answer that was an error, with its status
@@ -484,7 +496,12 @@ type chatFailed struct {
func (s *Server) askWaited(ctx context.Context) classifier {
var mu sync.Mutex
var until time.Time
return func(model string, intents []string, prev before, effort bool, text string) (verdict, error) {
// the caller's accounts (a gateway key's, the group the request names)
// hold its classifier's calls too, as they hold magpie's other calls
// for it (accountHolds): only the accounts, not the key's models, as
// the classifier is the group's pick, not the caller's
caller := access.Caller(ctx)
return func(held access.Identity, model string, intents []string, prev before, effort bool, text string) (verdict, error) {
mu.Lock()
now := time.Now()
if until.IsZero() {
@@ -496,7 +513,8 @@ func (s *Server) askWaited(ctx context.Context) classifier {
return verdict{}, waitSpent{fmt.Errorf("%s not asked: the request's classifier wait of %s was spent by the routing group above", model, classifyTimeout())}
}
defer noteWait(ctx, "decision model")()
return s.askClassifierIn(left, model, intents, prev, effort, text)
who := access.Identity{Accounts: caller.Accounts, Group: caller.Group}.HeldToGroup(held.Group, held.Accounts)
return s.askClassifierIn(left, who, model, intents, prev, effort, text)
}
}
@@ -505,17 +523,18 @@ func (s *Server) askWaited(ctx context.Context) classifier {
// intents the message is and, when effort, how hard the turn is, each in a
// call of its own, at once.
func (s *Server) askClassifier(model string, intents []string, prev before, effort bool, text string) (verdict, error) {
return s.askClassifierIn(classifyTimeout(), model, intents, prev, effort, text)
return s.askClassifierIn(classifyTimeout(), access.Identity{}, model, intents, prev, effort, text)
}
// askClassifierIn is askClassifier given wait to answer in, all of the
// classifier's wait or what a request has left of it (askWaited).
func (s *Server) askClassifierIn(wait time.Duration, model string, intents []string, prev before, effort bool, text string) (verdict, error) {
// classifier's wait or what a request has left of it (askWaited), held
// to who's accounts, when it names any.
func (s *Server) askClassifierIn(wait time.Duration, who access.Identity, model string, intents []string, prev before, effort bool, text string) (verdict, error) {
if p, m, ok := provider.Resolve(model); ok && p.DecidesModel(m) {
return s.askDecider(wait, p, m, intents, prev, effort, text)
return s.askDecider(wait, who, p, m, intents, prev, effort, text)
}
// a group of decision models: each in turn (decide_group.go)
if v, ok, err := s.askDecisionGroup(wait, model, intents, prev, effort, text); ok {
if v, ok, err := s.askDecisionGroup(wait, who, model, intents, prev, effort, text); ok {
return v, err
}
var v verdict
@@ -526,7 +545,7 @@ func (s *Server) askClassifierIn(wait time.Duration, model string, intents []str
go func() {
defer wg.Done()
var a string
if a, ierr = s.askLeast(wait, model, func(effort string) []byte { return classifyBody(model, effort, intents, prev, text) }); ierr == nil {
if a, ierr = s.askLeast(wait, who, model, func(effort string) []byte { return classifyBody(model, effort, intents, prev, text) }); ierr == nil {
v.Intent, v.Said, ierr = readIntent(a, intents)
}
}()
@@ -536,7 +555,7 @@ func (s *Server) askClassifierIn(wait time.Duration, model string, intents []str
go func() {
defer wg.Done()
var a string
if a, eerr = s.askLeast(wait, model, func(effort string) []byte { return effortBody(model, effort, prev, text) }); eerr == nil {
if a, eerr = s.askLeast(wait, who, model, func(effort string) []byte { return effortBody(model, effort, prev, text) }); eerr == nil {
v.Effort, v.Score, eerr = readEffort(a)
}
}()
@@ -605,7 +624,9 @@ func readEffort(answer string) (string, float64, error) {
// askChat sends a chat model body through the gateway and returns its
// answer's text, if it comes in wait.
func (s *Server) askChat(wait time.Duration, model string, body []byte) (string, error) {
// held, when it names accounts, holds it to them, as heldByGroup does a
// request through a group.
func (s *Server) askChat(wait time.Duration, held access.Identity, model string, body []byte) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), wait)
defer cancel()
r, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://magpie/v1/chat/completions", nil)
@@ -614,6 +635,9 @@ func (s *Server) askChat(wait time.Duration, model string, body []byte) (string,
}
r.Header.Set("Content-Type", "application/json")
r.Header.Set("User-Agent", RouterAgent)
if len(held.Accounts) > 0 {
r = r.WithContext(access.WithIdentity(r.Context(), held))
}
w := httptest.NewRecorder()
s.serve(w, r, provider.Chat, body)
if ctx.Err() != nil {
+16 -14
View File
@@ -7,6 +7,8 @@ import (
"testing"
"testing/synctest"
"time"
"github.com/yetone/magpie/internal/access"
)
type classifyResult struct {
@@ -37,13 +39,13 @@ func TestConcurrentClassificationSharesAnswer(t *testing.T) {
results := make(chan classifyResult, 17)
var calls atomic.Int32
want := verdict{Intent: "refactoring", Effort: "high", Score: 2, Sure: 0.9}
ask := func(string, []string, before, bool, string) (verdict, error) {
ask := func(access.Identity, string, []string, before, bool, string) (verdict, error) {
calls.Add(1)
<-release
return want, nil
}
run := func() {
v, cached, err := classify(ask, t.Name(), []string{"refactoring"}, before{}, true, "rename this package")
v, cached, err := classify(ask, access.Identity{}, t.Name(), []string{"refactoring"}, before{}, true, "rename this package")
results <- classifyResult{v, cached, err}
}
go run()
@@ -70,7 +72,7 @@ func TestConcurrentClassificationSharesAnswer(t *testing.T) {
if shared != 16 {
t.Fatalf("shared answers = %d, want 16", shared)
}
v, cached, err := classify(ask, t.Name(), []string{"refactoring"}, before{}, true, "rename this package")
v, cached, err := classify(ask, access.Identity{}, t.Name(), []string{"refactoring"}, before{}, true, "rename this package")
if v != want || !cached || err != nil || calls.Load() != 1 {
t.Fatalf("completed cache = %+v, %v, %v; calls = %d", v, cached, err, calls.Load())
}
@@ -84,7 +86,7 @@ func TestConcurrentClassificationDistinctKeys(t *testing.T) {
results := make(chan classifyResult, 7)
var calls atomic.Int32
want := verdict{Intent: "refactoring"}
ask := func(string, []string, before, bool, string) (verdict, error) {
ask := func(access.Identity, string, []string, before, bool, string) (verdict, error) {
calls.Add(1)
<-release
return want, nil
@@ -105,7 +107,7 @@ func TestConcurrentClassificationDistinctKeys(t *testing.T) {
{t.Name(), []string{"refactoring"}, before{}, false, "test"},
} {
go func() {
v, cached, err := classify(ask, input.model, input.intents, input.prev, input.effort, input.text)
v, cached, err := classify(ask, access.Identity{}, input.model, input.intents, input.prev, input.effort, input.text)
results <- classifyResult{v, cached, err}
}()
}
@@ -139,7 +141,7 @@ func TestConcurrentClassificationSharesFailure(t *testing.T) {
results := make(chan classifyResult, 2)
var calls atomic.Int32
want := verdict{Intent: "refactoring"}
ask := func(string, []string, before, bool, string) (verdict, error) {
ask := func(access.Identity, string, []string, before, bool, string) (verdict, error) {
n := calls.Add(1)
<-release
if n == 1 {
@@ -148,7 +150,7 @@ func TestConcurrentClassificationSharesFailure(t *testing.T) {
return want, nil
}
run := func() {
v, cached, err := classify(ask, t.Name(), []string{"refactoring"}, before{}, false, "rename")
v, cached, err := classify(ask, access.Identity{}, t.Name(), []string{"refactoring"}, before{}, false, "rename")
results <- classifyResult{v, cached, err}
}
go run()
@@ -166,13 +168,13 @@ func TestConcurrentClassificationSharesFailure(t *testing.T) {
}
}
if tc.rests {
_, cached, err := classify(ask, t.Name(), []string{"refactoring"}, before{}, false, "rename")
_, cached, err := classify(ask, access.Identity{}, t.Name(), []string{"refactoring"}, before{}, false, "rename")
if cached || err == nil || !strings.Contains(err.Error(), "not asked again") || calls.Load() != 1 {
t.Fatalf("cooldown = %v, %v; calls = %d", cached, err, calls.Load())
}
time.Sleep(classifyRest + time.Second)
}
v, cached, err := classify(ask, t.Name(), []string{"refactoring"}, before{}, false, "rename")
v, cached, err := classify(ask, access.Identity{}, t.Name(), []string{"refactoring"}, before{}, false, "rename")
if v != want || cached || err != nil || calls.Load() != 2 {
t.Fatalf("retry = %+v, %v, %v; calls = %d", v, cached, err, calls.Load())
}
@@ -188,18 +190,18 @@ func TestConcurrentClassificationPanicReleasesWaiters(t *testing.T) {
panicked := make(chan any, 1)
result := make(chan classifyResult, 1)
var calls atomic.Int32
ask := func(string, []string, before, bool, string) (verdict, error) {
ask := func(access.Identity, string, []string, before, bool, string) (verdict, error) {
calls.Add(1)
<-release
panic("classifier panic")
}
go func() {
defer func() { panicked <- recover() }()
classify(ask, t.Name(), nil, before{}, false, "rename")
classify(ask, access.Identity{}, t.Name(), nil, before{}, false, "rename")
}()
synctest.Wait()
go func() {
v, cached, err := classify(ask, t.Name(), nil, before{}, false, "rename")
v, cached, err := classify(ask, access.Identity{}, t.Name(), nil, before{}, false, "rename")
result <- classifyResult{v, cached, err}
}()
synctest.Wait()
@@ -212,8 +214,8 @@ func TestConcurrentClassificationPanicReleasesWaiters(t *testing.T) {
t.Fatalf("panic waiter = %+v; calls = %d", got, calls.Load())
}
want := verdict{Intent: "refactoring"}
retry := func(string, []string, before, bool, string) (verdict, error) { return want, nil }
v, cached, err := classify(retry, t.Name(), nil, before{}, false, "rename")
retry := func(access.Identity, string, []string, before, bool, string) (verdict, error) { return want, nil }
v, cached, err := classify(retry, access.Identity{}, t.Name(), nil, before{}, false, "rename")
if v != want || cached || err != nil {
t.Fatalf("retry after panic = %+v, %v, %v", v, cached, err)
}
+3 -2
View File
@@ -5,6 +5,7 @@ import (
"strings"
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
@@ -192,7 +193,7 @@ func TestChatClassifierIsToldWhatCameBefore(t *testing.T) {
func TestClassifyKeepsAnAnswerPerTurnBefore(t *testing.T) {
resetClassified(t)
n := 0
ask := func(_ string, _ []string, prev before, _ bool, _ string) (verdict, error) {
ask := func(_ access.Identity, _ string, _ []string, prev before, _ bool, _ string) (verdict, error) {
n++
return verdict{Intent: prev.User}, nil
}
@@ -205,7 +206,7 @@ func TestClassifyKeepsAnAnswerPerTurnBefore(t *testing.T) {
{before{User: "design the sync protocol"}, false},
{before{User: "design the sync protocol", Reply: "Here is a plan."}, false},
} {
v, cached, err := classify(ask, t.Name(), []string{"rename a variable", "design the sync protocol"}, c.prev, false, "继续")
v, cached, err := classify(ask, access.Identity{}, t.Name(), []string{"rename a variable", "design the sync protocol"}, c.prev, false, "继续")
if err != nil || cached != c.cached || v.Intent != c.prev.User {
t.Fatalf("%+v: %+v cached %v %v", c.prev, v, cached, err)
}
+2 -1
View File
@@ -11,6 +11,7 @@ import (
"testing"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
@@ -248,7 +249,7 @@ func TestIntentNotAskedWhenItCantMatter(t *testing.T) {
g, ms, _ := provider.FindGroup("group/r")
img := &Request{Messages: []Message{{Role: "user", Parts: []Part{{Kind: Image}}}}}
asked := 0
hit := ruleFor("img", g, ms, img, "claude", func(string, []string, before, bool, string) (verdict, error) {
hit := ruleFor("img", g, ms, img, "claude", func(access.Identity, string, []string, before, bool, string) (verdict, error) {
asked++
return verdict{Intent: "debugging"}, nil
}, "")
+8 -4
View File
@@ -17,6 +17,7 @@ import (
"strings"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
@@ -329,7 +330,7 @@ func (e decideRefused) Unwrap() error { return e.err }
// accounts in the group's order, each asked as Jev is (askJev) until one
// answers, the one that failed resting as it would for a chat. ok is false
// when model names no decision group.
func (s *Server) askDecisionGroup(wait time.Duration, model string, intents []string, prev before, effort bool, text string) (v verdict, ok bool, err error) {
func (s *Server) askDecisionGroup(wait time.Duration, who access.Identity, model string, intents []string, prev before, effort bool, text string) (v verdict, ok bool, err error) {
if !provider.IsGroupRef(model) {
return verdict{}, false, nil
}
@@ -341,8 +342,9 @@ func (s *Server) askDecisionGroup(wait time.Duration, model string, intents []st
ms, _ = provider.PausedOut(g, ms, RouterAgent, "", ruleClock())
cs, _, _ := s.decideTries(g, ms)
// held to the group's own accounts, if it is: no request carries a
// caller here to hold (heldByGroup)
cs = slices.DeleteFunc(cs, func(c candidate) bool { return groupHeld(c, []provider.Group{g}) != "" })
// caller here to hold (heldByGroup); and to who's, the accounts the
// group asking holds its classifier to
cs = slices.DeleteFunc(cs, func(c candidate) bool { return groupHeld(c, []provider.Group{g}) != "" || !accountAllowed(who, c) })
cs = probeOne(cs) // of those resting, only the one back soonest (#1799)
if len(cs) == 0 {
return verdict{}, true, fmt.Errorf("no decision model of the group %s can be asked now", g.Name)
@@ -354,8 +356,10 @@ func (s *Server) askDecisionGroup(wait time.Duration, model string, intents []st
// askDecider is askClassifier for one decision provider's model: its keys
// or accounts in its routing's order (decideKeys), each asked until one
// answers, as a decision group's are.
func (s *Server) askDecider(wait time.Duration, p provider.Provider, model string, intents []string, prev before, effort bool, text string) (verdict, error) {
func (s *Server) askDecider(wait time.Duration, who access.Identity, p provider.Provider, model string, intents []string, prev before, effort bool, text string) (verdict, error) {
cs, _ := s.decideKeys(p, model)
// held to who's accounts: those the group asking holds it to
cs = slices.DeleteFunc(cs, func(c candidate) bool { return !accountAllowed(who, c) })
cs = probeOne(cs) // of those resting, only the one back soonest (#1799)
if len(cs) == 0 {
return verdict{}, fmt.Errorf("no key or account of %s may be asked %s now", p.Name, model)
@@ -1,6 +1,7 @@
package gateway
import (
"github.com/yetone/magpie/internal/access"
"io"
"net/http"
"net/http/httptest"
@@ -127,7 +128,7 @@ func TestDecisionKeyCutShortIsNotRested(t *testing.T) {
t.Fatal(err)
}
s := New()
_, err := s.askClassifierIn(50*time.Millisecond, "jw/jev-latest", []string{"feature", "bug"}, before{}, false, "fix this")
_, err := s.askClassifierIn(50*time.Millisecond, access.Identity{}, "jw/jev-latest", []string{"feature", "bug"}, before{}, false, "fix this")
if err == nil || !strings.Contains(err.Error(), "left of the request's classifier wait") {
t.Fatalf("cut short: %v", err)
}
+34 -1
View File
@@ -7,6 +7,7 @@ package gateway
// meanwhile.
import (
"cmp"
"crypto/sha256"
"encoding/hex"
"fmt"
@@ -16,6 +17,7 @@ import (
"sync"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
)
@@ -351,7 +353,7 @@ func ruleFor(key string, g provider.Group, ms []provider.Member, req *Request, a
c.Error = "the message has no words to classify"
default:
t0 := time.Now()
v, cached, err := classify(ask, g.Classifier, intents, prev, effort, text)
v, cached, err := classify(ask, classifierHeld(g, ms), g.Classifier, intents, prev, effort, text)
classifiedFor(g.ID, g.Classifier, err)
v.Intent = intentOf(v, g) // the group's own sure of an intent (#5101)
c.Intent, c.Said, c.Cached, c.Ms = v.Intent, v.Said, cached, int(time.Since(t0).Milliseconds())
@@ -949,3 +951,34 @@ func pausedError(asked string, paused []provider.Paused) string {
}
return fmt.Sprintf("every model of %s is paused now by its rules: %s; change the rules on Magpie's Routing page, or ask again when they end", asked, strings.Join(bits, ", "))
}
// classifierHeld is the accounts g holds its classifier's calls to: its
// own (Group.Accounts), and, when the classifier is one of its members
// that names its account (Member.Account), that account — every one of
// them, when the model is a member once for each of several. The
// classifier's questions are the group's spend as much as its turns are
// (AWilsonPeng on X: GPT-6 Luna held to one of two ChatGPT accounts, its
// classifier its own member GPT-6-Luna · Codex, which asked on both). A
// group, as the classifier, holds itself to its own when it is asked.
func classifierHeld(g provider.Group, ms []provider.Member) access.Identity {
name := cmp.Or(g.Name, g.ID)
who := access.Identity{}.HeldToGroup(name, g.Accounts)
if provider.IsGroupRef(g.Classifier) {
return who
}
p, model, ok := provider.Resolve(g.Classifier)
if !ok {
return who
}
var pinned []string
for _, m := range ms {
if m.Provider.ID != p.ID || m.Model != model {
continue
}
if m.Account == "" {
return who // on any account the group allows
}
pinned = append(pinned, m.Account)
}
return who.HeldToGroup(name, pinned)
}