diff --git a/docs/reference.md b/docs/reference.md index 7f1fb85ad..084be062a 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1046,6 +1046,22 @@ the vendor's cache of it is worth keeping), `session`, `turn` or `off`. `models=` replaces the whole list, in order; a bare model id works when only one provider serves it. +A group can also be of decision models alone (Jev and the like: TypeSafe's, +Bailian's `decision-model-preview`, a plugin's marked models) — never mixed +with models that hold a conversation. It is not offered to agents; it is asked +at `POST /v1/systemone` with `"model":"group/"` (or its id or name), and a +chat group can take it as its classifier. Each of its models' keys and +accounts is asked in the group's routing order: one that fails as a chat +request would fail over (a 429, a 5xx, an unreachable host, an exhausted +key) rests and the next is asked, and the Routing page's Requests list shows +every try. It takes no patterns, rules, classifier, effort or fast mode. + +```sh +magpie group add Jevs models=typesafe/jev-latest,bailian-token-plan/decision-model-preview routing=order +curl -s localhost:3425/v1/systemone -H 'Authorization: Bearer magpie' \ + -d '{"model":"group/jevs","state":{"message":"fix the login bug"},"questions":{"intent":{"type":"choice","choices":["bug","feature"]}}}' +``` + The Routing page's Requests list defaults to the time-ordered By request view. Choose By session to group calls by the agent's session ID; the page remembers your choice across reloads. diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 28c51ca27..ccbf0e460 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -88,6 +88,24 @@ are described in [Providers and accounts](providers-accounts.md#remote-magpie). System One uses `RouteDecider` and `postDecide` in [`decide.go`](../../internal/gateway/decide.go), taking one provider prefix off at each hop and preserving the state, questions and vendor errors. +A model naming a group of decision models (`provider.Group.Decides`: every +member a decision model; `cleanDecisionGroup` in +[`decide_group.go`](../../internal/provider/decide_group.go) refuses a mixed +one, one inside a chat group, and patterns, rules, effort or fast mode on +it) goes to `serveDecisionGroup` in +[`decide_group.go`](../../internal/gateway/decide_group.go) instead +(`decisionGroupOf`: `group/`, or a group's id or name by `GroupFor`). It +plans the members' keys and accounts with `planGroup` (`perKeyBarred` keeps +a decision-only provider's keys: `DecidesModel`), applies a gateway key's +model and account limits and pause rules as for a chat, and tries each +candidate in turn: a `retryable` failure that is not the request's own +(`shapeRefused`, `promptRefused`, `protectionRefused`) rests it +(`decideFailed` → `restAfter`) and the next is asked; the last one's answer +is passed on. Every try is a `Try` of one route; one usage row is written +for the answer. A group classifier of decision models fails over the same +way (`askDecisionGroup`, `decideRefused` carrying the vendor's status). A +decision group is kept out of the agents' catalog (`groupEntries`), and a +conversation asked of it is refused 400 pointing at `/v1/systemone`. [`embeddings.go`](../../internal/gateway/embeddings.go) relays retrieval bodies and options, [`draw.go`](../../internal/gateway/draw.go) sends images to the remote's images API, and [`video.go`](../../internal/gateway/video.go) diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index 0d6181a03..b6ad2b413 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -50,7 +50,7 @@ Qoder plugins without `auth.checkin` still use [`qoder_checkin.go`](../../intern A plugin can serve TypeSafe's System One for its provider (#1514). Its `config` hook sets `decide: true` on the provider, and `decides: true` on a model that answers questions rather than a conversation, in the `config` hook or on the `models` hook's list. The host passes both through (`plugin.Provider.Decide`, `plugin.Model.Decides`). [`pluginProvider`](../../internal/provider/plugins.go) then sets the provider's `Decide` to `plugin:///v1`, its own base: `pluginFetch` sends nowhere but the loader's host, so a decision address of the plugin's own couldn't be reached. `AskSystemOne` and the gateway's classifier post `/v1/systemone` with `Provider.Do`, which reaches the loader's `fetch` as `{baseURL}/systemone` with the account's sign-in. -In [`decide.go`](../../internal/provider/decide.go) a plugin provider's decision models are the ones it marks (`pluginMarks`, read from the plugin's current listing) and Jev's by name (`jev-*`). They are kept from agents (`isDecision` in `buildEntries`), refused for chat ("only decides"), refused as a group member, and offered as a group's classifier (`Deciders`, `DecisionModels`). A mark counts only when the provider says `decide`; without it every model stays one to chat with. A plugin provider's editor (the account editor) has no address fields, so this address is never typed; the GUI marks the decision models from `deciders`. +In [`decide.go`](../../internal/provider/decide.go) a plugin provider's decision models are the ones it marks (`pluginMarks`, read from the plugin's current listing) and Jev's by name (`jev-*`). They are kept from agents (`isDecision` in `buildEntries`), refused for chat ("only decides"), refused as a member of a group beside models that hold a conversation (a group of decision models alone answers `/v1/systemone`: [gateway-routing](gateway-routing.md#remote-magpie-apis)), and offered as a group's classifier (`Deciders`, `DecisionModels`). A mark counts only when the provider says `decide`; without it every model stays one to chat with. A plugin provider's editor (the account editor) has no address fields, so this address is never typed; the GUI marks the decision models from `deciders`. ## Two plugins for one provider id @@ -124,7 +124,7 @@ The GUI's plugin integration includes `subOf`, `pluginSubs`, and `startPluginSig Gateway parity tests in [`plugin_parity_test.go`](../../internal/gateway/plugin_parity_test.go) and other `plugin_*_test.go` files compare or exercise plugin paths. A built-in test alone does not establish moved-user behavior. Inspect each test's fixture to confirm that it covers the provider and operation being changed. -[`plugin_decide_test.go`](../../internal/gateway/plugin_decide_test.go) runs the fake plugin (`FAKE_DECIDE`) with a decision API: its marked and `jev-*` models are classifiers and not offered to agents, chat to one is refused, a group saves one as classifier and not as member, and each classifier's question reaches the fake vendor at `/v1/systemone` through the plugin's fetch. With `FAKE_DECIDE=models` the marks without `decide` change nothing. +[`plugin_decide_test.go`](../../internal/gateway/plugin_decide_test.go) runs the fake plugin (`FAKE_DECIDE`) with a decision API: its marked and `jev-*` models are classifiers and not offered to agents, chat to one is refused, a group saves one as classifier, not beside a chat model, and a group of decision models alone, and each classifier's question reaches the fake vendor at `/v1/systemone` through the plugin's fetch. With `FAKE_DECIDE=models` the marks without `decide` change nothing. [`plugin_checkin_test.go`](../../internal/provider/plugin_checkin_test.go) runs the fake plugin's `auth.checkin` (`FAKE_CHECKIN`) through the schedule: off, each outcome, no second press the same day, failures only after the retry window, the next day, cards and Settings, and the vendor check-in stepping aside. `plugin-checkin.test.cjs` covers the card row and the Settings tab. diff --git a/groups_cli.go b/groups_cli.go index 98138a7ef..05df6342a 100644 --- a/groups_cli.go +++ b/groups_cli.go @@ -230,6 +230,11 @@ func memberResolver(keep []string) func(string) (string, error) { if slices.Contains(ids, id) || slices.Contains(keep, id) { return id, nil } + if provider.IsDecider(id) { + // a decision model, for a group of decision models alone, + // asked at /v1/systemone (SaveGroup refuses a mixed one) + return id, nil + } for _, x := range ids { // a provider/model id in another case if strings.EqualFold(x, id) { return x, nil diff --git a/groups_decide_cli_test.go b/groups_decide_cli_test.go new file mode 100644 index 000000000..4846baaed --- /dev/null +++ b/groups_decide_cli_test.go @@ -0,0 +1,32 @@ +package main + +import ( + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// magpie group add takes decision models for a group of them alone, asked +// at /v1/systemone (ARNO on Discord), and refuses one beside a chat model. +func TestGroupAddDecisionModels(t *testing.T) { + groupsHome(t) + for _, p := range []provider.Provider{ + {ID: "ja", Name: "JA", Key: "k1", Decide: "http://127.0.0.1:1/v1"}, + {ID: "jb", Name: "JB", Key: "k2", Decide: "http://127.0.0.1:1/v1"}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + g, err := addGroup("Jevs", []string{"models=ja/jev-latest,jb/jev-latest", "routing=order"}) + if err != nil { + t.Fatal(err) + } + if strings.Join(g.Members, " ") != "ja/jev-latest jb/jev-latest" || !g.Decides() { + t.Fatalf("%+v", g) + } + if _, err := addGroup("Mixed", []string{"models=ja/jev-latest,a/m"}); err == nil || !strings.Contains(err.Error(), "decision models only") { + t.Fatalf("mixed: %v", err) + } +} diff --git a/internal/gateway/classify.go b/internal/gateway/classify.go index 9badad51a..153b5a834 100644 --- a/internal/gateway/classify.go +++ b/internal/gateway/classify.go @@ -256,6 +256,10 @@ func (s *Server) askClassifier(model string, intents []string, prev before, effo if p, m, ok := provider.Resolve(model); ok && p.DecidesModel(m) { return s.askJev(p, m, intents, prev, effort, text) } + // a group of decision models: each in turn (decide_group.go) + if v, ok, err := s.askDecisionGroup(model, intents, prev, effort, text); ok { + return v, err + } var v verdict var ierr, eerr error var wg sync.WaitGroup diff --git a/internal/gateway/decide.go b/internal/gateway/decide.go index 9b485b584..92d5eac7c 100644 --- a/internal/gateway/decide.go +++ b/internal/gateway/decide.go @@ -320,7 +320,7 @@ func (s *Server) askJev(p provider.Provider, model string, intents []string, pre // and answers in its own way (decideAsk, decideAnswer). func (s *Server) systemOne(ctx context.Context, p provider.Provider, model string, body []byte) ([]byte, error) { start := time.Now() - status, b, _, err := s.postDecide(ctx, p, model, body) + status, b, header, err := s.postDecide(ctx, p, model, body) if err != nil { if ctx.Err() != nil { return nil, fmt.Errorf("%s gave no answer in %s", p.Name, classifyTimeout) @@ -328,7 +328,7 @@ func (s *Server) systemOne(ctx context.Context, p provider.Provider, model strin return nil, err } if status >= 300 { - return nil, fmt.Errorf("%s: %s", p.Name, provider.APIError(b, fmt.Sprintf("%d %s", status, http.StatusText(status)))) + return nil, decideRefused{fmt.Errorf("%s: %s", p.Name, provider.APIError(b, fmt.Sprintf("%d %s", status, http.StatusText(status)))), status, header, b} } var use struct { Model string `json:"model"` // the one that answered, when the reply says @@ -349,20 +349,20 @@ func (s *Server) systemOne(ctx context.Context, p provider.Provider, model strin } // postDecide posts body to p's decision API and returns the status, body -// and Content-Type. A success is rewritten into System One's shape when +// and headers (its Content-Type, a refusal's Retry-After). A success is rewritten into System One's shape when // the provider answers in another one. DecideURL and Sign errors are as // they are; a transport error is named with p. -func (s *Server) postDecide(ctx context.Context, p provider.Provider, model string, body []byte) (int, []byte, string, error) { +func (s *Server) postDecide(ctx context.Context, p provider.Provider, model string, body []byte) (int, []byte, http.Header, error) { ctx = s.metered(p.Via(ctx), p, "") // counted against its MaxRPM (rpm.go) u, err := p.DecideModelURL(ctx, model) if err != nil { - return 0, nil, "", err + return 0, nil, nil, err } via := p.DecideVia() body = provider.DecideAsk(via, model, body) req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(body)) if err != nil { - return 0, nil, "", err + return 0, nil, nil, err } req.Header.Set("Content-Type", "application/json") req.Header.Set("User-Agent", RouterAgent) @@ -378,18 +378,18 @@ func (s *Server) postDecide(ctx context.Context, p provider.Provider, model stri req.Header.Set("ai-evaluation-model-specification-version", "4") } if err := p.Sign(ctx, req, provider.Chat, body); err != nil { - return 0, nil, "", err + return 0, nil, nil, err } res, err := p.Do(s.client, req) if err != nil { - return 0, nil, "", fmt.Errorf("%s: %v", p.Name, err) + return 0, nil, nil, fmt.Errorf("%s: %v", p.Name, err) } defer res.Body.Close() b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) if res.StatusCode < 300 { b = provider.DecideAnswer(via, b) } - return res.StatusCode, b, res.Header.Get("Content-Type"), nil + return res.StatusCode, b, res.Header, nil } // maxSystemOneBody is the most a System One request may be; larger is 413 @@ -415,6 +415,15 @@ func (s *Server) serveSystemOne(w http.ResponseWriter, r *http.Request) { writeError(w, provider.Chat, http.StatusBadRequest, "not a System One request") return } + // a routing group of decision models: each of them in turn + // (decide_group.go) + if g, ms, ok, status, err := decisionGroupOf(q.Model); err != nil { + writeError(w, provider.Chat, status, err.Error()) + return + } else if ok { + s.serveDecisionGroup(w, r, body, q.Model, g, ms) + return + } p, model, err := provider.RouteDecider(q.Model) if err != nil { writeError(w, provider.Chat, provider.DecideRouteStatus(err), err.Error()) @@ -475,7 +484,8 @@ func (s *Server) serveSystemOne(w http.ResponseWriter, r *http.Request) { t.Usage = routeUsage(p.ID, model, used) }) } - status, b, ctype, err := s.postDecide(r.Context(), p, model, body) + status, b, header, err := s.postDecide(r.Context(), p, model, body) + ctype := header.Get("Content-Type") if err != nil { writeError(w, provider.Chat, http.StatusBadGateway, err.Error()) end(http.StatusBadGateway, err.Error(), 0) diff --git a/internal/gateway/decide_group.go b/internal/gateway/decide_group.go new file mode 100644 index 000000000..e283baa65 --- /dev/null +++ b/internal/gateway/decide_group.go @@ -0,0 +1,269 @@ +package gateway + +// A decision group (provider/decide_group.go) is asked at /v1/systemone as +// a chat group is asked a conversation (ARNO on Discord: 给decision模型也加 +// 上group功能): "group/", or the group's id or name, goes to its models' +// keys and accounts in the group's routing order, and one that fails as a +// chat request would fail over (retryable) rests, the next asked, each try +// in the routing log. + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "slices" + "strings" + "time" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" +) + +// decisionGroupOf is the decision group a System One request's model names: +// "group/", or a group's id or name as GroupFor takes it. ok is false +// when it names none, and the model goes to RouteDecider; err is said to +// the caller when it names a group System One can't ask (a chat group, or +// one switched off or gone), with its status. +func decisionGroupOf(asked string) (g provider.Group, ms []provider.Member, ok bool, status int, err error) { + ref := strings.TrimSpace(asked) + explicit := strings.HasPrefix(ref, provider.GroupPrefix) + if !explicit { + gid, found := provider.GroupFor(ref) + if !found { + return g, nil, false, 0, nil + } + ref = gid + } + g, ms, found := provider.FindGroup(ref) + if !found { + if !explicit { + return g, nil, false, 0, nil + } + if off, isOff := provider.DisabledGroup(ref); isOff { + return g, nil, false, http.StatusNotFound, fmt.Errorf("the routing group %s is switched off in Magpie, so %q is not served; switch it on again on Magpie's Routing page to use it", off.Name, asked) + } + return g, nil, false, http.StatusNotFound, fmt.Errorf("magpie has no routing group %q", strings.TrimPrefix(ref, provider.GroupPrefix)) + } + if !g.Decides() { + if !explicit { + return provider.Group{}, nil, false, 0, nil // a chat group by that name: a model of it may still be one + } + return g, nil, false, http.StatusBadRequest, fmt.Errorf("the routing group %s holds models that hold conversations; System One asks a group of decision models, or a decision model as \"provider/model\"", g.Name) + } + return g, ms, true, 0, nil +} + +// decideTries are the keys and accounts of a decision group's models, in +// the group's routing order — those resting after the rest, as for a +// chat — with the models of it that answer no System One left out. left +// and order are what the routing log shows of the plan. +func (s *Server) decideTries(g provider.Group, ms []provider.Member) ([]candidate, planned, []provider.Member) { + ms = slices.DeleteFunc(slices.Clone(ms), func(m provider.Member) bool { return !m.Provider.DecidesModel(m.Model) }) + if len(ms) == 0 { + return nil, planned{}, nil + } + cs, pl := s.planGroup(g, ms, provider.Chat) + return cs, pl, ms +} + +// decideFailed rests a candidate whose System One call failed as status, +// header and body say, the way a chat's failed try rests: not when the +// request itself was at fault (its shape, its prompt, its content), which +// would fail the same at any. It returns why it failed, and its rest when +// it rests. +func (s *Server) decideFailed(c candidate, status int, header http.Header, body []byte) (string, *Rest) { + if shapeRefused(status, body) || promptRefused(status, body) || protectionRefused(status, body) || !retryable(status, body) { + return failureOf(c, status, body), nil + } + rest := s.restAfter(c, status, header, body) + return rest.Why, &rest +} + +// serveDecisionGroup answers a System One request to the decision group g +// (decisionGroupOf), its models ms: each of the group's keys and accounts +// in turn until one answers, or the last one's answer passed on. +func (s *Server) serveDecisionGroup(w http.ResponseWriter, r *http.Request, body []byte, asked string, g provider.Group, ms []provider.Member) { + start := time.Now() + g = g.Live() + keyWho, keyHeld := keyHolds(r) + accWho, accHeld := accountHolds(r) + // a gateway key held to some models (#882) names the group, or the + // models of it it may use + if keyHeld && !groupAllowed(keyWho, g, ms) { + writeError(w, provider.Chat, http.StatusForbidden, keyModelError(keyWho, asked)) + return + } + // a model a pause rule holds for now is out, as for a chat + ms, paused := provider.PausedOut(g, ms, agentOf(r), ruleClock()) + if len(ms) == 0 && len(paused) > 0 { + writeError(w, provider.Chat, http.StatusServiceUnavailable, pausedError(asked, paused)) + return + } + cs, pl, ms := s.decideTries(g, ms) + if len(ms) == 0 { + writeError(w, provider.Chat, http.StatusNotFound, fmt.Sprintf("no decision model of the group %s can be asked now: their providers are switched off or gone", g.Name)) + return + } + if keyHeld || accHeld { + who := keyWho + if !keyHeld { + who = accWho + } + var members map[string]bool + if keyHeld { + members = groupKeeps(keyWho, g, ms) + } + var held bool + if cs, pl, held = allowedCandidates(who, cs, pl, members); len(cs) == 0 && held { + writeError(w, provider.Chat, http.StatusForbidden, keyAccountsError(who, asked)) + return + } + } + if len(cs) == 0 { + writeError(w, provider.Chat, http.StatusServiceUnavailable, fmt.Sprintf("no key or account of the group %s's decision models may serve them now", g.Name)) + return + } + who := callerOf(r) + tr := s.trace.begin(Route{Time: start, Agent: who.agent, Session: sessionOf(r.Header), Model: asked, Provider: cs[0].p.ID, + Group: groupRef(g, ms), Order: pl.order, Left: pl.left}) + var skipped []string + for i, c := range cs { + last := i == len(cs)-1 + at := time.Now() + s.trace.update(tr, func(t *Route) { + t.Provider = c.p.ID + t.Tries = append(t.Tries, Try{ID: c.rest, Model: c.model, Start: at}) + }) + // each try ends as it went, and the route with the last + tried := func(status int, msg, fail string, rest *Rest, used Usage) { + ms := time.Since(at).Milliseconds() + s.trace.update(tr, func(t *Route) { + try := &t.Tries[len(t.Tries)-1] + try.Done, try.Status, try.Millis, try.Error, try.Fail, try.Rest = true, status, ms, msg, fail, rest + if status < 400 || last || r.Context().Err() != nil { + t.Done, t.Status, t.Error, t.Millis, t.Tokens = true, status, msg, time.Since(start).Milliseconds(), used.Input+used.Output + t.Usage = routeUsage(c.p.ID, c.model, used) + } + }) + } + status, b, header, err := s.postDecide(r.Context(), c.p, c.model, withModel(body, c.model)) + if err != nil { + fail, rest := failOther, (*Rest)(nil) + var tooMany *errRPM + if r.Context().Err() == nil && !errors.As(err, &tooMany) { + // unreachable: it rests, as a chat's would + fail, rest = s.decideFailed(c, http.StatusBadGateway, nil, []byte(err.Error())) + } + if !last && r.Context().Err() == nil { + tried(http.StatusBadGateway, err.Error(), fail, rest, Usage{}) + skipped = append(skipped, c.label()+": "+err.Error()) + continue + } + last = true + tried(http.StatusBadGateway, err.Error(), fail, rest, Usage{}) + msg := err.Error() + if len(skipped) > 0 { + msg += " (tried first: " + strings.Join(skipped, "; ") + ")" + } + writeError(w, provider.Chat, http.StatusBadGateway, msg) + return + } + var use struct { + Model string `json:"model"` // the one that answered, when the reply says + Usage struct { + Input int `json:"input_tokens"` + Output int `json:"output_tokens"` + } `json:"usage"` + } + _ = json.Unmarshal(b, &use) + used := Usage{Input: use.Usage.Input, Output: use.Usage.Output} + errMsg, fail := "", "" + var rest *Rest + if status >= 300 { + errMsg = provider.APIError(b, fmt.Sprintf("%d %s", status, http.StatusText(status))) + } + if status >= 400 { + fail, rest = s.decideFailed(c, status, header, b) + if !last && retryable(status, b) { + tried(status, errMsg, fail, rest, used) + skipped = append(skipped, fmt.Sprintf("%s: %s", c.label(), errMsg)) + continue + } + } + last = true + tried(status, errMsg, fail, rest, used) + if status < 400 { + servedCandidate(c, used.Input+used.Output) + } + var keyID, keyName string + if c.p.Account == nil && c.p.Key != "" { + keyID, keyName = provider.KeyID(c.p.Key), c.p.KeyName + } + appendUsage(r, usage.Record{RouteID: tr.ID, Time: start, Agent: who.agent, Via: who.via, Provider: c.p.ID, Host: c.p.Where(), Model: c.model, Requested: asked, Served: use.Model, + ProviderKeyID: keyID, ProviderKeyName: keyName, ProviderAccount: accountOf(c.p), + Input: use.Usage.Input, Output: use.Usage.Output, Millis: time.Since(start).Milliseconds(), Status: status}) + ctype := header.Get("Content-Type") + if ctype == "" || status < 300 { + ctype = "application/json" + } + if status >= 400 { + keepRetry(w.Header(), header, b) + } + w.Header().Set("Content-Type", ctype) + w.WriteHeader(status) + w.Write(b) + return + } +} + +// decideRefused is a System One call a decision provider answered with a +// failure: its status, headers and body, for a decision group's classifier +// to rest the one that failed as a chat's try would rest. +type decideRefused struct { + err error + status int + header http.Header + body []byte +} + +func (e decideRefused) Error() string { return e.err.Error() } +func (e decideRefused) Unwrap() error { return e.err } + +// askDecisionGroup is askClassifier for a decision group: its keys and +// 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(model string, intents []string, prev before, effort bool, text string) (v verdict, ok bool, err error) { + if !strings.HasPrefix(model, provider.GroupPrefix) { + return verdict{}, false, nil + } + g, ms, found := provider.FindGroup(model) + if !found || !g.Decides() { + return verdict{}, false, nil + } + g = g.Live() + ms, _ = provider.PausedOut(g, ms, RouterAgent, ruleClock()) + cs, _, _ := s.decideTries(g, ms) + if len(cs) == 0 { + return verdict{}, true, fmt.Errorf("no decision model of the group %s can be asked now", g.Name) + } + for _, c := range cs { + if v, err = s.askJev(c.p, c.model, intents, prev, effort, text); err == nil { + servedCandidate(c, 0) + return v, true, nil + } + var refused decideRefused + var answer answerError + switch { + case errors.As(err, &refused): + s.decideFailed(c, refused.status, refused.header, refused.body) + case errors.As(err, &answer), errors.Is(err, context.Canceled): + // it answered, not in System One's shape: nothing to rest for + default: + s.decideFailed(c, http.StatusBadGateway, nil, []byte(err.Error())) + } + } + return verdict{}, true, err +} diff --git a/internal/gateway/decide_group_test.go b/internal/gateway/decide_group_test.go new file mode 100644 index 000000000..73eff324c --- /dev/null +++ b/internal/gateway/decide_group_test.go @@ -0,0 +1,178 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// decideFleet is System One APIs whose every key answers as status says +// (200 when unset), and the keys asked in turn. +type decideFleet struct { + mu sync.Mutex + status map[string]int + asked []string +} + +func (f *decideFleet) set(key string, code int) { + f.mu.Lock() + defer f.mu.Unlock() + f.status[key] = code +} + +func (f *decideFleet) took() []string { + f.mu.Lock() + defer f.mu.Unlock() + out := f.asked + f.asked = nil + return out +} + +func (f *decideFleet) serve() *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/v1/systemone" { + http.NotFound(w, r) + return + } + key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + var q struct{ Model string } + json.NewDecoder(r.Body).Decode(&q) + f.mu.Lock() + f.asked = append(f.asked, key) + code := f.status[key] + f.mu.Unlock() + w.Header().Set("Content-Type", "application/json") + if code != 0 && code != 200 { + w.WriteHeader(code) + io.WriteString(w, `{"detail":{"message":"no capacity for `+key+`"}}`) + return + } + json.NewEncoder(w).Encode(map[string]any{"model": q.Model, "answers": map[string]any{ + "levels": map[string]any{"type": "noul", "noul": 0}, + "intent": map[string]any{"type": "choice", "choice": "bug", "confidence": 0.9}}, + "usage": map[string]int{"input_tokens": 10, "output_tokens": 2}}) + })) +} + +// A routing group of decision models answers /v1/systemone (ARNO on +// Discord): its keys and accounts asked in the group's order, one that +// fails as a chat's would resting and the next asked, every try in the +// routing log; asked by "group/" or by the group's name. +func TestSystemOneDecisionGroupFailsOver(t *testing.T) { + fresh(t) + f := &decideFleet{status: map[string]int{}} + a, b := f.serve(), f.serve() + defer a.Close() + defer b.Close() + for _, p := range []provider.Provider{ + // a decision provider alone, two keys: each one a try of its own + {ID: "ja", Name: "JA", Key: "ka1", Keys: []provider.KeyAccount{{Key: "ka2"}}, Decide: a.URL + "/v1"}, + {ID: "jb", Name: "JB", Key: "kb", Decide: b.URL + "/v1"}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + if err := provider.SaveGroup(provider.Group{ID: "jevs", Name: "Jevs", Members: []string{"ja/jev-latest", "jb/jev-latest"}}); err != nil { + t.Fatal(err) + } + s := New() + call := func(path, body string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", path, strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer magpie") + s.Handler().ServeHTTP(rec, req) + return rec + } + const ask = `{"model":%q,"state":{"message":"hi"},"questions":{"intent":{"type":"choice"}}}` + f.set("ka1", 429) + f.set("ka2", 503) + rec := call("/v1/systemone", strings.Replace(ask, "%q", `"group/jevs"`, 1)) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"choice":"bug"`) { + t.Fatalf("group: %d %s", rec.Code, rec.Body) + } + if got := strings.Join(f.took(), ","); got != "ka1,ka2,kb" { + t.Fatalf("asked %s, want ka1,ka2,kb", got) + } + if n := len(s.trace.routes); n != 1 { + t.Fatalf("traced %d", n) + } + r := s.trace.routes[0] + if r.Model != "group/jevs" || r.Group == nil || r.Provider != "jb" || !r.Done || r.Status != 200 || len(r.Tries) != 3 { + t.Fatalf("route %+v", r) + } + for i, want := range []int{429, 503, 200} { + try := r.Tries[i] + if try.Status != want || try.Model != "jev-latest" || (want != 200) != (try.Rest != nil) { + t.Errorf("try %d: %+v, want %d, a rest when it failed", i, try, want) + } + } + if len(r.Usage) != 1 || r.Usage[0].Provider != "jb" { + t.Fatalf("usage %+v", r.Usage) + } + // the two that failed rest: by the group's name, the one that answered + // goes first + rec = call("/v1/systemone", strings.Replace(ask, "%q", `"Jevs"`, 1)) + if rec.Code != 200 { + t.Fatalf("by name: %d %s", rec.Code, rec.Body) + } + if got := strings.Join(f.took(), ","); got != "kb" { + t.Fatalf("by name asked %s, want kb", got) + } + // all failing: every one tried, those resting last, and the last + // one's answer passed on + f.set("kb", 429) + rec = call("/v1/systemone", strings.Replace(ask, "%q", `"group/jevs"`, 1)) + if got := strings.Join(f.took(), ","); got != "kb,ka1,ka2" { + t.Fatalf("all failing asked %s, want kb,ka1,ka2", got) + } + if rec.Code != 503 || !strings.Contains(rec.Body.String(), "no capacity for ka2") { + t.Fatalf("all failing: %d %s", rec.Code, rec.Body) + } + // a chat request to it is told where it is asked + rec = call("/v1/chat/completions", `{"model":"group/jevs","messages":[{"role":"user","content":"hi"}]}`) + if rec.Code != 400 || !strings.Contains(rec.Body.String(), "/v1/systemone") { + t.Fatalf("chat to a decision group: %d %s", rec.Code, rec.Body) + } +} + +// A decision group as a chat group's classifier fails over the same way. +func TestDecisionGroupClassifierFailsOver(t *testing.T) { + fresh(t) + f := &decideFleet{status: map[string]int{"kc": 503}} + a, b := f.serve(), f.serve() + defer a.Close() + defer b.Close() + for _, p := range []provider.Provider{ + {ID: "jc", Name: "JC", Key: "kc", Decide: a.URL + "/v1"}, + {ID: "jd", Name: "JD", Key: "kd", Decide: b.URL + "/v1"}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + if err := provider.SaveGroup(provider.Group{ID: "judges", Name: "Judges", Members: []string{"jc/jev-latest", "jd/jev-latest"}}); err != nil { + t.Fatal(err) + } + s := New() + if v, err := s.askClassifier("group/judges", []string{"feature", "bug"}, before{}, false, "fix this"); err != nil || v.Intent != "bug" { + t.Fatalf("classify: %+v %v", v, err) + } + asked := f.took() + if len(asked) < 2 || asked[0] != "kc" || asked[len(asked)-1] != "kd" { + t.Fatalf("asked %v", asked) + } + // jc rests: the next classification asks jd first + if _, err := s.askClassifier("group/judges", []string{"feature", "bug"}, before{}, false, "fix this"); err != nil { + t.Fatal(err) + } + if asked := f.took(); len(asked) == 0 || asked[0] != "kd" { + t.Fatalf("after the rest asked %v", asked) + } +} diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index e1abdac51..4ef427c30 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -219,7 +219,7 @@ func perKeyBarred(p provider.Provider, model string, from provider.Protocol) (ou var unlisted []candidate for i, k := range keys { q := p.WithKey(k) - if len(q.Speaks()) == 0 { + if len(q.Speaks()) == 0 && !q.DecidesModel(model) { continue // made for a protocol this provider has no endpoint for } rest := p.ID diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index b1ee2b2fb..15f29556b 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1386,6 +1386,12 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro if g, ok := provider.DisabledGroup(asked); ok { call.Error = "group switched off" msg = fmt.Sprintf("the routing group %s is switched off in Magpie, so %q is not served; switch it on again on Magpie's Routing page to use it", g.Name, call.Model) + } else if g, _, ok := provider.FindGroup(asked); ok && g.Decides() { + // a group of decision models answers System One, not this + call.Status, call.Error = 400, "a decision group" + writeError(w, from, 400, fmt.Sprintf("the routing group %s holds decision models: it only decides a routing group's model and effort, asked at /v1/systemone; it holds no conversation", g.Name)) + turnedAway() + return } else if g, ok := emptyGroup(asked); ok { // a group of its own with nothing in it now — its patterns // match no model served (#766) — said so, not the whole list diff --git a/internal/gateway/plugin_decide_test.go b/internal/gateway/plugin_decide_test.go index 96f4d6889..2030ee3b4 100644 --- a/internal/gateway/plugin_decide_test.go +++ b/internal/gateway/plugin_decide_test.go @@ -86,14 +86,18 @@ func TestPluginServesSystemOne(t *testing.T) { if code, out := postAs(t, s, "", `{"model":"`+pid+`/fake-clef","messages":[{"role":"user","content":"hi"}]}`); code != 400 || !strings.Contains(out, "only decides") { t.Fatalf("chat to a decision model: %d %s", code, out) } - // a group's classifier, and never a member + // a chat group's classifier, and never one of its models; a group of + // decision models alone is a decision group (decide_group.go) g := provider.Group{ID: "d", Members: []string{pid + "/fake-1"}, Classifier: pid + "/fake-clef", Rules: []provider.Rule{{Use: pid + "/fake-1", Intent: "bug"}}} if err := provider.SaveGroup(g); err != nil { t.Fatal(err) } - if err := provider.SaveGroup(provider.Group{ID: "e", Members: []string{pid + "/fake-judge"}}); err == nil || !strings.Contains(err.Error(), "classifier") { - t.Fatalf("a decision model saved as a member: %v", err) + if err := provider.SaveGroup(provider.Group{ID: "e", Members: []string{pid + "/fake-1", pid + "/fake-judge"}}); err == nil || !strings.Contains(err.Error(), "decision models only") { + t.Fatalf("a decision model saved beside a chat model: %v", err) + } + if err := provider.SaveGroup(provider.Group{ID: "e", Members: []string{pid + "/fake-judge", pid + "/jev-9"}}); err != nil { + t.Fatalf("a group of decision models: %v", err) } for _, m := range []string{"fake-clef", "fake-judge", "jev-9"} { if v, err := s.askClassifier(pid+"/"+m, []string{"feature", "bug"}, before{}, false, "fix this"); err != nil || v.Intent != "bug" { diff --git a/internal/gui/assets/routing.js b/internal/gui/assets/routing.js index 3544f7b0c..24bf8e0db 100644 --- a/internal/gui/assets/routing.js +++ b/internal/gui/assets/routing.js @@ -3088,7 +3088,11 @@ const m = /^(.+):(none|minimal|low|medium|high|xhigh|max)$/i.exec(id); return m ? [m[1], m[2].toLowerCase()] : [id, ""]; } - const modelOf = (id) => groups?.models.find((m) => m.id === id) || groups?.models.find((m) => m.id === splitMember(id)[0]); + // a decision model (Jev) is a member of a group of decision models only, + // asked at /v1/systemone (provider/decide_group.go): it is in + // groups.deciders, not groups.models + const deciderOf = (id) => groups?.deciders?.find((m) => m.id === splitMember(id)[0]); + const modelOf = (id) => groups?.models.find((m) => m.id === id) || groups?.models.find((m) => m.id === splitMember(id)[0]) || deciderOf(id); // a group's patterns (#766, provider.IsPattern): a glob, * any run of // characters over the provider/model id in any case, or re: over // the whole id. The group keeps them, and the models they match now @@ -3779,7 +3783,8 @@ // the reasoning the model is sent at in this group: the group's // (blank), or one of its own whatever the agent asks. A group in // it reasons as it says. - if (!s) { + // a decision model reasons at no level of the group's or its own + if (!s && !deciderOf(id)) { const [base, fixed] = splitMember(id); const fx = el("button", "rt-cond rt-fixed" + (fixed ? " on" : ""), fixed ? fixedWords(fixed) : t("Group's reasoning")); fx.title = fixed ? t("Sent at {level} reasoning whatever the agent asks, at the model's nearest level", { level: fixed }) : t("Reasons as the group's effort says"); @@ -3811,7 +3816,7 @@ fb.onclick = () => { d.fast = on ? d.fast.filter((x) => x !== id) : [...d.fast, id]; draw(); }; row.append(fb); } - } else { + } else if (s) { // a group in the group takes no reasoning of its own: its models // reason as it says (provider.SaveGroup refuses "group/x:high", and // the gateway has nowhere to put one). So the slot a model's own @@ -3858,10 +3863,15 @@ addBtn.onclick = (ev) => { // a group in it may be any other, but never one it is in already: // that would put it in itself - const subs = groups.groups.filter((x) => !x.hidden && x.id !== g?.id && !(g && x.holds?.includes(g.id))) + // a group is of decision models only, or of models that hold + // conversations (provider.cleanDecisionGroup): one holding either + // is offered more of the same, an empty one both. A group of + // decision models is never in another: it holds no conversation + const decides = d.members.some((m) => !subOf(m) && deciderOf(m)), chats = d.members.some((m) => subOf(m) || !deciderOf(m)); + const subs = decides ? [] : groups.groups.filter((x) => !x.hidden && !x.decides && x.id !== g?.id && !(g && x.holds?.includes(g.id))) .map((x) => ({ value: "group/" + x.id, label: x.name, note: noted("group/" + x.id, "group/" + x.id), icons: groupIcons(x), group: ROUTING_GROUPS, ref: "group/" + x.id })); - const options = [...subs, ...groups.models - .map((x) => ({ value: x.id, label: x.name || x.id, note: noted(x.providerName, x.id), icon: x.icon, group: x.providerName, ref: x.id, context: x.context }))]; + const ref = (x) => ({ value: x.id, label: x.name || x.id, note: noted(x.providerName, x.id), icon: x.icon, group: x.providerName, ref: x.id, context: x.context }); + const options = [...subs, ...(decides ? [] : groups.models.map(ref)), ...(chats ? [] : (groups.deciders || []).map(ref))]; // the member a model is in the group as: itself, or with its // reasoning fixed (deepseek/x:max), which is ticked as it and taken // out by it rather than added twice (#907) diff --git a/internal/gui/groups.go b/internal/gui/groups.go index 176090d85..bec253fa3 100644 --- a/internal/gui/groups.go +++ b/internal/gui/groups.go @@ -47,6 +47,9 @@ type groupJSON struct { // Patterns: its patterns, each with how many models it matches now // (#766), so one that matches nothing is said on its card Patterns []provider.PatternHit `json:"patterns"` + // Decides: it is a group of decision models, asked at /v1/systemone + // and by a group's classifier, never by an agent + Decides bool `json:"decides,omitempty"` } type memberJSON struct { @@ -189,6 +192,7 @@ func groupsState() groupsJSON { for _, g := range provider.Groups() { gj := groupJSON{Group: g, Info: []memberJSON{}, Holds: []string{}, Offers: []string{}, Shared: []string{}, Patterns: []provider.PatternHit{}} gj.Patterns = append(gj.Patterns, provider.PatternHits(g)...) + gj.Decides = g.Decides() for _, e := range served { if e.ID == provider.GroupPrefix+g.ID { gj.Offers, gj.Shared = append(gj.Offers, e.Efforts...), append(gj.Shared, e.Shared...) diff --git a/internal/gui/tests/group-decide-members.test.cjs b/internal/gui/tests/group-decide-members.test.cjs new file mode 100644 index 000000000..0c9e54ba5 --- /dev/null +++ b/internal/gui/tests/group-decide-members.test.cjs @@ -0,0 +1,104 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// ARNO on Discord: decision models (Jev) make a routing group of their own, +// asked at /v1/systemone (provider/decide_group.go). The group editor's +// Add a model picker offers a group of decision models only decision +// models, and a group of models that hold conversations only those and +// the groups it may hold, never a group of decision models; a decision +// model's row has no reasoning picker. In English and Chinese, Chromium +// and WebKit; no new strings. +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 models = [ + { id: "a/one", name: "one", providerName: "A", icon: "generic" }, + { id: "a/two", name: "two", providerName: "A", icon: "generic" }, +]; +const deciders = [ + { id: "ja/jev-latest", name: "jev-a", providerName: "JA", icon: "generic" }, + { id: "jb/jev-latest", name: "jev-b", providerName: "JB", icon: "generic" }, +]; +const words = { + en: { edit: "Edit", add: "Add another model", own: "Group's reasoning" }, + zh: { edit: "编辑", add: "再添加一个模型" }, +}; + +function serve(lang) { + const groups = () => ({ + models, deciders, pools: [], + groups: [ + { id: "g", name: "G", members: ["a/one"], off: [], routing: "order", ready: true, memberInfo: [{ id: "a/one", ready: true }] }, + { id: "other", name: "Other", members: ["a/two"], off: [], routing: "order", ready: true, memberInfo: [{ id: "a/two", ready: true }] }, + { id: "jevs", name: "Jevs", decides: true, members: ["ja/jev-latest"], off: [], routing: "order", ready: true, memberInfo: [{ id: "ja/jev-latest", ready: true }] }, + ], + }); + const state = { agents: [{ id: "codex", name: "Codex", path: "/test/codex", fields: [] }], profiles: [], settings: { lang, theme: "light" } }; + 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/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) return new Promise(() => {}); + return json({ mine: true, now: new Date().toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/groups") return json(groups()); + if (url.pathname.startsWith("/api/groups/")) return json(groups()); + 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)]; + await r.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + const w = words[lang]; + test(`${engine} ${lang}: a group of decision models is offered decision models, a chat group none`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await (await browser.newContext({ viewport: { width: 1100, height: 1400 }, reducedMotion: "reduce" })).newPage(); + t.after(() => browser.close()); + 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"); + const card = (id) => page.locator(`.rt-group[data-id="${id}"]`); + await card("g").waitFor(); + const pop = page.locator("#pop"); + const offered = async (id) => { + await card(id).locator("button", { hasText: w.edit }).click(); + const ed = page.locator(".rt-gedit"); + await ed.locator("button.rt-gadd", { hasText: w.add }).click(); + await pop.locator("li .v").first().waitFor(); + const names = await pop.locator("li .v").evaluateAll((vs) => vs.map((v) => v.textContent.trim())); + await page.keyboard.press("Escape"); + await pop.waitFor({ state: "hidden" }); + return { ed, names }; + }; + + const jevs = await offered("jevs"); + assert.deepEqual(jevs.names.sort(), ["jev-a", "jev-b"], "a group of decision models offered more than decision models"); + const row = jevs.ed.locator(".fbl").first().locator(".fbrow").first(); + assert.equal(await row.locator(".rt-fixed").count(), 0, "a decision model has a reasoning picker"); + assert.equal(await row.evaluate((r) => r.classList.contains("off")), false, "a decision model's row says no provider serves it"); + await page.reload(); + await card("g").waitFor(); + + const chat = await offered("g"); + assert.ok(chat.names.includes("one") && chat.names.includes("two") && chat.names.includes("Other"), `chat group offered ${chat.names}`); + assert.ok(!chat.names.some((n) => n.startsWith("jev") || n === "Jevs"), `a chat group offered a decision model or group: ${chat.names}`); + if (w.own) assert.equal(await chat.ed.locator(".fbl").first().locator(".fbrow .rt-fixed", { hasText: w.own }).count(), 1); + + assert.equal(await page.locator("select").count(), 0, "a native select"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/provider/decide_group.go b/internal/provider/decide_group.go new file mode 100644 index 000000000..5b2acabbb --- /dev/null +++ b/internal/provider/decide_group.go @@ -0,0 +1,89 @@ +package provider + +import ( + "fmt" + "slices" + "strings" +) + +// A decision group is a routing group of decision models (Jev and the +// like) and nothing else (ARNO on Discord: 给decision模型也加上group功能): +// a System One request naming it (/v1/systemone, "group/" or the +// group's id or name) goes to its models as a conversation goes to a +// chat group's, the next asked when one fails. It holds no conversation, +// so it is kept out of the agents' catalog, a chat group can't hold it, +// and it takes nothing that shapes a conversation: no patterns, rules, +// classifier, effort, levels or fast mode. + +// decidingMember reports whether a group's member names a decision model: +// "provider/model" whose provider answers model at its decision API, on +// or not. A group, or a member with an effort of its own, is not one. +func decidingMember(id string) bool { + if strings.HasPrefix(id, GroupPrefix) { + return false + } + if IsDecider(id) { + return true + } + pid, model, ok := strings.Cut(id, "/") + if !ok || model == "" { + return false + } + p, err := Find(pid) + return err == nil && p.DecidesModel(model) +} + +// Decides reports whether g is a decision group: every model it names is +// a decision model. +func (g Group) Decides() bool { + return len(g.Members) > 0 && !slices.ContainsFunc(g.Members, func(m string) bool { return !decidingMember(m) }) +} + +// DecisionGroup reports whether ms, a group's models as they resolve now, +// are decision models, every one: the group answers System One, not a +// conversation. +func DecisionGroup(ms []Member) bool { + return len(ms) > 0 && !slices.ContainsFunc(ms, func(m Member) bool { return !m.Provider.DecidesModel(m.Model) }) +} + +// cleanDecisionGroup checks a decision group as SaveGroup is to keep it, +// and a chat group for decision models or decision groups in it; all is +// every group magpie has. +func cleanDecisionGroup(g *Group, all []Group) error { + var deciders, others []string + for _, m := range g.Members { + if model, _ := memberEffortIn(nil, m); decidingMember(model) { + deciders = append(deciders, m) + } else { + others = append(others, m) + } + } + if len(deciders) == 0 { + // a chat group: none of its groups may be a decision group + for _, m := range g.Members { + if gid, ok := strings.CutPrefix(m, GroupPrefix); ok { + if sub, ok := groupOf(all, gid); ok && sub.Decides() { + return fmt.Errorf("%s holds decision models, which answer System One, not a conversation: it can be %s's classifier, not one of its models", sub.Name, g.Name) + } + } + } + return nil + } + if len(others) > 0 { + return fmt.Errorf("%s is a decision model and %s holds conversations: a group is of decision models only, asked at /v1/systemone, or of models that hold conversations", deciders[0], others[0]) + } + switch { + case len(g.Match) > 0: + return fmt.Errorf("%s is of decision models: it takes them by name, not by a pattern", g.Name) + case len(g.Rules) > 0, g.Classifier != "", g.Effort != "": + return fmt.Errorf("%s is of decision models, asked at /v1/systemone: it has no conversation for rules, a classifier or an effort to pick for", g.Name) + case len(g.Levels) > 0, len(g.Fast) > 0: + return fmt.Errorf("%s is of decision models: they take no reasoning level or fast mode", g.Name) + } + for _, m := range g.Members { + if model, effort := memberEffortIn(nil, m); effort != "" { + return fmt.Errorf("%s is a decision model: it takes no effort of its own (:%s)", model, effort) + } + } + return nil +} diff --git a/internal/provider/decide_group_test.go b/internal/provider/decide_group_test.go new file mode 100644 index 000000000..2cdebca08 --- /dev/null +++ b/internal/provider/decide_group_test.go @@ -0,0 +1,60 @@ +package provider + +import ( + "strings" + "testing" +) + +// A group of decision models alone saves, answers System One and stays out +// of the agents' catalog; one beside chat models, or inside a chat group, +// or with what shapes a conversation, is refused (ARNO on Discord). +func TestDecisionGroup(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", t.TempDir()) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + for _, p := range []Provider{ + {ID: "a", Name: "a", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m"}}, + {ID: "ja", Name: "JA", Key: "k1", Decide: "http://127.0.0.1:1/v1"}, + {ID: "jb", Name: "JB", Key: "k2", Decide: "http://127.0.0.1:1/v1"}, + } { + if err := Save(p); err != nil { + t.Fatal(err) + } + } + if err := SaveGroup(Group{ID: "jevs", Name: "Jevs", Members: []string{"ja/jev-latest", "jb/jev-latest"}}); err != nil { + t.Fatal(err) + } + g, ms, ok := FindGroup("group/jevs") + if !ok || !g.Decides() || !DecisionGroup(ms) || len(ms) != 2 { + t.Fatalf("decision group %+v %+v %v", g, ms, ok) + } + if id, ok := GroupFor("Jevs"); !ok || id != "group/jevs" { + t.Fatalf("by name: %q %v", id, ok) + } + for _, e := range Catalog() { + if e.ID == "group/jevs" || strings.HasPrefix(e.ID, "group/jevs") { + t.Fatalf("a decision group in the agents' catalog: %+v", e) + } + } + if _, _, ok := Resolve("group/jevs"); ok { + t.Fatal("a decision group resolves as a chat model") + } + for _, tc := range []struct { + g Group + err string + }{ + {Group{Name: "Mixed", Members: []string{"ja/jev-latest", "a/m"}}, "decision models only"}, + {Group{Name: "Chat", Members: []string{"a/m", "group/jevs"}}, "classifier, not one of its models"}, + {Group{Name: "P", Members: []string{"ja/jev-latest"}, Match: []string{"jev*"}}, "not by a pattern"}, + {Group{Name: "R", Members: []string{"ja/jev-latest"}, Effort: EffortAuto, Classifier: "jb/jev-latest"}, "no conversation"}, + {Group{Name: "E", Members: []string{"ja/jev-latest:high"}}, "no effort of its own"}, + } { + if err := SaveGroup(tc.g); err == nil || !strings.Contains(err.Error(), tc.err) { + t.Errorf("%s: %v, want %q", tc.g.Name, err, tc.err) + } + } + // a chat group still takes the decision group as its classifier + if err := SaveGroup(Group{Name: "C", Members: []string{"a/m"}, Effort: EffortAuto, Classifier: "group/jevs"}); err != nil { + t.Errorf("decision group as a classifier: %v", err) + } +} diff --git a/internal/provider/decide_test.go b/internal/provider/decide_test.go index d3a22902c..d888a998b 100644 --- a/internal/provider/decide_test.go +++ b/internal/provider/decide_test.go @@ -61,9 +61,14 @@ func TestMixedDecisionProvider(t *testing.T) { if _, ms, ok := FindGroup("group/auto-deepseek-v4-1-flash"); !ok || len(ms) != 2 || ms[0].Provider.ID != p.ID { t.Fatalf("automatic group: %+v %v", ms, ok) } - if err := SaveGroup(Group{Name: "Bad", Members: []string{"mixed/typesafe/jev"}}); err == nil { + // alone it is a group of decision models (decide_group.go); beside a + // model that holds conversations it is refused + if err := SaveGroup(Group{Name: "Bad", Members: []string{"mixed/deepseek-v4.1-flash", "mixed/typesafe/jev"}}); err == nil { t.Fatal("Jev accepted as a conversation member") } + if err := SaveGroup(Group{Name: "Judges", Members: []string{"mixed/typesafe/jev"}}); err != nil { + t.Fatalf("a group of decision models: %v", err) + } if got, m, err := RouteDecider("mixed/typesafe/jev"); err != nil || got.ID != p.ID || m != "typesafe/jev" { t.Fatalf("Jev route: %+v %s %v", got, m, err) } @@ -107,8 +112,8 @@ func TestMixedDecisionProvider(t *testing.T) { } } -// A decision provider (TypeSafe's Jev) is only ever a group's classifier: -// its models aren't in the catalog nor a group's members, and a group's +// A decision provider (TypeSafe's Jev) is a chat group's classifier, never +// one of its models: its models aren't in the catalog, and a group's // effort is picked only by it. func TestDecider(t *testing.T) { t.Setenv("HOME", t.TempDir()) @@ -158,8 +163,10 @@ func TestDecider(t *testing.T) { if g, _, _ := FindGroup("group/g"); g.Effort != EffortAuto || g.Classifier != "typesafe/jev-latest" || !g.Ruled() { t.Fatalf("saved %+v", g) } - if err := SaveGroup(Group{Name: "H", Members: []string{"typesafe/jev-latest"}}); err == nil { - t.Error("Jev saved as a group's member") + // beside a model that holds conversations it is refused; a group of + // decision models alone is a decision group (decide_group_test.go) + if err := SaveGroup(Group{Name: "H", Members: []string{"a/m", "typesafe/jev-latest"}}); err == nil { + t.Error("Jev saved in a group beside a chat model") } } diff --git a/internal/provider/group.go b/internal/provider/group.go index 4202aba76..28a87f34d 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -694,8 +694,8 @@ func groupEntries(entries []Entry) []Entry { continue } ms := membersIn(entries, all, g) - if len(ms) == 0 { - continue + if len(ms) == 0 || DecisionGroup(ms) { + continue // a decision group answers System One, no agent's conversation } e := Entry{ID: GroupPrefix + g.ID, Model: ms[0].Model, Name: g.Name, Provider: ms[0].Provider, Group: g.ID, Named: !g.Auto} var fixed []string // the efforts members are fixed at @@ -930,10 +930,10 @@ func SaveGroup(g Group) error { if err := groupsInGroup(g, groupsIn(entries)); err != nil { return err } - for _, m := range g.Members { - if IsDecider(m) { - return fmt.Errorf("%s decides a group's model and effort; it holds no conversation, so it can only be the group's classifier", m) - } + // decision models make a group of their own, asked at /v1/systemone, + // never one with models that hold conversations (decide_group.go) + if err := cleanDecisionGroup(&g, groupsIn(entries)); err != nil { + return err } if g.Routing != Ordered && g.Routing != Rotate && g.Routing != LeastUsed && g.Routing != Pace && g.Routing != Manual { g.Routing = "" diff --git a/internal/tui/decide_group_test.go b/internal/tui/decide_group_test.go new file mode 100644 index 000000000..becffc36f --- /dev/null +++ b/internal/tui/decide_group_test.go @@ -0,0 +1,43 @@ +package tui + +import ( + "slices" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// The member picker offers a group of decision models only decision +// models, a chat group none, and a new group both (ARNO on Discord). +func TestMemberOptionsDecisionGroup(t *testing.T) { + home(t) + if err := provider.Save(provider.Provider{ID: "ja", Name: "JA", Key: "k1", Decide: "http://127.0.0.1:1/v1"}); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "jb", Name: "JB", Key: "k2", Decide: "http://127.0.0.1:1/v1"}); err != nil { + t.Fatal(err) + } + if err := provider.SaveGroup(provider.Group{ID: "jevs", Name: "Jevs", Members: []string{"ja/jev-latest"}}); err != nil { + t.Fatal(err) + } + if err := provider.SaveGroup(provider.Group{ID: "chat", Name: "Chat", Members: []string{"a/m"}}); err != nil { + t.Fatal(err) + } + ids := func(skip []string, self string) []string { + var out []string + for _, o := range memberOptions(skip, self) { + out = append(out, o.Value) + } + return out + } + got := ids([]string{"ja/jev-latest"}, "jevs") + if !slices.Contains(got, "jb/jev-latest") || slices.Contains(got, "ja/jev-latest") || slices.ContainsFunc(got, func(id string) bool { return !provider.IsDecider(id) }) { + t.Fatalf("decision group offered %v", got) + } + if got := ids([]string{"a/m"}, "chat"); slices.Contains(got, "jb/jev-latest") || slices.Contains(got, "group/jevs") || len(got) == 0 { + t.Fatalf("chat group offered %v", got) + } + if got := ids(nil, ""); !slices.Contains(got, "jb/jev-latest") || !slices.Contains(got, "a/m") { + t.Fatalf("a new group offered %v", got) + } +} diff --git a/internal/tui/routing.go b/internal/tui/routing.go index 213f4c86d..d8a2deb89 100644 --- a/internal/tui/routing.go +++ b/internal/tui/routing.go @@ -187,15 +187,29 @@ type pickMsg struct{ group, newGroup string } // memberOptions is every model and group magpie has, but those in skip. func memberOptions(skip []string, self string) []agent.Option { var out []agent.Option - for _, e := range provider.Catalog() { - if slices.Contains(skip, e.ID) || e.ID == provider.GroupPrefix+self { - continue + // a group is of decision models alone, asked at /v1/systemone, or of + // models that hold conversations (provider.cleanDecisionGroup): one + // holding either is offered more of the same, a new one both + g, _ := findGroup(self) + decides := self != "" && g.Decides() + if !decides { + for _, e := range provider.Catalog() { + if slices.Contains(skip, e.ID) || e.ID == provider.GroupPrefix+self { + continue + } + note := e.Name + if e.Group != "" { + note = "group · " + e.Name + } + out = append(out, agent.Option{Value: e.ID, Note: note}) } - note := e.Name - if e.Group != "" { - note = "group · " + e.Name + } + if self == "" || decides { + for _, e := range provider.Deciders() { + if !slices.Contains(skip, e.ID) { + out = append(out, agent.Option{Value: e.ID, Note: e.Name + " · decision model"}) + } } - out = append(out, agent.Option{Value: e.ID, Note: note}) } return out }