diff --git a/docs/reference.md b/docs/reference.md index 7428e6979..480093668 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -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 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 diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index ae9355a9d..758c702e7 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -19,7 +19,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md). | HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), `/mcp/{name}`, `/mcp/magpie/web-search` and `/mcp/magpie/vision` (magpie's own web search and image recognition as MCP servers, below) and the `/v1/magpie/*` status endpoints. A GET on `/v1/responses` (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). A browser extension's own pages, popup and service worker are listed the same way by their origin, which is the browser's scheme and the extension's id: `chrome-extension://` (Chromium, the id 32 letters a–p), `moz-extension://` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://` (Safari, which picks a new UUID on each launch, so a listing lasts until Safari restarts); the id must have that browser's shape, cased any way, and nothing else is taken — no bare scheme, no wildcard, no path (SkyAerope on Discord: an extension without host permissions is held to CORS like a page). A content script's fetch carries the page's origin, not the extension's. A listed extension is treated exactly as a listed page, below; one not listed passes as before (other schemes, below) with no CORS headers. For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. `null` and other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost`, `*.localhost`, a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). Next, before the key or `rebound` is looked at, the allow list (lc on Discord, magpie in Docker on a public host): with `MAGPIE_ALLOW_IPS` or Settings › Network › Allowed addresses (`settings.AllowIPs`; the variable wins and the page then only shows it) naming IPs and CIDR ranges, a request whose connection (`RemoteAddr`, IPv4-mapped IPv6 unmapped, zone dropped) is outside them is refused 403 naming its address, even with an enabled gateway key (`refuseNotAllowed`). Loopback and this computer's own interface addresses always pass. A forwarding header is never taken for the address, so a proxy or tunnel on this computer passes (it arrives from loopback) and its clients are limited at the proxy. An entry that doesn't parse lets nothing in and is logged once; the list stays on. Settings' list is read with `settings.LoadChecked`: a settings.json that can't be read, or doesn't parse with no last good generation, is unknown, never "no list", so the list read last in this process stays in force (`lastAllow`), and with none read yet only this computer passes, the 403 saying settings.json couldn't be read; logged once. No file, or an empty one, is no list. The Settings page's saves read with `LoadChecked` too and refuse such a file, as `settings.Save` does. `magpie web`'s server is wrapped in the same check (`AllowGuard`). Settings refuses a list that would leave out the address the page saving it is open from (`KeepsOut`). | [`gateway.go`](../../internal/gateway/gateway.go), [`allow.go`](../../internal/gateway/allow.go), [`internal/settings/allowips.go`](../../internal/settings/allowips.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) | | Model resolution | `serve` resolves the model the agent asked for: Claude tier stand-ins, a routing group (`provider.GroupFor`: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id), auto stand-ins, the agent's own stand-in (`StandIn`: Codex's config.toml `model` when magpie is its provider, for a name it sends that magpie doesn't serve, such as its auto-review's `codex-auto-review`), itself taken through `GroupFor` and auto stand-ins so a config naming a group bare reaches it, then `provider.Resolve`. A Codex memory call or auto-review (`x-openai-subagent: guardian`, or `codex-auto-review`) that still names no served model goes to the model Codex's last turn was answered on (`codexMemoryStandIn`, per agent and gateway key), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, `TestCodexAutoReviewReachesItsTurnsModel`). A bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api) is never refused: with found groups on (the default) `GroupFor` takes it to the group magpie found for it (`auto-`), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, `Resolve` takes the first provider in the Providers order that exposes it, with no fallback. magpie writes only `provider/model` ids into agents' configs (`magpieModels`), so a bare id is one the user wrote. Every reply says who answered in `X-Magpie-Provider` and `X-Magpie-Model` (`noteMember`), and the usage log and the Routing page keep it. A model id with `~` and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as `~` (`unflat`, `provider.Unflat`; MiniMax Code's spelling, #1387), taken back in `validateModel` before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (`relay/claude-opus-4-6-us`, with or without `:level` and `[1m]`) that is not served as spelled is the one served id it dashes (`provider.ClaudeUndashed`; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in `validateModel` and `unprefixed` the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (`provider.Closest`: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told `opencode-zen-free/space-bunny-free`, MOMO on Discord), then the ways a model can be named, then every id (`unknownModel`; chat and embeddings). | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.go), [`internal/provider/flat.go`](../../internal/provider/flat.go), [`internal/provider/claudedash.go`](../../internal/provider/claudedash.go) | | Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576). So does a member whose provider routes other than Smart (`ownRouting`): weighed as one by its first not resting (`firstAwake`), tried whole in its own order; `leastHeld` leaves such a group's order alone too. A provider on Smart, or routed as the group is, is pooled with the group's other keys and accounts. `group_own_routing_test.go`. A member's own fallbacks are not the group's. | [`fallback.go`](../../internal/gateway/fallback.go) | -| Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace` or `weight` (`weightedFirst`). Smart, `usage` and `pace` weigh a subscription by its allowance (`allowances`), and a key by its own usage windows when magpie reads them (`keyAllowance`: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/provider/routing.go`](../../internal/provider/routing.go) | +| Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace` or `weight` (`weightedFirst`). Smart, `usage` and `pace` weigh a subscription by its allowance (`allowances`), and a key by its own usage windows when magpie reads them (`keyAllowance`: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. A group routed `weight` (#1910) takes its members, not their keys, by smooth weighted round robin: `planLevel` makes each model member (its keys ordered by its own provider's routing) and each nested group one unit, and `weightedUnits` puts the round's pick (`group/`, keyed by the member's spelling, `Group.Weights`, 1 if unset) first and the rest in member order for failover; a unit whose head rests leaves the round, and a kept conversation moves the round's charge to the member that kept it (`wrrSeat`, `wrrMove`). A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). A failure rests a candidate (`failure`, `failureOf`). A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/provider/routing.go`](../../internal/provider/routing.go) | | Limits | Each key or account (a candidate's `who()`) has at most `MaxConcurrency` requests out at once (its own `AccountConcurrency` over it); one more waits in its lane's queue, bounded by `QueueLimit` and `QueueWait` and turned away with a 429 past either (`lanes.take`). `MaxRPM` (coeo91 on Discord: OpenRouter's free models take 20 a minute) bounds how many requests it sends the vendor in any rolling 60 seconds (`rpms`), counting each for a second more (`rpmSlack`), since the vendor counts a request when it arrives and the first on a new connection arrives later by its dial: one more waits for room in the minute, in the order they came, after it has its slot and right before it is sent. A wait that would be longer than 2 minutes (or the provider's `QueueWait`, when shorter: `rpmWait`) is turned away at once with a 429 whose `Retry-After` is when the minute has room; nothing rests for it. An agent gone while it waits gives its place back. Every request that reaches the vendor counts: each try of the candidate loop (a retry, the next key, a fallback) waits in `serve`, and the requests a try makes on the way and the gateway's own asks (count_tokens, System One's decisions, embeddings, drawing, Kimi's search) are counted by `rpmTransport` on `s.client` (`metered`, `paidFor`). count_tokens never waits: a candidate with no room is skipped, and the local estimate answers. A full lane or a minute with no room gives way to a ready key or account of the provider or the group (`laneMate`, `ready`); a fallback is never asked for want of either. A plugin's account sends through its own transport, so only its tries are counted, not a plugin's own extra requests. Set in the provider editor (Concurrency, Requests per minute, Queue size, Queue wait) or with `magpie provider account-concurrency`, `queue` and `rpm`; a subscription's are kept with its picks, and every account of it keeps them, those on beside the first as well (`withPicks`, called by `All` and `AlsoOn`; #1899: a second WorkBuddy AI account had none, and queued 62s with the wait set to 1s). | [`concurrency.go`](../../internal/gateway/concurrency.go), [`rpm.go`](../../internal/gateway/rpm.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | | Sink | With `Sink` on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart. | [`sink.go`](../../internal/gateway/sink.go) | | Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`, `strict`. Stored in `affinity.json` next to `providers.json`. | [`affinity.go`](../../internal/gateway/affinity.go) | diff --git a/internal/cli/groups_cli.go b/internal/cli/groups_cli.go index a3d0bc6b4..fe5794ec4 100644 --- a/internal/cli/groups_cli.go +++ b/internal/cli/groups_cli.go @@ -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=|group/, pick= (routing=manual, every request to that one of its models), fast=[,m2…] (the models sent in their vendor's fast mode; empty for none), + weight==[,m2=…] (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 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==, 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" } diff --git a/internal/cli/groups_weight_cli_test.go b/internal/cli/groups_weight_cli_test.go new file mode 100644 index 000000000..0dab36c1d --- /dev/null +++ b/internal/cli/groups_weight_cli_test.go @@ -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) + } +} diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index b24738680..83d63fd1e 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -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 diff --git a/internal/gateway/weighted.go b/internal/gateway/weighted.go index f7ff48095..7b259b79d 100644 --- a/internal/gateway/weighted.go +++ b/internal/gateway/weighted.go @@ -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 } diff --git a/internal/gateway/weighted_group_test.go b/internal/gateway/weighted_group_test.go new file mode 100644 index 000000000..6959d5a17 --- /dev/null +++ b/internal/gateway/weighted_group_test.go @@ -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) + } +} diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 469a074ee..e2162a946 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -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.", diff --git a/internal/gui/assets/routing.css b/internal/gui/assets/routing.css index 67faa1015..d6e3c9360 100644 --- a/internal/gui/assets/routing.css +++ b/internal/gui/assets/routing.css @@ -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 diff --git a/internal/gui/assets/routing.js b/internal/gui/assets/routing.js index 826bf5f56..173014cc8 100644 --- a/internal/gui/assets/routing.js +++ b/internal/gui/assets/routing.js @@ -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 diff --git a/internal/gui/tests/group-member-weight.test.cjs b/internal/gui/tests/group-member-weight.test.cjs new file mode 100644 index 000000000..578f2a308 --- /dev/null +++ b/internal/gui/tests/group-member-weight.test.cjs @@ -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, []); + }); + } +} diff --git a/internal/provider/group.go b/internal/provider/group.go index 3095c346d..8bef6d110 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -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 } diff --git a/internal/provider/group_share.go b/internal/provider/group_share.go index a300f6b58..09ee7b5a6 100644 --- a/internal/provider/group_share.go +++ b/internal/provider/group_share.go @@ -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 } diff --git a/internal/provider/groupfast.go b/internal/provider/groupfast.go index 6cca554dd..80bd908c7 100644 --- a/internal/provider/groupfast.go +++ b/internal/provider/groupfast.go @@ -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 + }) } diff --git a/internal/provider/groupweight.go b/internal/provider/groupweight.go new file mode 100644 index 000000000..a0f039de5 --- /dev/null +++ b/internal/provider/groupweight.go @@ -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 +} diff --git a/internal/provider/groupweight_test.go b/internal/provider/groupweight_test.go new file mode 100644 index 000000000..fe34ce2c3 --- /dev/null +++ b/internal/provider/groupweight_test.go @@ -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) + } +} diff --git a/internal/provider/rename.go b/internal/provider/rename.go index 6f8b27be1..1d2544314 100644 --- a/internal/provider/rename.go +++ b/internal/provider/rename.go @@ -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) } diff --git a/internal/tui/routing.go b/internal/tui/routing.go index df883abde..5ce576cb2 100644 --- a/internal/tui/routing.go +++ b/internal/tui/routing.go @@ -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 { diff --git a/site/public/docs/ja/start.html b/site/public/docs/ja/start.html index e11e46c6f..dcedd2ba6 100644 --- a/site/public/docs/ja/start.html +++ b/site/public/docs/ja/start.html @@ -175,6 +175,7 @@ 持ち回り rotate各会話の次のターンを、次のメンバーのアカウントやキーに送り、負荷を分散します。 使用量の少ない順 usage利用枠の残りが最も多いアカウントやキー。 週のペース pace更新までの 1 時間あたりの週の枠の残りが最も多いアカウント、つまりリセット時に失う分が最も多いもの。これにより各メンバーの週の枠がリセットで無駄になりにくくなります。週の枠がなく 5 時間枠だけのアカウント(Claude Enterprise)は、更新までの 1 時間あたりの 5 時間枠の残りで判断されるので、ほぼ常に最初になります。使用率が 90% 以上のものは、他が応答できなくなるまで待ちます。キーは最近送ったトークン数で判断します。 + 重み順 weightグループ編集画面で各モデルの横に設定した重み(1〜1000、未設定は 1)に応じてリクエストを分けます。重み 3 のモデルは重み 1 のモデルが 1 件受けるごとに 3 件受け、まとめてではなく均等に散らします。各モデルは自分のプロバイダーのルーティングで自分のアカウントやキーを使い、グループ内のグループは 1 つとして数えます。失敗して休んでいるものはその回から外れ、失敗したときは次のモデルが代わりに答えます。
@@ -217,6 +218,7 @@
magpie groups                        # 自分のグループ、次に magpie が見つけたもの
 magpie group add "Opus anywhere" 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  # 4 件に 3 件をこれに
 magpie group rule add opus-anywhere use=openrouter/anthropic/claude-opus-5.5 tokens=150k  # 長いターンはまずこれへ
 magpie group rule add opus-anywhere use=copilot/claude-opus-5.5 intent="ちょっとした質問" classifier=groq/llama-3.1-8b-instant
 magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash compact  # /compact の要約は安いモデルへ
diff --git a/site/public/docs/start.html b/site/public/docs/start.html
index bae8769ad..7f8def4b2 100644
--- a/site/public/docs/start.html
+++ b/site/public/docs/start.html
@@ -175,6 +175,7 @@
       
+
維持会話が、応答したアカウントやキーに留まる期間
In turn rotateEach conversation’s next turn goes to the next member’s account or key, spreading the load.
Least used usageThe account or key with the most of its allowance left.
Weekly pace paceThe 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.
By weight weightEach 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.
@@ -217,6 +218,7 @@
magpie groups                        # yours, then those magpie found
 magpie group add "Opus anywhere" 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  # three of every four requests to it
 magpie group rule add opus-anywhere use=openrouter/anthropic/claude-opus-5.5 tokens=150k  # long turns to it first
 magpie group rule add opus-anywhere use=copilot/claude-opus-5.5 intent="a quick question" classifier=groq/llama-3.1-8b-instant
 magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash compact  # /compact summaries to a cheap model
diff --git a/site/public/docs/zh/start.html b/site/public/docs/zh/start.html
index 77d3a6383..efe767b00 100644
--- a/site/public/docs/zh/start.html
+++ b/site/public/docs/zh/start.html
@@ -175,6 +175,7 @@
       
+
StaysHow long a conversation stays with the account or key that answered it
轮流 rotate会话的每一轮交给下一个成员的账号或 Key,均摊负载。
最少使用 usage剩余额度最多的账号或 Key 排第一。
重置前用完 pace每周剩余额度除以距重置的小时数,最高的账号排第一——重置时损失最多的那个——少让成员的周额度到重置时作废;只有 5 小时额度、没有周额度的账号(如 Claude Enterprise)按 5 小时窗口的剩余额度除以距它重置的小时数算,所以几乎总排第一。用到 90% 以上的等其他账号都答不了时才用。Key 按最近发给它的 token 数排。
按权重 weight每个模型按群组编辑器里它旁边设的权重(1 到 1000,不设为 1)分得请求:权重 3 的模型每拿三个,权重 1 的拿一个,均匀穿插而不是成批。每个模型按它自己提供方的路由用自己的账号或 Key,群组里的群组算一个成员。失败后歇着的那个退出这一轮;一个失败时,下一个模型接上。
@@ -217,6 +218,7 @@
magpie groups                        # 先列你建的,再列 magpie 自动发现的
 magpie group add "Opus anywhere" 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  # 每四个请求有三个给它
 magpie group rule add opus-anywhere use=openrouter/anthropic/claude-opus-5.5 tokens=150k  # 长对话优先发给它
 magpie group rule add opus-anywhere use=copilot/claude-opus-5.5 intent="一个简单问题" classifier=groq/llama-3.1-8b-instant
 magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash compact  # /compact 的总结交给便宜的模型
会话保持会话在回答过它的账号或 Key 上留多久