gateway, provider, cli, gui: a group can route By weight, each member's share set beside it (#1910, DD on Discord)
DD asked for weighted round robin as a group routing, next to In turn.
A provider's keys could already route by weight (#841). Groups could not.
What changes:
- provider: Group.Weights maps a member's spelling to its weight, 1 to
1000. A member left out, or set to 0, weighs 1. SaveGroup accepts
routing "weight". It also cleans weights the way it cleans fast and
off: it strips :fast, drops weights of members that are gone and of
members weighing 1, and refuses a weight below 0 or above 1000.
Weights follow a member when it is renamed (RenameMember, Rename,
RenameGroup) and survive Share/Import.
- gateway: planLevel treats each member of a weight-routed group as one
unit: a model with its keys in its provider's order, or a nested group
routed its own way. weightedUnits orders the units by smooth WRR on a
round per group ("group/<id>"), sharing wrrPick with the keys. The
round's pick goes first and the rest stay in member order for
failover. A unit whose head is resting leaves the round. When a
conversation is kept on another member (session/turn/cache/strict),
the charge moves to that member (wrrSeat, wrrMove).
- cli: routing=weight (also weighted, wrr). weight=<model>=<n>[,...]
sets weights and keeps the rest; weight= on its own clears them. The
group view shows "· weight N" for each member.
- tui: By weight is in the group routing list.
- gui: the group editor offers By weight. Each member then shows
"Weight N · S%", its share among the members that are on. Clicking it
edits the number in place: Enter or blur keeps it, Escape cancels,
and a value outside 1 to 1000 shows a warning. The trace header uses
group wording for a weight-routed group. Strings are added in zh,
zh-TW, ja and de.
- docs: reference.md, gateway-routing.md, and site start pages in en,
zh and ja.
Run:
- go test -tags nogui ./internal/provider ./internal/cli ./internal/tui:
ok.
- ./internal/gateway: ok in 988s with -timeout 45m. The first run hit
the default 10m timeout at load average ~170. The test running at
that moment had been running for 2s; it was not a hang.
- go vet -tags nogui on those packages, for darwin, GOOS=linux and
GOOS=windows: clean. gofmt -l: clean.
- New group-member-weight.test.cjs: 8/8 in Chromium and WebKit, en and
zh at 1100, en and de at 420. The WebKit de 420 case also passed six
runs at once.
- gui-zh-tw, gui-ja, gui-de, i18n-keys, routing-*, group-*,
panel-routing*, settings-groups and agent-model-groups: all green
except two.
- routing-steady (WebKit) is #1804. It is red 2/3 alone on origin/main
e1b70c13d too.
- routing-save-blank (chromium en) was red under load only, and 3/3
green alone. The overshoot in its wheel loop is filed as #1924.
Broken by hand, each red, then restored:
- byWeight forced false:
--- FAIL: TestWeightedGroup (weighted_group_test.go:69 its turn ...)
- cleanWeights call skipped:
--- FAIL: TestSaveGroupWeights (groupweight_test.go:39 weights map[...
an/claude-opus-5-5:0 ... oa/gpt-6.1-sol:high:fast:3 ...])
- CLI weight case renamed:
--- FAIL: TestGroupWeightCLI (unknown field "weight")
- GUI chip not appended: group-member-weight chromium en 1100 timed out
on the weight button.
- Not red: the test's "moved nothing" check. A scroll forced on click,
or padding added above, did not turn it red, because the view's own
scroll guard and scroll anchoring hold the clicked row in place. It
only shows that the row stays under the pointer.
Not tried: real accounts through a running gateway. The routing is
proven by the plan-level test with synthetic providers only.
This commit is contained in:
+6
-1
@@ -1144,6 +1144,7 @@ magpie group add "Opus anywhere" models=claude/claude-opus-5-5,copilot/claude-op
|
||||
magpie group opus-anywhere # one group, its models in order
|
||||
magpie group set opus-anywhere models+=openrouter/anthropic/claude-opus-5.5 routing=usage
|
||||
magpie group set opus-anywhere models-=copilot/claude-opus-5.5
|
||||
magpie group set opus-anywhere routing=weight weight=claude/claude-opus-5-5=3,copilot/claude-opus-5.5=1
|
||||
magpie group copy opus-anywhere "Opus test" # the same models, routing and rules, to change on its own
|
||||
magpie group rm opus-anywhere # one magpie found is hidden; magpie group restore <id> brings it back
|
||||
magpie claude group/opus-anywhere # use it
|
||||
@@ -1154,7 +1155,11 @@ spare, the one whose allowance renews soonest first), `order` (the first
|
||||
model until it can't answer, then the next), `rotate` (each turn to the next
|
||||
member), `usage` (least used first) or `pace` (weekly pace: the account with
|
||||
the most of its week left per hour until it renews first, so less of a week
|
||||
is lost at its reset). A key has no allowance to weigh, so it goes by its
|
||||
is lost at its reset) or `weight` (each model takes its share of the
|
||||
requests by its weight, smoothly interleaved: `weight=claude/claude-opus-5-5=3`
|
||||
gives it three requests for every one a model left at weight 1 takes; a
|
||||
weight is 1 to 1000, `weight=` alone clears them all, and a group in the
|
||||
group counts as one member, `weight=group/fast=2`). A key has no allowance to weigh, so it goes by its
|
||||
order or by what magpie sent it lately — except a sub2api key its owner gave
|
||||
a 5-hour, day or 7-day limit: with the provider's Balance URL set to the
|
||||
relay's `/v1/usage`, its card shows those windows and routing weighs it by
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -3,6 +3,7 @@ package cli
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
@@ -34,6 +35,8 @@ const groupUsage = `usage:
|
||||
effort=agent (the agent's again), classifier=<provider/model>|group/<id>,
|
||||
pick=<model> (routing=manual, every request to that one of its models),
|
||||
fast=<m1>[,m2…] (the models sent in their vendor's fast mode; empty for none),
|
||||
weight=<m1>=<n>[,m2=<n>…] (each model's share under routing=weight,
|
||||
1 to 1000; a model not named keeps its own, 1 by default; empty for all 1),
|
||||
listed=no (its models leave the lists agents see, offered through the
|
||||
group alone; listed=yes lists them too again)
|
||||
magpie group pick <id> <model> route the group manually, every request to that one of its models
|
||||
@@ -85,6 +88,9 @@ const groupUsage = `usage:
|
||||
usage the account or key with the most of its allowance left first
|
||||
pace the account with the most of its week left per hour until it renews first, so less
|
||||
of a week is lost at its reset
|
||||
weight each model takes its share by its weight (weight=): one weighing 3 three requests for
|
||||
every one a model weighing 1 takes, spread out; one resting leaves the round, the next
|
||||
model is the fallback, a group in it is one model, a model's keys go as its provider routes
|
||||
manual only the model you pick (pick=, or click it on the group's card): the others and
|
||||
the rules wait until you pick another or route it otherwise; no failover to them
|
||||
stays auto (default) with the account or key that answered, while its cache is worth keeping
|
||||
@@ -107,6 +113,7 @@ const groupUsage = `usage:
|
||||
magpie group add Fast models=codex/gpt-5.6-luna:low,deepseek/deepseek-v4-flash,glm/glm-5.3-flash:high
|
||||
magpie group set fast models+=gcloud/gemini-3.8-flash:medium
|
||||
magpie group add my-free-pool models='openrouter/*:free,opencode-zen/*-free' routing=order
|
||||
magpie group set opus-anywhere routing=weight weight=claude/claude-opus-5-5=3
|
||||
magpie group pick opus-anywhere copilot/claude-opus-5.5
|
||||
magpie claude group/opus-anywhere`
|
||||
|
||||
@@ -121,6 +128,7 @@ var routingNames = []struct {
|
||||
{provider.Rotate, "rotate", []string{"in-turn", "round-robin"}},
|
||||
{provider.LeastUsed, "usage", []string{"least-used"}},
|
||||
{provider.Pace, "pace", []string{"weekly-pace"}},
|
||||
{provider.Weighted, "weight", []string{"weighted", "by-weight", "weighted-round-robin", "wrr"}},
|
||||
{provider.Manual, "manual", []string{"pick", "picked", "pinned"}},
|
||||
}
|
||||
|
||||
@@ -472,13 +480,35 @@ func applyGroupPairs(g *provider.Group, pairs []string, resolve func(string) (st
|
||||
}
|
||||
g.Fast = append(g.Fast, id)
|
||||
}
|
||||
case "weight", "weights":
|
||||
// each member's share when the group routes by weight (#1910):
|
||||
// those named, the rest kept; empty for every one 1 again
|
||||
if strings.TrimSpace(v) == "" {
|
||||
g.Weights = nil
|
||||
}
|
||||
for _, mw := range splitList(v) {
|
||||
at := strings.LastIndex(mw, "=")
|
||||
if at < 0 {
|
||||
return fmt.Errorf("weight=<model>=<n>, as weight=%s=3, not %q", mw, mw)
|
||||
}
|
||||
n, aerr := strconv.Atoi(strings.TrimSpace(mw[at+1:]))
|
||||
if aerr != nil || n < 1 || n > provider.MaxKeyWeight {
|
||||
return fmt.Errorf("%s: a model's weight is 1 to %d", mw, provider.MaxKeyWeight)
|
||||
}
|
||||
m, _ := provider.MemberFast(mw[:at])
|
||||
id, perr := pickMember(g.Members, m)
|
||||
if perr != nil {
|
||||
return perr
|
||||
}
|
||||
g.SetMemberWeight(id, n)
|
||||
}
|
||||
case "pick", "use":
|
||||
// the one member a manual group sends to (#317): routing is
|
||||
// manual then
|
||||
g.Pick, err = pickMember(g.Members, v)
|
||||
g.Routing = provider.Manual
|
||||
default:
|
||||
return fmt.Errorf("unknown field %q (fields: name, models, models+, models-, routing, pick, stays, context, levels, family, effort, classifier, fast, listed; magpie group help)", k)
|
||||
return fmt.Errorf("unknown field %q (fields: name, models, models+, models-, routing, pick, stays, context, levels, family, effort, classifier, fast, weight, listed; magpie group help)", k)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -1037,6 +1067,9 @@ func showGroup(g provider.Group) error {
|
||||
if g.IsFast(id) {
|
||||
l += " · fast"
|
||||
}
|
||||
if g.Routing == provider.Weighted {
|
||||
l += fmt.Sprintf(" · weight %d", g.MemberWeight(id))
|
||||
}
|
||||
if slices.Contains(g.Matched, id) {
|
||||
l += " · by pattern"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// routing=weight routes a group by its members' weights (#1910, DD on
|
||||
// Discord), weight= sets those it names and keeps the rest, the group
|
||||
// shows each member's, and a weight outside 1 to 1000 is refused.
|
||||
func TestGroupWeightCLI(t *testing.T) {
|
||||
groupsHome(t)
|
||||
g, err := addGroup("Spread", []string{"models=a/m:high,b/vendor/m", "routing=weighted-round-robin", "weight=a/m:high=3"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if g.Routing != provider.Weighted || g.MemberWeight("a/m:high") != 3 || g.MemberWeight("b/vendor/m") != 1 {
|
||||
t.Fatalf("routing %q weights %v", g.Routing, g.Weights)
|
||||
}
|
||||
out, err := said(t, func() error { return showGroup(g) })
|
||||
if err != nil || !strings.Contains(out, "weight") || !strings.Contains(out, "· weight 3") || !strings.Contains(out, "· weight 1") {
|
||||
t.Fatalf("shown %v:\n%s", err, out)
|
||||
}
|
||||
if g, err = setGroup("spread", []string{"weight=b/vendor/m=5"}); err != nil || g.MemberWeight("a/m:high") != 3 || g.MemberWeight("b/vendor/m") != 5 {
|
||||
t.Fatalf("weight=b/vendor/m=5: %v %v", g.Weights, err)
|
||||
}
|
||||
for _, bad := range []string{"weight=b/vendor/m=0", "weight=b/vendor/m=1001", "weight=b/vendor/m", "weight=c/m=2"} {
|
||||
if _, err := setGroup("spread", []string{bad}); err == nil {
|
||||
t.Fatalf("%s taken", bad)
|
||||
}
|
||||
}
|
||||
if g, err = setGroup("spread", []string{"weight="}); err != nil || len(g.Weights) != 0 {
|
||||
t.Fatalf("weight= %v %v", g.Weights, err)
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,10 @@ type candidate struct {
|
||||
// provider has no URL for (#1702): the provider is tried whole, on the
|
||||
// URLs it has, and the routing trace says why
|
||||
noURL provider.Protocol
|
||||
// seats are its places in the rounds of the groups routed by weight
|
||||
// it is in (weightedUnits), for affinity to charge the member that
|
||||
// keeps a conversation (weightedKept)
|
||||
seats []wrrSeat
|
||||
}
|
||||
|
||||
// capHold is how an account is held at its usage cap: the cap of the
|
||||
@@ -415,10 +419,14 @@ func planLevel(g provider.Group, ms []provider.Member, depth int, from provider.
|
||||
// and each group in it as one — planned by its own routing, put
|
||||
// where the one it would try first is, the rest of it after
|
||||
type unit struct {
|
||||
m provider.Member // the model, for one of its keys
|
||||
cs []candidate // a group in g, or a provider routed its own way: its own order
|
||||
order []Weighed
|
||||
m provider.Member // the model, for one of its keys
|
||||
cs []candidate // a group in g, or a provider routed its own way: its own order
|
||||
order []Weighed
|
||||
member string // as g spells it, for a unit of a group routed by weight
|
||||
}
|
||||
// a group routed by weight weighs its members, each whole: a
|
||||
// model's keys in its provider's order, a group in it in its own
|
||||
byWeight := g.Routing == provider.Weighted
|
||||
var units []unit
|
||||
var heads []candidate
|
||||
at := map[string][]int{} // a head's seat → its units, in turn
|
||||
@@ -438,12 +446,12 @@ func planLevel(g provider.Group, ms []provider.Member, depth int, from provider.
|
||||
pl.left = append(pl.left, sub.left...)
|
||||
pl.capped = append(pl.capped, sub.capped...)
|
||||
if len(cs) > 0 {
|
||||
add(unit{cs: cs, order: sub.order}, firstAwake(cs))
|
||||
add(unit{cs: cs, order: sub.order, member: m.Path[depth]}, firstAwake(cs))
|
||||
}
|
||||
i = j
|
||||
continue
|
||||
}
|
||||
if ownRouting(m.Provider, g) {
|
||||
if ownRouting(m.Provider, g) || byWeight {
|
||||
// a provider routed its own way keeps it, as a group
|
||||
// in the group does: weighed as one by the first it
|
||||
// would try, and tried whole in its own order (kchen0x
|
||||
@@ -457,7 +465,7 @@ func planLevel(g provider.Group, ms []provider.Member, depth int, from provider.
|
||||
order = append(order, w)
|
||||
}
|
||||
if len(cs) > 0 {
|
||||
add(unit{cs: cs, order: order}, firstAwake(cs))
|
||||
add(unit{cs: cs, order: order, member: m.Path[depth]}, firstAwake(cs))
|
||||
}
|
||||
i++
|
||||
continue
|
||||
@@ -467,6 +475,27 @@ func planLevel(g provider.Group, ms []provider.Member, depth int, from provider.
|
||||
}
|
||||
i++
|
||||
}
|
||||
if byWeight {
|
||||
members := make([]string, len(units))
|
||||
for i, u := range units {
|
||||
members[i] = u.member
|
||||
}
|
||||
var out []candidate
|
||||
for i, k := range weightedUnits(g, members, heads) {
|
||||
u := units[k]
|
||||
seat := wrrSeat{round: provider.GroupPrefix + g.ID, member: u.member}
|
||||
for _, c := range u.cs {
|
||||
c.seats = append(slices.Clip(c.seats), seat)
|
||||
out = append(out, c)
|
||||
}
|
||||
order := slices.Clone(u.order)
|
||||
if i == 0 && len(units) > 1 && len(order) > 0 {
|
||||
order[0].Turn = true
|
||||
}
|
||||
pl.order = append(pl.order, order...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
routing := g.Routing
|
||||
if routing == provider.Manual {
|
||||
routing = "" // the member picked, its keys or accounts weighed smartly
|
||||
|
||||
@@ -10,6 +10,11 @@ package gateway
|
||||
// its affinity says (affinity.go); a request kept so counts against the
|
||||
// key that took it, not the one the round picked (weightedKept), so new
|
||||
// conversations make up the share.
|
||||
//
|
||||
// A group routed by weight (#1910) spreads its requests over its members
|
||||
// the same way, by each member's weight (provider.Group.Weights): a
|
||||
// member's own keys are ordered by its provider's routing, and a group in
|
||||
// it is one member, planned by its own.
|
||||
|
||||
import (
|
||||
"sync"
|
||||
@@ -25,8 +30,9 @@ var wrr = struct {
|
||||
}{m: map[string]*wrrRound{}}
|
||||
|
||||
type wrrRound struct {
|
||||
cur map[string]int // candidate rest → current weight
|
||||
cur map[string]int // candidate rest, or a group's member → current weight
|
||||
total int
|
||||
last string // the one the last pick was charged to
|
||||
}
|
||||
|
||||
// keyWeight is a candidate's weight: its key's, 1 when none.
|
||||
@@ -47,6 +53,21 @@ func resting(c candidate) bool {
|
||||
// weightedFirst puts first the key the provider id's round picks now, the
|
||||
// others after it in their order, for failover.
|
||||
func weightedFirst(id string, cs []candidate) []candidate {
|
||||
keys, weights, rests := make([]string, len(cs)), make([]int, len(cs)), make([]bool, len(cs))
|
||||
for i, c := range cs {
|
||||
keys[i], weights[i], rests[i] = c.rest, keyWeight(c), resting(c)
|
||||
}
|
||||
best := wrrPick(id, keys, weights, rests)
|
||||
if best <= 0 {
|
||||
return cs // first already, or all resting: restLast orders them
|
||||
}
|
||||
return append(append([]candidate{cs[best]}, cs[:best]...), cs[best+1:]...)
|
||||
}
|
||||
|
||||
// wrrPick is which of keys round id picks now, each weighing its weight,
|
||||
// those resting left out of the round; -1 when every one rests. The
|
||||
// pick is charged the round's total.
|
||||
func wrrPick(id string, keys []string, weights []int, rests []bool) int {
|
||||
wrr.Lock()
|
||||
defer wrr.Unlock()
|
||||
r := wrr.m[id]
|
||||
@@ -55,9 +76,9 @@ func weightedFirst(id string, cs []candidate) []candidate {
|
||||
wrr.m[id] = r
|
||||
}
|
||||
// keys no longer on are dropped from the round
|
||||
on := make(map[string]bool, len(cs))
|
||||
for _, c := range cs {
|
||||
on[c.rest] = true
|
||||
on := make(map[string]bool, len(keys))
|
||||
for _, k := range keys {
|
||||
on[k] = true
|
||||
}
|
||||
for k := range r.cur {
|
||||
if !on[k] {
|
||||
@@ -65,44 +86,81 @@ func weightedFirst(id string, cs []candidate) []candidate {
|
||||
}
|
||||
}
|
||||
best, total := -1, 0
|
||||
for i, c := range cs {
|
||||
if resting(c) {
|
||||
for i, k := range keys {
|
||||
if rests[i] {
|
||||
continue
|
||||
}
|
||||
w := keyWeight(c)
|
||||
r.cur[c.rest] += w
|
||||
total += w
|
||||
if best < 0 || r.cur[c.rest] > r.cur[cs[best].rest] {
|
||||
r.cur[k] += weights[i]
|
||||
total += weights[i]
|
||||
if best < 0 || r.cur[k] > r.cur[keys[best]] {
|
||||
best = i
|
||||
}
|
||||
}
|
||||
if best < 0 {
|
||||
return cs // all resting: restLast orders them
|
||||
return -1
|
||||
}
|
||||
r.cur[cs[best].rest] -= total
|
||||
r.total = total
|
||||
if best == 0 {
|
||||
return cs
|
||||
}
|
||||
return append(append([]candidate{cs[best]}, cs[:best]...), cs[best+1:]...)
|
||||
r.cur[keys[best]] -= total
|
||||
r.total, r.last = total, keys[best]
|
||||
return best
|
||||
}
|
||||
|
||||
// weightedKept moves the pick of picked's round to kept, when affinity
|
||||
// keeps a conversation with kept, another key of the same weighted
|
||||
// provider: the round counts the requests each key really took.
|
||||
// provider, or another member of a group routed by weight that both are
|
||||
// in: the round counts the requests each key, and each member, really
|
||||
// took.
|
||||
func weightedKept(picked, kept candidate) {
|
||||
if picked.p.Routing != provider.Weighted || picked.p.ID != kept.p.ID || picked.rest == kept.rest {
|
||||
return
|
||||
if picked.p.Routing == provider.Weighted && picked.p.ID == kept.p.ID && picked.rest != kept.rest {
|
||||
wrrMove(picked.p.ID, picked.rest, kept.rest)
|
||||
}
|
||||
for _, s := range picked.seats {
|
||||
for _, t := range kept.seats {
|
||||
if s.round == t.round && s.member != t.member {
|
||||
wrrMove(s.round, s.member, t.member)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// wrrMove charges round id's pick to kept rather than picked.
|
||||
func wrrMove(id, picked, kept string) {
|
||||
wrr.Lock()
|
||||
defer wrr.Unlock()
|
||||
r := wrr.m[picked.p.ID]
|
||||
if r == nil {
|
||||
r := wrr.m[id]
|
||||
if r == nil || r.last != picked {
|
||||
return
|
||||
}
|
||||
if _, ok := r.cur[kept.rest]; !ok {
|
||||
if _, ok := r.cur[kept]; !ok {
|
||||
return
|
||||
}
|
||||
r.cur[picked.rest] += r.total
|
||||
r.cur[kept.rest] -= r.total
|
||||
r.cur[picked] += r.total
|
||||
r.cur[kept] -= r.total
|
||||
r.last = kept
|
||||
}
|
||||
|
||||
// wrrSeat is a candidate's place in the round of a group routed by
|
||||
// weight it is in: the round (the group's ref) and the member it is of.
|
||||
type wrrSeat struct{ round, member string }
|
||||
|
||||
// weightedUnits orders the units of a group g routed by weight — each
|
||||
// member, a group in it as one — by g's round over their members'
|
||||
// weights: the one it picks first, the others after it in their order,
|
||||
// for failover. heads are what each is weighed by: one resting is left
|
||||
// out of the round.
|
||||
func weightedUnits(g provider.Group, members []string, heads []candidate) []int {
|
||||
weights, rests := make([]int, len(members)), make([]bool, len(members))
|
||||
for i, m := range members {
|
||||
weights[i], rests[i] = g.MemberWeight(m), resting(heads[i])
|
||||
}
|
||||
order := make([]int, 0, len(members))
|
||||
best := wrrPick(provider.GroupPrefix+g.ID, members, weights, rests)
|
||||
if best > 0 {
|
||||
order = append(order, best)
|
||||
}
|
||||
for i := range members {
|
||||
if i != best || best <= 0 {
|
||||
order = append(order, i)
|
||||
}
|
||||
}
|
||||
return order
|
||||
}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// A group routed by weight (#1910, DD on Discord): members weighing 3, 1
|
||||
// and 4 take three, one and four of every eight requests, each tried
|
||||
// whole — a member's keys in its provider's order, a group in it in its
|
||||
// own — the next one the fallback. A member resting leaves the round,
|
||||
// the others sharing it by their weights, and a conversation kept on a
|
||||
// member counts against that member, so new ones make up the share.
|
||||
func TestWeightedGroup(t *testing.T) {
|
||||
forgetSinks(t)
|
||||
s := &Server{}
|
||||
url := "http://127.0.0.1:1/v1"
|
||||
a := provider.Provider{ID: "wa", Chat: url, Key: "k-a"}
|
||||
b := provider.Provider{ID: "wb", Chat: url, Key: "k-b1", Keys: []provider.KeyAccount{{Key: "k-b2", Weight: 50}}, Routing: provider.Ordered}
|
||||
c := provider.Provider{ID: "wc", Chat: url, Key: "k-c"}
|
||||
d := provider.Provider{ID: "wd", Chat: url, Key: "k-d"}
|
||||
sub := provider.Group{ID: "wsub", Routing: provider.Ordered}
|
||||
g := provider.Group{ID: "wg", Routing: provider.Weighted, Members: []string{"wa/m", "wb/m:high", "group/wsub"},
|
||||
Weights: map[string]int{"wa/m": 3, "group/wsub": 4}}
|
||||
ms := []provider.Member{
|
||||
{ID: "wa/m", Path: []string{"wa/m"}, Provider: a, Model: "m"},
|
||||
{ID: "wb/m:high", Path: []string{"wb/m:high"}, Provider: b, Model: "m", Effort: "high"},
|
||||
{ID: "group/wsub", Path: []string{"group/wsub", "wc/m"}, Via: []provider.Group{sub}, Provider: c, Model: "m"},
|
||||
{ID: "group/wsub", Path: []string{"group/wsub", "wd/m"}, Via: []provider.Group{sub}, Provider: d, Model: "m"},
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
wrr.Lock()
|
||||
delete(wrr.m, provider.GroupPrefix+g.ID)
|
||||
wrr.Unlock()
|
||||
})
|
||||
unitOf := map[string]string{"wa": "a", "wb": "b", "wc": "sub", "wd": "sub"}
|
||||
plan := func() []candidate {
|
||||
t.Helper()
|
||||
cs, pl := s.planGroup(g, ms, provider.Chat)
|
||||
if len(cs) != 5 || len(pl.order) != 5 {
|
||||
t.Fatalf("%d planned, %d in the trace: %s", len(cs), len(pl.order), restsOf(cs))
|
||||
}
|
||||
// each member whole, in its own order
|
||||
var ids []string
|
||||
for _, c := range cs {
|
||||
ids = append(ids, c.p.ID)
|
||||
}
|
||||
joined := strings.Join(ids, " ")
|
||||
if !strings.Contains(joined, "wb wb") || !strings.Contains(joined, "wc wd") {
|
||||
t.Fatalf("a member split up: %s", joined)
|
||||
}
|
||||
if i := slices.Index(ids, "wb"); cs[i].p.Key != "k-b1" || cs[i+1].p.Key != "k-b2" {
|
||||
t.Fatalf("wb's keys not in its own order: %s", restsOf(cs))
|
||||
}
|
||||
if !pl.order[0].Turn || slices.ContainsFunc(pl.order[1:], func(w Weighed) bool { return w.Turn }) {
|
||||
t.Fatalf("its turn: %+v", pl.order)
|
||||
}
|
||||
return cs
|
||||
}
|
||||
var seq []string
|
||||
counts := func(n int, keep func(i int, cs []candidate) candidate) map[string]int {
|
||||
got := map[string]int{}
|
||||
seq = nil
|
||||
for i := range n {
|
||||
cs := plan()
|
||||
took := cs[0]
|
||||
if keep != nil {
|
||||
took = keep(i, cs)
|
||||
}
|
||||
got[unitOf[took.p.ID]]++
|
||||
seq = append(seq, unitOf[took.p.ID])
|
||||
}
|
||||
return got
|
||||
}
|
||||
if got := counts(8*25, nil); got["a"] != 75 || got["b"] != 25 || got["sub"] != 100 {
|
||||
t.Fatalf("3:1:4 over 200: %v", got)
|
||||
}
|
||||
// smoothly: never the same member three times running
|
||||
if strings.Contains(strings.Join(seq, " "), "sub sub sub") {
|
||||
t.Fatalf("not smooth: %v", seq[:8])
|
||||
}
|
||||
|
||||
// wa resting: wb and the group in it share its requests 1 : 4, and
|
||||
// wa is tried last
|
||||
var aKey string
|
||||
for _, c := range plan() {
|
||||
if c.p.ID == "wa" {
|
||||
aKey = c.restKey()
|
||||
}
|
||||
}
|
||||
restingUntil.Lock()
|
||||
restingUntil.m[aKey] = time.Now().Add(time.Hour)
|
||||
restingUntil.Unlock()
|
||||
if cs := plan(); cs[len(cs)-1].p.ID != "wa" {
|
||||
t.Fatalf("the resting member isn't last: %s", restsOf(cs))
|
||||
}
|
||||
wrr.Lock()
|
||||
delete(wrr.m, provider.GroupPrefix+g.ID)
|
||||
wrr.Unlock()
|
||||
if got := counts(5*20, nil); got["a"] != 0 || got["b"] != 20 || got["sub"] != 80 {
|
||||
t.Fatalf("with wa resting, 1:4 over 100: %v", got)
|
||||
}
|
||||
rested(aKey)
|
||||
|
||||
// a conversation kept on wb each round of eight: the round counts it
|
||||
// against wb
|
||||
wrr.Lock()
|
||||
delete(wrr.m, provider.GroupPrefix+g.ID)
|
||||
wrr.Unlock()
|
||||
got := counts(8*10, func(i int, cs []candidate) candidate {
|
||||
if i%8 != 0 || cs[0].p.ID == "wb" {
|
||||
return cs[0]
|
||||
}
|
||||
at := slices.IndexFunc(cs, func(c candidate) bool { return c.p.ID == "wb" })
|
||||
weightedKept(cs[0], cs[at])
|
||||
return cs[at]
|
||||
})
|
||||
if got["a"] != 30 || got["b"] != 10 || got["sub"] != 40 {
|
||||
t.Fatalf("with wb kept: %v", got)
|
||||
}
|
||||
}
|
||||
@@ -1388,6 +1388,11 @@ const I18N = {
|
||||
"Requests spread over the keys by the weight set beside each: a key weighing 3 takes three requests for every one a key weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with its key as Stays says.": "请求按每个密钥旁设置的权重分配:权重 3 的密钥每接 3 个请求,权重 1 的接 1 个,几个请求之内就均匀分开。出错的在休息期间被跳过,由其他密钥按各自权重分担;会话按「会话保持」的设置留在原来的密钥上。",
|
||||
"Weight {n} · {share}%": "权重 {n} · {share}%",
|
||||
"Its share of the requests: a key weighing 3 takes three for every one a key weighing 1 takes": "它在请求中的份额:权重 3 的密钥每接 3 个请求,权重 1 的接 1 个",
|
||||
"By weight: each model takes its share of the requests by the weight set beside it — one weighing 3 three for every one a model weighing 1 takes, spread out rather than in bursts. One resting after a failure leaves the round and the others share its requests; the next model is the fallback when one fails.": "按权重:每个模型按旁边设置的权重分得请求——权重 3 的模型每接 3 个,权重 1 的接 1 个,均匀穿插而不是成批连发。失败后休息中的模型退出这一轮,其余模型分担它的请求;某个模型失败时,由下一个模型接替。",
|
||||
"Weight {n}": "权重 {n}",
|
||||
"Its share of the requests: a model weighing 3 takes three for every one a model weighing 1 takes": "它在请求中的份额:权重 3 的模型每接 3 个请求,权重 1 的接 1 个",
|
||||
"Weight of {name}": "{name} 的权重",
|
||||
"A weight is 1 to 1000": "权重为 1 到 1000",
|
||||
"{key} weighs {n}": "{key} 的权重已设为 {n}",
|
||||
"Requests go to the first; the next takes over when the one before runs out of quota, hits a rate limit or fails.": "请求先发给第一个;它额度用完、被限流或出错时,由下一个接手。",
|
||||
"Each turn of a conversation goes to the next one, spreading the load evenly; the requests within a turn stay where it began, so the prompt cache holds, and one that fails is passed over while it rests.": "会话每一轮轮流交给下一个,均摊负载;同一轮内的请求留在起始处,保持提示词缓存;出错的在暂停期间跳过。",
|
||||
@@ -5991,6 +5996,11 @@ const I18N = {
|
||||
"Requests spread over the keys by the weight set beside each: a key weighing 3 takes three requests for every one a key weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with its key as Stays says.": "請求按每個金鑰旁設定的權重分配:權重 3 的金鑰每接 3 個請求,權重 1 的接 1 個,幾個請求之內就均勻分開。出錯的在休息期間被跳過,由其他金鑰按各自權重分擔;會話按「會話保持」的設定留在原來的金鑰上。",
|
||||
"Weight {n} · {share}%": "權重 {n} · {share}%",
|
||||
"Its share of the requests: a key weighing 3 takes three for every one a key weighing 1 takes": "它在請求中的份額:權重 3 的金鑰每接 3 個請求,權重 1 的接 1 個",
|
||||
"By weight: each model takes its share of the requests by the weight set beside it — one weighing 3 three for every one a model weighing 1 takes, spread out rather than in bursts. One resting after a failure leaves the round and the others share its requests; the next model is the fallback when one fails.": "按權重:每個模型按旁邊設定的權重分得請求——權重 3 的模型每接 3 個,權重 1 的接 1 個,均勻穿插而不是成批連發。失敗後休息中的模型退出這一輪,其餘模型分擔它的請求;某個模型失敗時,由下一個模型接替。",
|
||||
"Weight {n}": "權重 {n}",
|
||||
"Its share of the requests: a model weighing 3 takes three for every one a model weighing 1 takes": "它在請求中的份額:權重 3 的模型每接 3 個請求,權重 1 的接 1 個",
|
||||
"Weight of {name}": "{name} 的權重",
|
||||
"A weight is 1 to 1000": "權重為 1 到 1000",
|
||||
"{key} weighs {n}": "{key} 的權重已設為 {n}",
|
||||
"Requests go to the first; the next takes over when the one before runs out of quota, hits a rate limit or fails.": "請求先發給第一個;它額度用完、被限流或出錯時,由下一個接手。",
|
||||
"Each turn of a conversation goes to the next one, spreading the load evenly; the requests within a turn stay where it began, so the prompt cache holds, and one that fails is passed over while it rests.": "會話每一輪輪流交給下一個,均攤負載;同一輪內的請求留在起始處,保持提示詞快取;出錯的在暫停期間跳過。",
|
||||
@@ -10568,6 +10578,11 @@ const I18N = {
|
||||
"Requests spread over the keys by the weight set beside each: a key weighing 3 takes three requests for every one a key weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with its key as Stays says.": "各キーの横で設定した重みでリクエストを振り分けます。重み 3 のキーは、重み 1 のキーが 1 件受けるごとに 3 件受け、数件のうちに均等に分かれます。失敗したキーは休止中は飛ばされ、他のキーがそれぞれの重みで分担します。会話は「維持」の設定どおりそのキーにとどまります。",
|
||||
"Weight {n} · {share}%": "重み {n} · {share}%",
|
||||
"Its share of the requests: a key weighing 3 takes three for every one a key weighing 1 takes": "リクエストの取り分:重み 3 のキーは、重み 1 のキーが 1 件受けるごとに 3 件受けます",
|
||||
"By weight: each model takes its share of the requests by the weight set beside it — one weighing 3 three for every one a model weighing 1 takes, spread out rather than in bursts. One resting after a failure leaves the round and the others share its requests; the next model is the fallback when one fails.": "重み付け:各モデルは横に設定した重みに応じてリクエストを受けます。重み 3 のモデルは、重み 1 のモデルが 1 件受けるごとに 3 件受け、まとめてではなく分散して届きます。失敗して休止中のモデルは巡回から外れ、残りがその分を分け合います。あるモデルが失敗したときは次のモデルが引き継ぎます。",
|
||||
"Weight {n}": "重み {n}",
|
||||
"Its share of the requests: a model weighing 3 takes three for every one a model weighing 1 takes": "リクエストの取り分:重み 3 のモデルは、重み 1 のモデルが 1 件受けるごとに 3 件受けます",
|
||||
"Weight of {name}": "{name} の重み",
|
||||
"A weight is 1 to 1000": "重みは 1〜1000 です",
|
||||
"{key} weighs {n}": "{key} の重みを {n} にしました",
|
||||
"Requests go to the first; the next takes over when the one before runs out of quota, hits a rate limit or fails.": "リクエストは最初のものに送られます。クォータ切れ、レート制限、エラーのときは次のものが引き継ぎます。",
|
||||
"Each turn of a conversation goes to the next one, spreading the load evenly; the requests within a turn stay where it began, so the prompt cache holds, and one that fails is passed over while it rests.": "会話のターンごとに次のものへ送り、負荷を均等に分散します。ターン内のリクエストは開始した場所に留まるのでプロンプトキャッシュが効きます。エラーになったものは休止中スキップされます。",
|
||||
@@ -15165,6 +15180,11 @@ const I18N = {
|
||||
"Requests spread over the keys by the weight set beside each: a key weighing 3 takes three requests for every one a key weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with its key as Stays says.": "Anfragen verteilen sich nach dem Gewicht neben jedem Schlüssel: Einer mit Gewicht 3 bekommt drei Anfragen für jede, die einer mit Gewicht 1 bekommt, schon über wenige Anfragen gleichmäßig. Ein fehlschlagender wird übersprungen, solange er pausiert, und die anderen teilen sich seine Anfragen; ein Gespräch bleibt bei seinem Schlüssel, wie „Bleibt“ es sagt.",
|
||||
"Weight {n} · {share}%": "Gewicht {n} · {share}%",
|
||||
"Its share of the requests: a key weighing 3 takes three for every one a key weighing 1 takes": "Sein Anteil an den Anfragen: Ein Schlüssel mit Gewicht 3 bekommt drei für jede, die einer mit Gewicht 1 bekommt",
|
||||
"By weight: each model takes its share of the requests by the weight set beside it — one weighing 3 three for every one a model weighing 1 takes, spread out rather than in bursts. One resting after a failure leaves the round and the others share its requests; the next model is the fallback when one fails.": "Nach Gewicht: Jedes Modell bekommt seinen Anteil an den Anfragen nach dem Gewicht daneben – eines mit Gewicht 3 drei für jede, die ein Modell mit Gewicht 1 bekommt, verteilt statt in Schüben. Eines, das nach einem Fehler pausiert, setzt aus, und die anderen teilen sich seine Anfragen; scheitert eines, springt das nächste Modell ein.",
|
||||
"Weight {n}": "Gewicht {n}",
|
||||
"Its share of the requests: a model weighing 3 takes three for every one a model weighing 1 takes": "Sein Anteil an den Anfragen: Ein Modell mit Gewicht 3 bekommt drei für jede, die eines mit Gewicht 1 bekommt",
|
||||
"Weight of {name}": "Gewicht von {name}",
|
||||
"A weight is 1 to 1000": "Ein Gewicht ist 1 bis 1000",
|
||||
"{key} weighs {n}": "{key} hat jetzt Gewicht {n}",
|
||||
"Requests go to the first; the next takes over when the one before runs out of quota, hits a rate limit or fails.": "Anfragen gehen an das erste; das nächste übernimmt, wenn das vorherige kein Kontingent mehr hat, ein Rate-Limit erreicht oder fehlschlägt.",
|
||||
"Each turn of a conversation goes to the next one, spreading the load evenly; the requests within a turn stay where it began, so the prompt cache holds, and one that fails is passed over while it rests.": "Jede Runde eines Gesprächs geht an das nächste, damit sich die Last gleichmäßig verteilt; die Anfragen einer Runde bleiben dort, wo sie begann, damit der Prompt-Cache greift, und ein fehlgeschlagenes wird übersprungen, solange es pausiert.",
|
||||
|
||||
@@ -495,6 +495,9 @@ button.rt-session { cursor: pointer; }
|
||||
.rt-gedit .fbrow.muted > :not(.rt-mon):not(.text) { opacity: .45; }
|
||||
/* a member's own reasoning, beside its Up and Remove */
|
||||
.rt-gedit .fbrow .rt-fixed { height: 24px; padding: 0 9px; font-size: 11.5px; flex: none; }
|
||||
/* a member's weight under By weight (#1910), edited in place */
|
||||
.rt-gedit .fbrow .rt-weight { font-variant-numeric: tabular-nums; }
|
||||
.rt-gedit .fbrow .rt-weight-in { width: 64px; flex: none; height: 24px; font-size: 12px; padding: 0 6px; }
|
||||
/* a group a member of a group is: it takes no reasoning of its own (its
|
||||
models reason as it says, provider.SaveGroup), so its chip names the group
|
||||
it follows and opens that group's card instead. It takes the room it needs
|
||||
|
||||
@@ -394,6 +394,8 @@
|
||||
weight: ["By weight", "Requests spread over the keys by the weight set beside each: a key weighing 3 takes three requests for every one a key weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with its key as Stays says."],
|
||||
};
|
||||
const GROUP_ORDER = "In order: member by member, the first model the group names until it can't answer, each over its own accounts or keys as its provider routes them.";
|
||||
// a group routed by weight (#1910): its members, not its keys
|
||||
const GROUP_WEIGHT = "By weight: each model takes its share of the requests by the weight set beside it — one weighing 3 three for every one a model weighing 1 takes, spread out rather than in bursts. One resting after a failure leaves the round and the others share its requests; the next model is the fallback when one fails.";
|
||||
const KEYS_SMART = "Smart: keys that suit the request go first — one made for the model's own API — then in their order. One resting after a failure goes last.";
|
||||
const LONE = "Only one account or key is on for this, so routing has nothing to choose between. Turn on a second in the provider's editor, and how it routes is set under Several accounts or keys below.";
|
||||
|
||||
@@ -1453,7 +1455,7 @@
|
||||
el("span", "", (g ? " · " + t("routing group") : "") + " · " + t(on === 1 ? "one on" : "{n} on", { n: on })
|
||||
+ (many > 1 ? " · " + t("{n} agents at once", { n: many }) : "")));
|
||||
// keys that read their own windows are weighed as accounts are
|
||||
mode.textContent = lone ? t(LONE) : g && routing === "order" ? t(GROUP_ORDER) : t(!routing && f?.kind === "key" && !r.order.some((x) => x.known) && !g ? KEYS_SMART : m[1]);
|
||||
mode.textContent = lone ? t(LONE) : g && routing === "order" ? t(GROUP_ORDER) : g && routing === "weight" ? t(GROUP_WEIGHT) : t(!routing && f?.kind === "key" && !r.order.some((x) => x.known) && !g ? KEYS_SMART : m[1]);
|
||||
}
|
||||
// goTo makes what names a routing a way to where it is set: a provider's
|
||||
// own under Several accounts or keys, a group's its card
|
||||
@@ -3169,7 +3171,8 @@
|
||||
const ROUTE_OPTS = [["", "Smart"], ["order", "In order"], ["rotate", "In turn"], ["usage", "Least used"], ["pace", "Weekly pace"]];
|
||||
// a group may also be routed by hand: every request to the member the
|
||||
// user picks on its card (provider.Manual, #317) — a provider's keys can't
|
||||
const GROUP_ROUTE_OPTS = [...ROUTE_OPTS, ["manual", "Manual"]];
|
||||
// and by its members' weights, as a provider's keys are (#1910)
|
||||
const GROUP_ROUTE_OPTS = [...ROUTE_OPTS, ["weight", "By weight"], ["manual", "Manual"]];
|
||||
const AFF_OPTS = [["", "Auto"], ["session", "Session"], ["turn", "Within a turn"], ["off", "Off"], ["strict", "Strict"]];
|
||||
// what one rate limited with quota left does then (provider.Sink), as in
|
||||
// a provider's editor (app.js SINKS)
|
||||
@@ -3209,6 +3212,7 @@
|
||||
rotate: "In turn: each conversation's next turn goes to the next member's account or key, spreading the load.",
|
||||
usage: "Least used first: the account or key with the most of its allowance left goes first.",
|
||||
pace: "Weekly pace: the account with the most of its week left per hour until it renews goes first, so less of each member's week is lost at its reset — an account with five hours and no week (Claude Enterprise) by what its five hours have left per hour until they renew, so almost always first; a key by the tokens magpie sent it lately.",
|
||||
weight: GROUP_WEIGHT,
|
||||
manual: "Manual: every request goes to the model you pick on the group's card, over its own accounts or keys; the others, and the rules, wait until you pick another — none takes over when it fails.",
|
||||
};
|
||||
// a group in the group, and a provider set to route other than Smart, is
|
||||
@@ -3248,9 +3252,11 @@
|
||||
const ids = (v) => Array.isArray(v) ? v.filter((s) => typeof s === "string") : [];
|
||||
// the lists Go leaves out when empty stay out; null or a non-list is none
|
||||
const opt = (v, f) => v === undefined ? v : f(v);
|
||||
// a member's weight is a whole number; anything else is none
|
||||
const weightsOf = (v) => Object.fromEntries(Object.entries(v && typeof v === "object" && !Array.isArray(v) ? v : {}).filter(([, n]) => Number.isInteger(n)));
|
||||
const group = (g) => ({ ...g, id: String(g.id ?? ""), name: typeof g.name === "string" && g.name ? g.name : String(g.id ?? ""),
|
||||
members: ids(g.members), memberInfo: objs(g.memberInfo), holds: ids(g.holds), offers: ids(g.offers), shared: ids(g.shared), patterns: objs(g.patterns),
|
||||
match: opt(g.match, ids), matched: opt(g.matched, ids), off: opt(g.off, ids), fast: opt(g.fast, ids), levels: opt(g.levels, ids),
|
||||
match: opt(g.match, ids), matched: opt(g.matched, ids), off: opt(g.off, ids), fast: opt(g.fast, ids), levels: opt(g.levels, ids), weights: opt(g.weights, weightsOf),
|
||||
rules: opt(g.rules, (rs) => objs(rs).map((r) => ({ ...r, agents: opt(r.agents, ids), folders: opt(r.folders, ids), exceptFolders: opt(r.exceptFolders, ids) }))) });
|
||||
const refs = (v) => objs(v).filter((m) => typeof m.id === "string");
|
||||
return { ...x, groups: objs(x.groups).filter((g) => typeof g.id === "string" && g.id).map(group),
|
||||
@@ -3336,7 +3342,7 @@
|
||||
// there, rather than leaving the slot empty.
|
||||
const openGroupEditor = async (g) => {
|
||||
if (groupDirty() && !(await confirmDiscard())) return false;
|
||||
gEdit = { id: g.id, draft: { name: g.name, members: [...g.members], match: [...(g.match || [])], matched: [...(g.matched || [])], fast: [...(g.fast || [])], off: [...(g.off || [])], routing: g.routing || "", pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink, unlists: !!g.unlists, firstToken: g.firstToken || 0, patience: patienceOf(g.patience), context: g.context || 0, classifier: g.classifier || "", effort: g.effort || "", levels: [...(g.levels || [])], rules: (g.rules || []).map((r) => ({ ...r, intent: r.intent || "", agents: [...(r.agents || [])], folders: [...(r.folders || [])], exceptFolders: [...(r.exceptFolders || [])], time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } };
|
||||
gEdit = { id: g.id, draft: { name: g.name, members: [...g.members], match: [...(g.match || [])], matched: [...(g.matched || [])], fast: [...(g.fast || [])], off: [...(g.off || [])], weights: { ...(g.weights || {}) }, routing: g.routing || "", pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink, unlists: !!g.unlists, firstToken: g.firstToken || 0, patience: patienceOf(g.patience), context: g.context || 0, classifier: g.classifier || "", effort: g.effort || "", levels: [...(g.levels || [])], rules: (g.rules || []).map((r) => ({ ...r, intent: r.intent || "", agents: [...(r.agents || [])], folders: [...(r.folders || [])], exceptFolders: [...(r.exceptFolders || [])], time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } };
|
||||
renderGroups();
|
||||
return true;
|
||||
};
|
||||
@@ -3934,7 +3940,7 @@
|
||||
b.onclick = (e) => {
|
||||
e.stopPropagation(); // the card opens the editor; this picks
|
||||
if (on) return;
|
||||
groupAction("save", { id: g.id, name: g.name, members: namedOf(g), match: g.match || [], routing: "manual", pick: id, affinity: g.affinity || "", sink: !!g.sink, firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], off: g.off || [], unlists: !!g.unlists },
|
||||
groupAction("save", { id: g.id, name: g.name, members: namedOf(g), match: g.match || [], routing: "manual", pick: id, affinity: g.affinity || "", sink: !!g.sink, firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], off: g.off || [], weights: g.weights || {}, unlists: !!g.unlists },
|
||||
t("{name}: every request to {model}", { name: g.name, model: memberName(id) }));
|
||||
};
|
||||
box.append(b);
|
||||
@@ -3947,6 +3953,7 @@
|
||||
// made from a model (newGroupWith) had no fast, and Add threw on it
|
||||
// and did nothing (悠悠哥 on Discord)
|
||||
for (const k of ["members", "match", "matched", "fast", "off", "rules"]) if (!Array.isArray(d[k])) d[k] = [];
|
||||
if (!d.weights || typeof d.weights !== "object") d.weights = {};
|
||||
const ed = el("div", "editor rt-gedit");
|
||||
const h = el("div", "ehead");
|
||||
h.append(el("b", "", g ? g.name : t("New group")));
|
||||
@@ -4058,6 +4065,39 @@
|
||||
};
|
||||
return b;
|
||||
};
|
||||
// a member's weight under By weight, and its share of the requests
|
||||
// among those on, as a provider's keys show theirs (app.js keyWeight)
|
||||
const weightOf = (id) => Math.max(d.weights[id] || 0, 1);
|
||||
const memberWeight = (id, off) => {
|
||||
const w = weightOf(id), total = d.members.filter((x) => !d.off.includes(x)).reduce((n, x) => n + weightOf(x), 0);
|
||||
const b = el("button", "rt-cond rt-fixed rt-weight" + (w > 1 ? " on" : ""), off ? t("Weight {n}", { n: w }) : t("Weight {n} · {share}%", { n: w, share: Math.round(100 * w / (total || 1)) }));
|
||||
b.type = "button";
|
||||
b.title = t("Its share of the requests: a model weighing 3 takes three for every one a model weighing 1 takes");
|
||||
b.onclick = () => {
|
||||
const i = input(String(w), "1");
|
||||
i.type = "number";
|
||||
i.min = "1";
|
||||
i.max = "1000";
|
||||
i.className = "rt-weight-in";
|
||||
i.setAttribute("aria-label", t("Weight of {name}", { name: memberName(id) }));
|
||||
i.title = b.title;
|
||||
let done = false;
|
||||
const keep = (yes) => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
const n = Math.round(Number(i.value));
|
||||
if (yes && n >= 1 && n <= 1000) { if (n > 1) d.weights[id] = n; else delete d.weights[id]; }
|
||||
else if (yes && i.value.trim()) status(t("A weight is 1 to 1000"), "warn");
|
||||
draw();
|
||||
};
|
||||
i.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") keep(true); else if (e.key === "Escape") keep(false); };
|
||||
i.onblur = () => keep(true);
|
||||
b.replaceWith(i);
|
||||
i.focus({ preventScroll: true });
|
||||
i.select();
|
||||
};
|
||||
return b;
|
||||
};
|
||||
const draw = () => {
|
||||
list.replaceChildren();
|
||||
d.members.forEach((id, i) => {
|
||||
@@ -4119,6 +4159,7 @@
|
||||
for (const r of d.rules) if (r.use === id) r.use = to;
|
||||
d.fast = d.fast.map((x) => x === id ? to : x);
|
||||
d.off = d.off.map((x) => x === id ? to : x);
|
||||
if (d.weights[id]) { d.weights[to] = d.weights[id]; delete d.weights[id]; }
|
||||
if (d.pick === id) d.pick = to;
|
||||
draw(); drawRules();
|
||||
}, fixed);
|
||||
@@ -4156,6 +4197,9 @@
|
||||
};
|
||||
row.append(hx);
|
||||
}
|
||||
// its share by weight (#1910): a click edits it in place, Enter
|
||||
// or leaving it keeps it, Escape puts it back
|
||||
if (d.routing === "weight") row.append(memberWeight(id, off));
|
||||
if (s) row.title = s.members.map((x) => memberLabel(s, x)).join(s.routing === "order" ? " → " : " · ");
|
||||
if (!m && !s) { row.classList.add("off"); row.title = info?.providerOff ? offWords(info) : t("No provider serves {id} now; it is skipped", { id }); }
|
||||
if (matched) {
|
||||
@@ -4269,7 +4313,7 @@
|
||||
|
||||
const rHint = el("div", "hint", t(GROUP_HINT[d.routing] || GROUP_HINT[""]));
|
||||
const rw = el("div");
|
||||
rw.append(segs(GROUP_ROUTE_OPTS.map(([id, n]) => [id, t(n)]), d.routing, (v) => { d.routing = v; rHint.textContent = t(GROUP_HINT[v] || GROUP_HINT[""]); drawRules(); drawSink(); }), rHint);
|
||||
rw.append(segs(GROUP_ROUTE_OPTS.map(([id, n]) => [id, t(n)]), d.routing, (v) => { d.routing = v; rHint.textContent = t(GROUP_HINT[v] || GROUP_HINT[""]); draw(); drawRules(); drawSink(); }), rHint);
|
||||
rw.append(el("div", "hint", t(GROUP_NEST)));
|
||||
ed.append(el("label", "", t("Routing")), rw);
|
||||
// one rate limited with quota left: its place, or the back
|
||||
@@ -4710,7 +4754,7 @@
|
||||
if (own && !d.levels.length) return status(t("Pick a level to offer, or leave them to its models"), "warn");
|
||||
saveBtn.classList.add("busy");
|
||||
// refused, Add can be pressed again (busy, it takes no clicks)
|
||||
groupAction("save", { id: idOf(), from: g?.id, name: d.name.trim() || idOf(), members: namedOf(d), match: d.match, routing: d.routing, pick: d.pick || "", affinity: d.affinity, sink: !!d.sink && sinkable(d.routing), firstToken: d.firstToken || 0, patience: d.patience || 0, rules: d.rules, effort: d.effort, classifier: d.rules.some((r) => r.intent) || d.effort === "auto" ? d.classifier : "", context: d.context || 0, levels: own ? d.levels : [], family: g?.family || "", fast: d.fast.filter((x) => d.members.includes(x)), off: d.off.filter((x) => d.members.includes(x)), unlists: !!d.unlists }, t(g ? "{name} saved" : "{name} added", { name: d.name.trim() || idOf() }))
|
||||
groupAction("save", { id: idOf(), from: g?.id, name: d.name.trim() || idOf(), members: namedOf(d), match: d.match, routing: d.routing, pick: d.pick || "", affinity: d.affinity, sink: !!d.sink && sinkable(d.routing), firstToken: d.firstToken || 0, patience: d.patience || 0, rules: d.rules, effort: d.effort, classifier: d.rules.some((r) => r.intent) || d.effort === "auto" ? d.classifier : "", context: d.context || 0, levels: own ? d.levels : [], family: g?.family || "", fast: d.fast.filter((x) => d.members.includes(x)), off: d.off.filter((x) => d.members.includes(x)), weights: Object.fromEntries(Object.entries(d.weights).filter(([x, n]) => d.members.includes(x) && n > 1)), unlists: !!d.unlists }, t(g ? "{name} saved" : "{name} added", { name: d.name.trim() || idOf() }))
|
||||
.then(() => saveBtn.classList.remove("busy"));
|
||||
};
|
||||
// what goes wrong is said where it is seen, never a click that does nothing
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A group may route By weight (#1910, DD on Discord): each model takes its
|
||||
// share of the requests by the weight set beside it. In the group editor
|
||||
// the routing's segments offer By weight; picked, every member shows its
|
||||
// weight and its share of the requests among those on ("Weight 3 · 60%"),
|
||||
// one switched off its weight alone. A click on it edits it in place:
|
||||
// Enter keeps it, Escape puts it back, and one out of 1 to 1000 is refused
|
||||
// with a warning. Nothing on the page moves. Saved, the group goes with
|
||||
// routing "weight" and the weights above 1 of the members it still has. At
|
||||
// 420px the segments and the rows don't spill. English, Chinese and German,
|
||||
// Chromium and WebKit; no backend, the API is faked here.
|
||||
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 { reach } = require("./reader.cjs");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const models = [
|
||||
{ id: "oa/gpt-6.1-sol", name: "gpt-6.1-sol", providerName: "OpenAI", icon: "generic", efforts: ["low", "medium", "high", "xhigh"] },
|
||||
{ id: "rl/glm-5", name: "glm-5", providerName: "Relay", icon: "generic" },
|
||||
{ id: "rl/o4-mini", name: "o4-mini", providerName: "Relay", icon: "generic" },
|
||||
{ id: "rl/kimi-k2.6", name: "kimi-k2.6", providerName: "Relay", icon: "generic" },
|
||||
];
|
||||
const members = ["oa/gpt-6.1-sol:high", "rl/glm-5", "rl/o4-mini", "rl/kimi-k2.6"];
|
||||
const groups = () => ({
|
||||
models, pools: [],
|
||||
groups: [{ id: "sol", name: "Sol", members, routing: "order", ready: true, off: ["rl/kimi-k2.6"],
|
||||
weights: { "oa/gpt-6.1-sol:high": 3, "rl/kimi-k2.6": 2 },
|
||||
memberInfo: members.map((id) => ({ id, ready: true })) }],
|
||||
});
|
||||
|
||||
function serve(lang, posts) {
|
||||
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(() => {}); // nothing more comes
|
||||
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/")) {
|
||||
posts.push({ path: url.pathname, body: JSON.parse(r.request().postData() || "{}") });
|
||||
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, width] of [["en", 1100], ["zh", 1100], ["en", 420], ["de", 420]]) {
|
||||
test(`${engine} ${lang} ${width}: a group routes by its members' weights`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const height = 1400;
|
||||
const page = await (await browser.newContext({ viewport: { width, height }, reducedMotion: "reduce" })).newPage();
|
||||
t.after(async () => {
|
||||
if (process.env.ARTIFACT_DIR) {
|
||||
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
|
||||
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-group-member-weight.png`) });
|
||||
}
|
||||
await browser.close();
|
||||
});
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [], posts = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang, posts));
|
||||
await page.goto("http://magpie.test/?view=routing");
|
||||
const tr = (k, v = {}) => page.evaluate(([lang, k, v]) => (lang === "en" ? k : I18N[lang][k] || k).replace(/\{(\w+)\}/g, (_, n) => v[n]), [lang, k, v]);
|
||||
const card = page.locator(".rt-group", { hasText: "Sol" });
|
||||
await card.waitFor();
|
||||
await card.locator("button", { hasText: await tr("Edit") }).click();
|
||||
const ed = page.locator(".rt-gedit");
|
||||
const row = (name) => ed.locator(".fbrow", { has: page.locator(".n", { hasText: name }) });
|
||||
const weight = (name) => row(name).locator("button.rt-weight");
|
||||
await row("glm-5").waitFor();
|
||||
assert.equal(await ed.locator("button.rt-weight").count(), 0, "In order shows no weights");
|
||||
|
||||
const byWeight = ed.locator(".segs .opt", { hasText: await tr("By weight") });
|
||||
// what is clicked is wheeled into view by the test, as the reader
|
||||
// would, and the click itself moves nothing: its row stays under
|
||||
// the pointer (rows above it that grow are held by the view)
|
||||
const still = async (what, act, why) => {
|
||||
await reach(page, what);
|
||||
const row = what.locator("xpath=ancestor::*[contains(@class,'fbrow') or contains(@class,'segs')][1]");
|
||||
const top = async () => Math.round((await row.boundingBox()).y);
|
||||
const before = await top();
|
||||
await act();
|
||||
await page.waitForTimeout(200);
|
||||
assert.equal(await top(), before, why);
|
||||
};
|
||||
await still(byWeight, () => byWeight.click(), "picking By weight moved nothing");
|
||||
assert.equal(await byWeight.getAttribute("aria-pressed"), "true");
|
||||
assert(await ed.locator(".hint", { hasText: (await tr("By weight: each model takes its share of the requests by the weight set beside it — one weighing 3 three for every one a model weighing 1 takes, spread out rather than in bursts. One resting after a failure leaves the round and the others share its requests; the next model is the fallback when one fails.")).slice(0, 12) }).count(), "the hint says what By weight does");
|
||||
// 3 + 1 + 1 among those on; kimi is off and has its weight alone
|
||||
assert.equal(await weight("gpt-6.1-sol").textContent(), await tr("Weight {n} · {share}%", { n: 3, share: 60 }));
|
||||
assert.equal(await weight("glm-5").textContent(), await tr("Weight {n} · {share}%", { n: 1, share: 20 }));
|
||||
assert.equal(await weight("o4-mini").textContent(), await tr("Weight {n} · {share}%", { n: 1, share: 20 }));
|
||||
assert.equal(await weight("kimi-k2.6").textContent(), await tr("Weight {n}", { n: 2 }));
|
||||
|
||||
// edited in place: Enter keeps it
|
||||
const input = row("glm-5").locator("input.rt-weight-in");
|
||||
await still(weight("glm-5"), async () => {
|
||||
await weight("glm-5").click();
|
||||
assert.equal(await input.getAttribute("aria-label"), await tr("Weight of {name}", { name: "glm-5" }));
|
||||
await input.fill("6");
|
||||
await input.press("Enter");
|
||||
}, "editing a weight moved nothing");
|
||||
assert.equal(await weight("glm-5").textContent(), await tr("Weight {n} · {share}%", { n: 6, share: 60 }));
|
||||
assert.equal(await weight("gpt-6.1-sol").textContent(), await tr("Weight {n} · {share}%", { n: 3, share: 30 }));
|
||||
// Escape puts it back; out of 1 to 1000 is refused, with a warning
|
||||
await weight("o4-mini").click();
|
||||
await row("o4-mini").locator("input.rt-weight-in").fill("9");
|
||||
await row("o4-mini").locator("input.rt-weight-in").press("Escape");
|
||||
assert.equal(await weight("o4-mini").textContent(), await tr("Weight {n} · {share}%", { n: 1, share: 10 }));
|
||||
await weight("o4-mini").click();
|
||||
await row("o4-mini").locator("input.rt-weight-in").fill("1001");
|
||||
await row("o4-mini").locator("input.rt-weight-in").press("Enter");
|
||||
assert.equal(await weight("o4-mini").textContent(), await tr("Weight {n} · {share}%", { n: 1, share: 10 }));
|
||||
assert(await page.locator("body", { hasText: await tr("A weight is 1 to 1000") }).count(), "the refusal is said");
|
||||
|
||||
// nothing spills, and no left-border accent
|
||||
const spill = await page.evaluate(() => {
|
||||
const ed = document.querySelector(".rt-gedit").getBoundingClientRect();
|
||||
const out = [...document.querySelectorAll(".rt-gedit .segs, .rt-gedit .rt-weight")].filter((e) => e.getBoundingClientRect().right > ed.right + 1).map((e) => e.className + ":" + e.textContent);
|
||||
if (document.scrollingElement.scrollWidth > innerWidth) out.push("page " + document.scrollingElement.scrollWidth);
|
||||
return out;
|
||||
});
|
||||
assert.deepEqual(spill, [], "nothing spills at " + width);
|
||||
const border = await page.evaluate(() => [...document.querySelectorAll(".rt-weight")].map((e) => getComputedStyle(e))
|
||||
.filter((c) => c.borderLeftWidth !== c.borderRightWidth || c.borderLeftColor !== c.borderRightColor));
|
||||
assert.equal(border.length, 0, "no left-border accent");
|
||||
|
||||
const b = ed.locator("button.primary", { hasText: await tr("Save") });
|
||||
await page.mouse.move(width / 2, 600);
|
||||
for (let i = 0; i < 20 && (await b.boundingBox()).y > height - 160; i++) {
|
||||
await page.mouse.wheel(0, 300);
|
||||
await page.waitForTimeout(150);
|
||||
}
|
||||
const bb = await b.boundingBox();
|
||||
await page.mouse.click(bb.x + bb.width / 2, bb.y + bb.height / 2);
|
||||
await page.waitForFunction(() => !document.querySelector(".rt-gedit"));
|
||||
const sent = posts.find((p) => p.path === "/api/groups/save");
|
||||
assert.equal(sent.body.routing, "weight");
|
||||
assert.deepEqual(sent.body.weights, { "oa/gpt-6.1-sol:high": 3, "rl/glm-5": 6, "rl/kimi-k2.6": 2 });
|
||||
|
||||
const missing = await page.evaluate(() => [
|
||||
"By weight", "Weight {n}", "Weight {n} · {share}%", "Weight of {name}", "A weight is 1 to 1000",
|
||||
"Its share of the requests: a model weighing 3 takes three for every one a model weighing 1 takes",
|
||||
"By weight: each model takes its share of the requests by the weight set beside it — one weighing 3 three for every one a model weighing 1 takes, spread out rather than in bursts. One resting after a failure leaves the round and the others share its requests; the next model is the fallback when one fails.",
|
||||
].filter((k) => !I18N.zh[k] || !I18N["zh-TW"][k] || !I18N.ja[k] || !I18N.de[k]));
|
||||
assert.deepEqual(missing, [], "every string has its translations");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ package provider
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
@@ -214,6 +215,12 @@ type Group struct {
|
||||
// beside Members, not in their ids, so a version before it still
|
||||
// routes to them, only not fast.
|
||||
Fast []string `json:"fast,omitempty"`
|
||||
// Weights are the members' shares (as Members spells them) when the
|
||||
// group routes by weight (Weighted, #1910): one weighing 3 takes three
|
||||
// requests for every one a member weighing 1 takes. One not in it
|
||||
// weighs 1. Kept while the group routes otherwise, for when it is by
|
||||
// weight again.
|
||||
Weights map[string]int `json:"weights,omitempty"`
|
||||
// Family is a tag the group goes by in which agents are shown it
|
||||
// (settings' Visible), with its id.
|
||||
Family string `json:"family,omitempty"`
|
||||
@@ -350,6 +357,12 @@ func withoutRemoved(g Group, have map[string]bool) Group {
|
||||
g.Members = kept
|
||||
g.Off = slices.DeleteFunc(slices.Clone(g.Off), gone)
|
||||
g.Fast = slices.DeleteFunc(slices.Clone(g.Fast), gone)
|
||||
g.Weights = renamedWeights(g.Weights, func(m string) string {
|
||||
if gone(m) {
|
||||
return ""
|
||||
}
|
||||
return m
|
||||
})
|
||||
return g
|
||||
}
|
||||
|
||||
@@ -365,6 +378,7 @@ func (g Group) own() Group {
|
||||
g.Off = slices.Clone(g.Off)
|
||||
g.Levels = slices.Clone(g.Levels)
|
||||
g.Fast = slices.Clone(g.Fast)
|
||||
g.Weights = maps.Clone(g.Weights)
|
||||
g.Rules = slices.Clone(g.Rules)
|
||||
for i, r := range g.Rules {
|
||||
g.Rules[i].Agents = slices.Clone(r.Agents)
|
||||
@@ -970,6 +984,9 @@ func SaveGroup(g Group) error {
|
||||
}
|
||||
}
|
||||
g.Off = off
|
||||
if err := cleanWeights(entries, &g); err != nil {
|
||||
return err
|
||||
}
|
||||
if g.Routing != Manual && len(g.Members) > 0 && len(g.Off) == len(g.Members) {
|
||||
return fmt.Errorf("every model in %s is switched off: switch one on, or it has nothing to send to", g.Name)
|
||||
}
|
||||
@@ -984,7 +1001,7 @@ func SaveGroup(g Group) error {
|
||||
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 {
|
||||
if g.Routing != Ordered && g.Routing != Rotate && g.Routing != LeastUsed && g.Routing != Pace && g.Routing != Weighted && g.Routing != Manual {
|
||||
g.Routing = ""
|
||||
}
|
||||
if !slices.Contains(Affinities, g.Affinity) {
|
||||
@@ -1360,6 +1377,12 @@ func RenameGroup(from, to string) error {
|
||||
f.Groups[i].Off[j] = now
|
||||
}
|
||||
}
|
||||
f.Groups[i].Weights = renamedWeights(f.Groups[i].Weights, func(m string) string {
|
||||
if m == old {
|
||||
return now
|
||||
}
|
||||
return m
|
||||
})
|
||||
if f.Groups[i].Classifier == old {
|
||||
f.Groups[i].Classifier = now
|
||||
}
|
||||
|
||||
@@ -190,6 +190,7 @@ func ImportGroup(text string) (Imported, error) {
|
||||
p, id, ok := resolveIn(entries, model)
|
||||
return ok && !CanFast(p, id)
|
||||
})
|
||||
g.Weights = renamedWeights(g.Weights, func(m string) string { return here[strings.TrimSpace(m)] })
|
||||
if g.Routing != Manual && len(g.Off) == len(g.Members) {
|
||||
g.Off = nil // the ones it sent to are gone: those left are on
|
||||
}
|
||||
|
||||
@@ -192,7 +192,8 @@ func (g *Group) SetMemberFast(id string, fast bool) {
|
||||
}
|
||||
|
||||
// RenameMember has the group's member from go by to (its effort changed):
|
||||
// its rules, its pick, its fast mode and its being off follow it.
|
||||
// its rules, its pick, its fast mode, its being off and its weight
|
||||
// follow it.
|
||||
func (g *Group) RenameMember(from, to string) {
|
||||
for i, m := range g.Members {
|
||||
if m == from {
|
||||
@@ -217,4 +218,10 @@ func (g *Group) RenameMember(from, to string) {
|
||||
g.Off[i] = to
|
||||
}
|
||||
}
|
||||
g.Weights = renamedWeights(g.Weights, func(m string) string {
|
||||
if m == from {
|
||||
return to
|
||||
}
|
||||
return m
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// MemberWeight is the share of the group's requests its member id takes
|
||||
// when the group routes by weight (Group.Weights): 1 when none is set.
|
||||
func (g Group) MemberWeight(id string) int { return max(g.Weights[id], 1) }
|
||||
|
||||
// SetMemberWeight sets the share the group's member id takes when the
|
||||
// group routes by weight; 1 or less is the default, left out.
|
||||
func (g *Group) SetMemberWeight(id string, weight int) {
|
||||
g.Weights = renamedWeights(g.Weights, func(m string) string {
|
||||
if m == id {
|
||||
return ""
|
||||
}
|
||||
return m
|
||||
})
|
||||
if weight > 1 {
|
||||
if g.Weights == nil {
|
||||
g.Weights = map[string]int{}
|
||||
}
|
||||
g.Weights[id] = weight
|
||||
}
|
||||
}
|
||||
|
||||
// renamedWeights is weights with each member as to spells it now, those
|
||||
// it gives "" dropped; nil when none is left.
|
||||
func renamedWeights(weights map[string]int, to func(string) string) map[string]int {
|
||||
var out map[string]int
|
||||
for m, w := range weights {
|
||||
if m = to(m); m == "" {
|
||||
continue
|
||||
}
|
||||
if out == nil {
|
||||
out = map[string]int{}
|
||||
}
|
||||
out[m] = max(out[m], w)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// cleanWeights keeps g.Weights to its members as Members spells them,
|
||||
// each weighing 2 to MaxKeyWeight, as a provider's keys do (#841): 1, the
|
||||
// default, and 0 are left out, and one outside the range is refused.
|
||||
func cleanWeights(entries []Entry, g *Group) error {
|
||||
var err error
|
||||
g.Weights = renamedWeights(g.Weights, func(m string) string {
|
||||
id, _ := memberFastIn(entries, strings.TrimSpace(m))
|
||||
id = cleanMember(entries, id)
|
||||
w := g.Weights[m]
|
||||
if w < 0 || w > MaxKeyWeight {
|
||||
err = fmt.Errorf("%s weighs %d: a member's weight is 1 to %d", id, w, MaxKeyWeight)
|
||||
}
|
||||
for _, have := range g.Members {
|
||||
if have == id && w > 1 {
|
||||
return id
|
||||
}
|
||||
}
|
||||
return ""
|
||||
})
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"maps"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A group routed by weight (#1910) keeps each member's weight under the
|
||||
// member as Members spells it: a member typed :fast, a default of 1 left
|
||||
// out, one not in the group dropped, and one outside 1 to 1000 refused.
|
||||
// The weight follows its member when the member's effort, its provider's
|
||||
// id or a group in it is renamed, and when the group is shared to another
|
||||
// magpie.
|
||||
func TestSaveGroupWeights(t *testing.T) {
|
||||
fastHome(t)
|
||||
weights := func(id string) map[string]int {
|
||||
t.Helper()
|
||||
g, _, ok := FindGroup(GroupPrefix + id)
|
||||
if !ok {
|
||||
t.Fatalf("no group %s", id)
|
||||
}
|
||||
return g.Weights
|
||||
}
|
||||
if err := SaveGroup(Group{ID: "in", Name: "In", Members: []string{"rl/claude-opus-5-5", "an/claude-sonnet-5"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g := Group{ID: "spread", Name: "Spread", Routing: Weighted,
|
||||
Members: []string{"oa/gpt-6.1-sol:high:fast", "rl/gpt-6.1-sol", "an/claude-opus-5-5", "group/in"},
|
||||
Weights: map[string]int{"oa/gpt-6.1-sol:high:fast": 3, "rl/gpt-6.1-sol": 1, "an/claude-opus-5-5": 0, "group/in": 7, "an/claude-sonnet-5": 9}}
|
||||
if err := SaveGroup(g); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
saved, _, _ := FindGroup(GroupPrefix + "spread")
|
||||
if saved.Routing != Weighted {
|
||||
t.Fatalf("routing %q", saved.Routing)
|
||||
}
|
||||
if want := map[string]int{"oa/gpt-6.1-sol:high": 3, "group/in": 7}; !maps.Equal(saved.Weights, want) {
|
||||
t.Fatalf("weights %v, want %v", saved.Weights, want)
|
||||
}
|
||||
if saved.MemberWeight("rl/gpt-6.1-sol") != 1 || saved.MemberWeight("oa/gpt-6.1-sol:high") != 3 {
|
||||
t.Fatalf("member weights %d %d", saved.MemberWeight("rl/gpt-6.1-sol"), saved.MemberWeight("oa/gpt-6.1-sol:high"))
|
||||
}
|
||||
for _, w := range []int{-1, MaxKeyWeight + 1} {
|
||||
bad := saved
|
||||
bad.Weights = map[string]int{"rl/gpt-6.1-sol": w}
|
||||
if err := SaveGroup(bad); err == nil || !strings.Contains(err.Error(), "weight") {
|
||||
t.Fatalf("weight %d: %v", w, err)
|
||||
}
|
||||
}
|
||||
|
||||
// its effort changed: the weight goes with it
|
||||
saved.RenameMember("oa/gpt-6.1-sol:high", "oa/gpt-6.1-sol:low")
|
||||
if saved.MemberWeight("oa/gpt-6.1-sol:low") != 3 || saved.MemberWeight("oa/gpt-6.1-sol:high") != 1 {
|
||||
t.Fatalf("after RenameMember %v", saved.Weights)
|
||||
}
|
||||
saved.SetMemberWeight("rl/gpt-6.1-sol", 2)
|
||||
saved.SetMemberWeight("group/in", 1)
|
||||
if err := SaveGroup(saved); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := map[string]int{"oa/gpt-6.1-sol:low": 3, "rl/gpt-6.1-sol": 2}; !maps.Equal(weights("spread"), want) {
|
||||
t.Fatalf("after SetMemberWeight %v, want %v", weights("spread"), want)
|
||||
}
|
||||
|
||||
// the provider renamed, a group in it renamed
|
||||
if err := Rename("rl", "relay"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
saved, _, _ = FindGroup(GroupPrefix + "spread")
|
||||
saved.SetMemberWeight("group/in", 4)
|
||||
if err := SaveGroup(saved); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := RenameGroup("in", "inner"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := map[string]int{"oa/gpt-6.1-sol:low": 3, "relay/gpt-6.1-sol": 2, "group/inner": 4}; !maps.Equal(weights("spread"), want) {
|
||||
t.Fatalf("after the renames %v, want %v", weights("spread"), want)
|
||||
}
|
||||
|
||||
// shared to another magpie, under the same models
|
||||
text, err := ShareGroup("spread")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := DeleteGroup("spread"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := ImportGroup(text); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var back Group
|
||||
for _, x := range Groups() {
|
||||
if x.Name == "Spread" {
|
||||
back = x
|
||||
}
|
||||
}
|
||||
if back.Routing != Weighted || back.MemberWeight("relay/gpt-6.1-sol") != 2 || back.MemberWeight("oa/gpt-6.1-sol:low") != 3 {
|
||||
t.Fatalf("imported %q %v", back.Routing, back.Weights)
|
||||
}
|
||||
}
|
||||
@@ -91,6 +91,7 @@ func Rename(from, to string) error {
|
||||
for k, m := range g.Off {
|
||||
g.Off[k] = renamedRef(m, from, to)
|
||||
}
|
||||
g.Weights = renamedWeights(g.Weights, func(m string) string { return renamedRef(m, from, to) })
|
||||
g.Classifier = renamedRef(g.Classifier, from, to)
|
||||
g.Pick = renamedRef(g.Pick, from, to)
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ func (m *model) reloadGroups() {
|
||||
m.grow = clamp(m.grow, len(m.groups))
|
||||
}
|
||||
|
||||
var routings = []string{"", provider.Ordered, provider.Rotate, provider.LeastUsed, provider.Pace, provider.Manual}
|
||||
var routings = []string{"", provider.Ordered, provider.Rotate, provider.LeastUsed, provider.Pace, provider.Weighted, provider.Manual}
|
||||
|
||||
func routingName(v string) string {
|
||||
switch v {
|
||||
|
||||
@@ -175,6 +175,7 @@
|
||||
<tr><td>持ち回り <code>rotate</code></td><td>各会話の次のターンを、次のメンバーのアカウントやキーに送り、負荷を分散します。</td></tr>
|
||||
<tr><td>使用量の少ない順 <code>usage</code></td><td>利用枠の残りが最も多いアカウントやキー。</td></tr>
|
||||
<tr><td>週のペース <code>pace</code></td><td>更新までの 1 時間あたりの週の枠の残りが最も多いアカウント、つまりリセット時に失う分が最も多いもの。これにより各メンバーの週の枠がリセットで無駄になりにくくなります。週の枠がなく 5 時間枠だけのアカウント(Claude Enterprise)は、更新までの 1 時間あたりの 5 時間枠の残りで判断されるので、ほぼ常に最初になります。使用率が 90% 以上のものは、他が応答できなくなるまで待ちます。キーは最近送ったトークン数で判断します。</td></tr>
|
||||
<tr><td>重み順 <code>weight</code></td><td>グループ編集画面で各モデルの横に設定した重み(1〜1000、未設定は 1)に応じてリクエストを分けます。重み 3 のモデルは重み 1 のモデルが 1 件受けるごとに 3 件受け、まとめてではなく均等に散らします。各モデルは自分のプロバイダーのルーティングで自分のアカウントやキーを使い、グループ内のグループは 1 つとして数えます。失敗して休んでいるものはその回から外れ、失敗したときは次のモデルが代わりに答えます。</td></tr>
|
||||
</table></div>
|
||||
<div class="table-wrap"><table>
|
||||
<tr><th>維持</th><th>会話が、応答したアカウントやキーに留まる期間</th></tr>
|
||||
@@ -217,6 +218,7 @@
|
||||
<pre id="ex-group">magpie groups <span class="c"># 自分のグループ、次に magpie が見つけたもの</span>
|
||||
magpie group add <span class="s">"Opus anywhere"</span> models=claude/claude-opus-5-5,copilot/claude-opus-5.5 routing=order stays=session
|
||||
magpie group set opus-anywhere models+=openrouter/anthropic/claude-opus-5.5
|
||||
magpie group set opus-anywhere routing=weight weight=claude/claude-opus-5-5=3 <span class="c"># 4 件に 3 件をこれに</span>
|
||||
magpie group rule add opus-anywhere use=openrouter/anthropic/claude-opus-5.5 tokens=150k <span class="c"># 長いターンはまずこれへ</span>
|
||||
magpie group rule add opus-anywhere use=copilot/claude-opus-5.5 intent=<span class="s">"ちょっとした質問"</span> classifier=groq/llama-3.1-8b-instant
|
||||
magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash compact <span class="c"># /compact の要約は安いモデルへ</span>
|
||||
|
||||
@@ -175,6 +175,7 @@
|
||||
<tr><td>In turn <code>rotate</code></td><td>Each conversation’s next turn goes to the next member’s account or key, spreading the load.</td></tr>
|
||||
<tr><td>Least used <code>usage</code></td><td>The account or key with the most of its allowance left.</td></tr>
|
||||
<tr><td>Weekly pace <code>pace</code></td><td>The account with the most of its week left per hour until it renews — the one with the most to lose at its reset — so less of each member’s week is lost at its reset; an account with five hours and no week (Claude Enterprise) by what its five hours have left per hour until they renew, so almost always first. One at 90% or more waits until the others can’t answer. A key by the tokens sent it lately.</td></tr>
|
||||
<tr><td>By weight <code>weight</code></td><td>Each model takes its share of the requests by the weight set beside it in the group editor (1 to 1000, 1 if unset): one weighing 3 takes three for every one a model weighing 1 takes, spread out rather than in bursts. Each model is tried whole over its own accounts or keys, as its provider routes them, and a group in the group counts as one. One resting after a failure leaves the round; the next model is the fallback when one fails.</td></tr>
|
||||
</table></div>
|
||||
<div class="table-wrap"><table>
|
||||
<tr><th>Stays</th><th>How long a conversation stays with the account or key that answered it</th></tr>
|
||||
@@ -217,6 +218,7 @@
|
||||
<pre id="ex-group">magpie groups <span class="c"># yours, then those magpie found</span>
|
||||
magpie group add <span class="s">"Opus anywhere"</span> models=claude/claude-opus-5-5,copilot/claude-opus-5.5 routing=order stays=session
|
||||
magpie group set opus-anywhere models+=openrouter/anthropic/claude-opus-5.5
|
||||
magpie group set opus-anywhere routing=weight weight=claude/claude-opus-5-5=3 <span class="c"># three of every four requests to it</span>
|
||||
magpie group rule add opus-anywhere use=openrouter/anthropic/claude-opus-5.5 tokens=150k <span class="c"># long turns to it first</span>
|
||||
magpie group rule add opus-anywhere use=copilot/claude-opus-5.5 intent=<span class="s">"a quick question"</span> classifier=groq/llama-3.1-8b-instant
|
||||
magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash compact <span class="c"># /compact summaries to a cheap model</span>
|
||||
|
||||
@@ -175,6 +175,7 @@
|
||||
<tr><td>轮流 <code>rotate</code></td><td>会话的每一轮交给下一个成员的账号或 Key,均摊负载。</td></tr>
|
||||
<tr><td>最少使用 <code>usage</code></td><td>剩余额度最多的账号或 Key 排第一。</td></tr>
|
||||
<tr><td>重置前用完 <code>pace</code></td><td>每周剩余额度除以距重置的小时数,最高的账号排第一——重置时损失最多的那个——少让成员的周额度到重置时作废;只有 5 小时额度、没有周额度的账号(如 Claude Enterprise)按 5 小时窗口的剩余额度除以距它重置的小时数算,所以几乎总排第一。用到 90% 以上的等其他账号都答不了时才用。Key 按最近发给它的 token 数排。</td></tr>
|
||||
<tr><td>按权重 <code>weight</code></td><td>每个模型按群组编辑器里它旁边设的权重(1 到 1000,不设为 1)分得请求:权重 3 的模型每拿三个,权重 1 的拿一个,均匀穿插而不是成批。每个模型按它自己提供方的路由用自己的账号或 Key,群组里的群组算一个成员。失败后歇着的那个退出这一轮;一个失败时,下一个模型接上。</td></tr>
|
||||
</table></div>
|
||||
<div class="table-wrap"><table>
|
||||
<tr><th>会话保持</th><th>会话在回答过它的账号或 Key 上留多久</th></tr>
|
||||
@@ -217,6 +218,7 @@
|
||||
<pre id="ex-group">magpie groups <span class="c"># 先列你建的,再列 magpie 自动发现的</span>
|
||||
magpie group add <span class="s">"Opus anywhere"</span> models=claude/claude-opus-5-5,copilot/claude-opus-5.5 routing=order stays=session
|
||||
magpie group set opus-anywhere models+=openrouter/anthropic/claude-opus-5.5
|
||||
magpie group set opus-anywhere routing=weight weight=claude/claude-opus-5-5=3 <span class="c"># 每四个请求有三个给它</span>
|
||||
magpie group rule add opus-anywhere use=openrouter/anthropic/claude-opus-5.5 tokens=150k <span class="c"># 长对话优先发给它</span>
|
||||
magpie group rule add opus-anywhere use=copilot/claude-opus-5.5 intent=<span class="s">"一个简单问题"</span> classifier=groq/llama-3.1-8b-instant
|
||||
magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash compact <span class="c"># /compact 的总结交给便宜的模型</span>
|
||||
|
||||
Reference in New Issue
Block a user